babylon.max.js 2.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.Forward = function () {
  834. return new Vector3(0, 0, 1.0);
  835. };
  836. Vector3.Right = function () {
  837. return new Vector3(1.0, 0, 0);
  838. };
  839. Vector3.Left = function () {
  840. return new Vector3(-1.0, 0, 0);
  841. };
  842. Vector3.TransformCoordinates = function (vector, transformation) {
  843. var result = Vector3.Zero();
  844. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  845. return result;
  846. };
  847. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  848. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  849. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  850. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  851. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  852. result.x = x / w;
  853. result.y = y / w;
  854. result.z = z / w;
  855. };
  856. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  857. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  858. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  859. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  860. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  861. result.x = rx / rw;
  862. result.y = ry / rw;
  863. result.z = rz / rw;
  864. };
  865. Vector3.TransformNormal = function (vector, transformation) {
  866. var result = Vector3.Zero();
  867. Vector3.TransformNormalToRef(vector, transformation, result);
  868. return result;
  869. };
  870. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  871. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  872. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  873. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  874. result.x = x;
  875. result.y = y;
  876. result.z = z;
  877. };
  878. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  879. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  880. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  881. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  882. };
  883. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  884. var squared = amount * amount;
  885. var cubed = amount * squared;
  886. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  887. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  888. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  889. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  890. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  891. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  892. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  893. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  894. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Clamp = function (value, min, max) {
  898. var x = value.x;
  899. x = (x > max.x) ? max.x : x;
  900. x = (x < min.x) ? min.x : x;
  901. var y = value.y;
  902. y = (y > max.y) ? max.y : y;
  903. y = (y < min.y) ? min.y : y;
  904. var z = value.z;
  905. z = (z > max.z) ? max.z : z;
  906. z = (z < min.z) ? min.z : z;
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  910. var squared = amount * amount;
  911. var cubed = amount * squared;
  912. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  913. var part2 = (-2.0 * cubed) + (3.0 * squared);
  914. var part3 = (cubed - (2.0 * squared)) + amount;
  915. var part4 = cubed - squared;
  916. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  917. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  918. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  919. return new Vector3(x, y, z);
  920. };
  921. Vector3.Lerp = function (start, end, amount) {
  922. var x = start.x + ((end.x - start.x) * amount);
  923. var y = start.y + ((end.y - start.y) * amount);
  924. var z = start.z + ((end.z - start.z) * amount);
  925. return new Vector3(x, y, z);
  926. };
  927. Vector3.Dot = function (left, right) {
  928. return (left.x * right.x + left.y * right.y + left.z * right.z);
  929. };
  930. Vector3.Cross = function (left, right) {
  931. var result = Vector3.Zero();
  932. Vector3.CrossToRef(left, right, result);
  933. return result;
  934. };
  935. Vector3.CrossToRef = function (left, right, result) {
  936. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  937. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  938. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  939. result.copyFrom(Tmp.Vector3[0]);
  940. };
  941. Vector3.Normalize = function (vector) {
  942. var result = Vector3.Zero();
  943. Vector3.NormalizeToRef(vector, result);
  944. return result;
  945. };
  946. Vector3.NormalizeToRef = function (vector, result) {
  947. result.copyFrom(vector);
  948. result.normalize();
  949. };
  950. Vector3.Project = function (vector, world, transform, viewport) {
  951. var cw = viewport.width;
  952. var ch = viewport.height;
  953. var cx = viewport.x;
  954. var cy = viewport.y;
  955. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  956. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  957. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  958. world.multiplyToRef(transform, matrix);
  959. matrix.multiplyToRef(viewportMatrix, matrix);
  960. return Vector3.TransformCoordinates(vector, matrix);
  961. };
  962. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  963. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  964. world.multiplyToRef(transform, matrix);
  965. matrix.invert();
  966. source.x = source.x / viewportWidth * 2 - 1;
  967. source.y = -(source.y / viewportHeight * 2 - 1);
  968. var vector = Vector3.TransformCoordinates(source, matrix);
  969. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  970. if (MathTools.WithinEpsilon(num, 1.0)) {
  971. vector = vector.scale(1.0 / num);
  972. }
  973. return vector;
  974. };
  975. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  976. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  977. world.multiplyToRef(view, matrix);
  978. matrix.multiplyToRef(projection, matrix);
  979. matrix.invert();
  980. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  981. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  982. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  983. if (MathTools.WithinEpsilon(num, 1.0)) {
  984. vector = vector.scale(1.0 / num);
  985. }
  986. return vector;
  987. };
  988. Vector3.Minimize = function (left, right) {
  989. var min = left.clone();
  990. min.MinimizeInPlace(right);
  991. return min;
  992. };
  993. Vector3.Maximize = function (left, right) {
  994. var max = left.clone();
  995. max.MaximizeInPlace(right);
  996. return max;
  997. };
  998. Vector3.Distance = function (value1, value2) {
  999. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1000. };
  1001. Vector3.DistanceSquared = function (value1, value2) {
  1002. var x = value1.x - value2.x;
  1003. var y = value1.y - value2.y;
  1004. var z = value1.z - value2.z;
  1005. return (x * x) + (y * y) + (z * z);
  1006. };
  1007. Vector3.Center = function (value1, value2) {
  1008. var center = value1.add(value2);
  1009. center.scaleInPlace(0.5);
  1010. return center;
  1011. };
  1012. /**
  1013. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1014. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1015. * to something in order to rotate it from its local system to the given target system.
  1016. */
  1017. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1018. var rotation = Vector3.Zero();
  1019. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1020. return rotation;
  1021. };
  1022. /**
  1023. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1024. */
  1025. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1026. var u = axis1.normalize();
  1027. var w = axis3.normalize();
  1028. // world axis
  1029. var X = Axis.X;
  1030. var Y = Axis.Y;
  1031. // equation unknowns and vars
  1032. var yaw = 0.0;
  1033. var pitch = 0.0;
  1034. var roll = 0.0;
  1035. var x = 0.0;
  1036. var y = 0.0;
  1037. var z = 0.0;
  1038. var t = 0.0;
  1039. var sign = -1.0;
  1040. var nbRevert = 0;
  1041. var cross = Tmp.Vector3[0];
  1042. var dot = 0.0;
  1043. // step 1 : rotation around w
  1044. // Rv3(u) = u1, and u1 belongs to plane xOz
  1045. // Rv3(w) = w1 = w invariant
  1046. var u1 = Tmp.Vector3[1];
  1047. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1048. z = 1.0;
  1049. }
  1050. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1051. x = 1.0;
  1052. }
  1053. else {
  1054. t = w.z / w.x;
  1055. x = -t * Math.sqrt(1 / (1 + t * t));
  1056. z = Math.sqrt(1 / (1 + t * t));
  1057. }
  1058. u1.x = x;
  1059. u1.y = y;
  1060. u1.z = z;
  1061. u1.normalize();
  1062. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1063. cross.normalize();
  1064. if (Vector3.Dot(w, cross) < 0) {
  1065. sign = 1.0;
  1066. }
  1067. dot = Vector3.Dot(u, u1);
  1068. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1069. roll = Math.acos(dot) * sign;
  1070. if (Vector3.Dot(u1, X) < 0) {
  1071. roll = Math.PI + roll;
  1072. u1 = u1.scaleInPlace(-1);
  1073. nbRevert++;
  1074. }
  1075. // step 2 : rotate around u1
  1076. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1077. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1078. var w2 = Tmp.Vector3[2];
  1079. var v2 = Tmp.Vector3[3];
  1080. x = 0.0;
  1081. y = 0.0;
  1082. z = 0.0;
  1083. sign = -1.0;
  1084. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1085. x = 1.0;
  1086. }
  1087. else {
  1088. t = u1.z / u1.x;
  1089. x = -t * Math.sqrt(1 / (1 + t * t));
  1090. z = Math.sqrt(1 / (1 + t * t));
  1091. }
  1092. w2.x = x;
  1093. w2.y = y;
  1094. w2.z = z;
  1095. w2.normalize();
  1096. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1097. v2.normalize();
  1098. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1099. cross.normalize();
  1100. if (Vector3.Dot(u1, cross) < 0) {
  1101. sign = 1.0;
  1102. }
  1103. dot = Vector3.Dot(w, w2);
  1104. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1105. pitch = Math.acos(dot) * sign;
  1106. if (Vector3.Dot(v2, Y) < 0) {
  1107. pitch = Math.PI + pitch;
  1108. nbRevert++;
  1109. }
  1110. // step 3 : rotate around v2
  1111. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1112. sign = -1.0;
  1113. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1114. cross.normalize();
  1115. if (Vector3.Dot(cross, Y) < 0) {
  1116. sign = 1.0;
  1117. }
  1118. dot = Vector3.Dot(u1, X);
  1119. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1120. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1121. if (dot < 0 && nbRevert < 2) {
  1122. yaw = Math.PI + yaw;
  1123. }
  1124. ref.x = pitch;
  1125. ref.y = yaw;
  1126. ref.z = roll;
  1127. };
  1128. return Vector3;
  1129. }());
  1130. BABYLON.Vector3 = Vector3;
  1131. //Vector4 class created for EulerAngle class conversion to Quaternion
  1132. var Vector4 = (function () {
  1133. function Vector4(x, y, z, w) {
  1134. this.x = x;
  1135. this.y = y;
  1136. this.z = z;
  1137. this.w = w;
  1138. }
  1139. Vector4.prototype.toString = function () {
  1140. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1141. };
  1142. Vector4.prototype.getClassName = function () {
  1143. return "Vector4";
  1144. };
  1145. Vector4.prototype.getHashCode = function () {
  1146. var hash = this.x || 0;
  1147. hash = (hash * 397) ^ (this.y || 0);
  1148. hash = (hash * 397) ^ (this.z || 0);
  1149. hash = (hash * 397) ^ (this.w || 0);
  1150. return hash;
  1151. };
  1152. // Operators
  1153. Vector4.prototype.asArray = function () {
  1154. var result = [];
  1155. this.toArray(result, 0);
  1156. return result;
  1157. };
  1158. Vector4.prototype.toArray = function (array, index) {
  1159. if (index === undefined) {
  1160. index = 0;
  1161. }
  1162. array[index] = this.x;
  1163. array[index + 1] = this.y;
  1164. array[index + 2] = this.z;
  1165. array[index + 3] = this.w;
  1166. return this;
  1167. };
  1168. Vector4.prototype.addInPlace = function (otherVector) {
  1169. this.x += otherVector.x;
  1170. this.y += otherVector.y;
  1171. this.z += otherVector.z;
  1172. this.w += otherVector.w;
  1173. return this;
  1174. };
  1175. Vector4.prototype.add = function (otherVector) {
  1176. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1177. };
  1178. Vector4.prototype.addToRef = function (otherVector, result) {
  1179. result.x = this.x + otherVector.x;
  1180. result.y = this.y + otherVector.y;
  1181. result.z = this.z + otherVector.z;
  1182. result.w = this.w + otherVector.w;
  1183. return this;
  1184. };
  1185. Vector4.prototype.subtractInPlace = function (otherVector) {
  1186. this.x -= otherVector.x;
  1187. this.y -= otherVector.y;
  1188. this.z -= otherVector.z;
  1189. this.w -= otherVector.w;
  1190. return this;
  1191. };
  1192. Vector4.prototype.subtract = function (otherVector) {
  1193. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1194. };
  1195. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1196. result.x = this.x - otherVector.x;
  1197. result.y = this.y - otherVector.y;
  1198. result.z = this.z - otherVector.z;
  1199. result.w = this.w - otherVector.w;
  1200. return this;
  1201. };
  1202. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1203. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1204. };
  1205. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1206. result.x = this.x - x;
  1207. result.y = this.y - y;
  1208. result.z = this.z - z;
  1209. result.w = this.w - w;
  1210. return this;
  1211. };
  1212. Vector4.prototype.negate = function () {
  1213. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1214. };
  1215. Vector4.prototype.scaleInPlace = function (scale) {
  1216. this.x *= scale;
  1217. this.y *= scale;
  1218. this.z *= scale;
  1219. this.w *= scale;
  1220. return this;
  1221. };
  1222. Vector4.prototype.scale = function (scale) {
  1223. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1224. };
  1225. Vector4.prototype.scaleToRef = function (scale, result) {
  1226. result.x = this.x * scale;
  1227. result.y = this.y * scale;
  1228. result.z = this.z * scale;
  1229. result.w = this.w * scale;
  1230. };
  1231. Vector4.prototype.equals = function (otherVector) {
  1232. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1233. };
  1234. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1235. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1236. return otherVector
  1237. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1238. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1239. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1240. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1241. };
  1242. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1243. return this.x === x && this.y === y && this.z === z && this.w === w;
  1244. };
  1245. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1246. this.x *= otherVector.x;
  1247. this.y *= otherVector.y;
  1248. this.z *= otherVector.z;
  1249. this.w *= otherVector.w;
  1250. return this;
  1251. };
  1252. Vector4.prototype.multiply = function (otherVector) {
  1253. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1254. };
  1255. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1256. result.x = this.x * otherVector.x;
  1257. result.y = this.y * otherVector.y;
  1258. result.z = this.z * otherVector.z;
  1259. result.w = this.w * otherVector.w;
  1260. return this;
  1261. };
  1262. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1263. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1264. };
  1265. Vector4.prototype.divide = function (otherVector) {
  1266. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1267. };
  1268. Vector4.prototype.divideToRef = function (otherVector, result) {
  1269. result.x = this.x / otherVector.x;
  1270. result.y = this.y / otherVector.y;
  1271. result.z = this.z / otherVector.z;
  1272. result.w = this.w / otherVector.w;
  1273. return this;
  1274. };
  1275. Vector4.prototype.MinimizeInPlace = function (other) {
  1276. if (other.x < this.x)
  1277. this.x = other.x;
  1278. if (other.y < this.y)
  1279. this.y = other.y;
  1280. if (other.z < this.z)
  1281. this.z = other.z;
  1282. if (other.w < this.w)
  1283. this.w = other.w;
  1284. return this;
  1285. };
  1286. Vector4.prototype.MaximizeInPlace = function (other) {
  1287. if (other.x > this.x)
  1288. this.x = other.x;
  1289. if (other.y > this.y)
  1290. this.y = other.y;
  1291. if (other.z > this.z)
  1292. this.z = other.z;
  1293. if (other.w > this.w)
  1294. this.w = other.w;
  1295. return this;
  1296. };
  1297. // Properties
  1298. Vector4.prototype.length = function () {
  1299. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1300. };
  1301. Vector4.prototype.lengthSquared = function () {
  1302. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1303. };
  1304. // Methods
  1305. Vector4.prototype.normalize = function () {
  1306. var len = this.length();
  1307. if (len === 0)
  1308. return this;
  1309. var num = 1.0 / len;
  1310. this.x *= num;
  1311. this.y *= num;
  1312. this.z *= num;
  1313. this.w *= num;
  1314. return this;
  1315. };
  1316. Vector4.prototype.toVector3 = function () {
  1317. return new Vector3(this.x, this.y, this.z);
  1318. };
  1319. Vector4.prototype.clone = function () {
  1320. return new Vector4(this.x, this.y, this.z, this.w);
  1321. };
  1322. Vector4.prototype.copyFrom = function (source) {
  1323. this.x = source.x;
  1324. this.y = source.y;
  1325. this.z = source.z;
  1326. this.w = source.w;
  1327. return this;
  1328. };
  1329. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. // Statics
  1337. Vector4.FromArray = function (array, offset) {
  1338. if (!offset) {
  1339. offset = 0;
  1340. }
  1341. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1342. };
  1343. Vector4.FromArrayToRef = function (array, offset, result) {
  1344. result.x = array[offset];
  1345. result.y = array[offset + 1];
  1346. result.z = array[offset + 2];
  1347. result.w = array[offset + 3];
  1348. };
  1349. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1350. result.x = array[offset];
  1351. result.y = array[offset + 1];
  1352. result.z = array[offset + 2];
  1353. result.w = array[offset + 3];
  1354. };
  1355. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1356. result.x = x;
  1357. result.y = y;
  1358. result.z = z;
  1359. result.w = w;
  1360. };
  1361. Vector4.Zero = function () {
  1362. return new Vector4(0, 0, 0, 0);
  1363. };
  1364. Vector4.Normalize = function (vector) {
  1365. var result = Vector4.Zero();
  1366. Vector4.NormalizeToRef(vector, result);
  1367. return result;
  1368. };
  1369. Vector4.NormalizeToRef = function (vector, result) {
  1370. result.copyFrom(vector);
  1371. result.normalize();
  1372. };
  1373. Vector4.Minimize = function (left, right) {
  1374. var min = left.clone();
  1375. min.MinimizeInPlace(right);
  1376. return min;
  1377. };
  1378. Vector4.Maximize = function (left, right) {
  1379. var max = left.clone();
  1380. max.MaximizeInPlace(right);
  1381. return max;
  1382. };
  1383. Vector4.Distance = function (value1, value2) {
  1384. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1385. };
  1386. Vector4.DistanceSquared = function (value1, value2) {
  1387. var x = value1.x - value2.x;
  1388. var y = value1.y - value2.y;
  1389. var z = value1.z - value2.z;
  1390. var w = value1.w - value2.w;
  1391. return (x * x) + (y * y) + (z * z) + (w * w);
  1392. };
  1393. Vector4.Center = function (value1, value2) {
  1394. var center = value1.add(value2);
  1395. center.scaleInPlace(0.5);
  1396. return center;
  1397. };
  1398. return Vector4;
  1399. }());
  1400. BABYLON.Vector4 = Vector4;
  1401. var Size = (function () {
  1402. function Size(width, height) {
  1403. this.width = width;
  1404. this.height = height;
  1405. }
  1406. Size.prototype.toString = function () {
  1407. return "{W: " + this.width + ", H: " + this.height + "}";
  1408. };
  1409. Size.prototype.getClassName = function () {
  1410. return "Size";
  1411. };
  1412. Size.prototype.getHashCode = function () {
  1413. var hash = this.width || 0;
  1414. hash = (hash * 397) ^ (this.height || 0);
  1415. return hash;
  1416. };
  1417. Size.prototype.copyFrom = function (src) {
  1418. this.width = src.width;
  1419. this.height = src.height;
  1420. };
  1421. Size.prototype.copyFromFloats = function (width, height) {
  1422. this.width = width;
  1423. this.height = height;
  1424. };
  1425. Size.prototype.multiplyByFloats = function (w, h) {
  1426. return new Size(this.width * w, this.height * h);
  1427. };
  1428. Size.prototype.clone = function () {
  1429. return new Size(this.width, this.height);
  1430. };
  1431. Size.prototype.equals = function (other) {
  1432. if (!other) {
  1433. return false;
  1434. }
  1435. return (this.width === other.width) && (this.height === other.height);
  1436. };
  1437. Object.defineProperty(Size.prototype, "surface", {
  1438. get: function () {
  1439. return this.width * this.height;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Size.Zero = function () {
  1445. return new Size(0, 0);
  1446. };
  1447. Size.prototype.add = function (otherSize) {
  1448. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1449. return r;
  1450. };
  1451. Size.prototype.substract = function (otherSize) {
  1452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1453. return r;
  1454. };
  1455. Size.Lerp = function (start, end, amount) {
  1456. var w = start.width + ((end.width - start.width) * amount);
  1457. var h = start.height + ((end.height - start.height) * amount);
  1458. return new Size(w, h);
  1459. };
  1460. return Size;
  1461. }());
  1462. BABYLON.Size = Size;
  1463. var Quaternion = (function () {
  1464. function Quaternion(x, y, z, w) {
  1465. if (x === void 0) { x = 0; }
  1466. if (y === void 0) { y = 0; }
  1467. if (z === void 0) { z = 0; }
  1468. if (w === void 0) { w = 1; }
  1469. this.x = x;
  1470. this.y = y;
  1471. this.z = z;
  1472. this.w = w;
  1473. }
  1474. Quaternion.prototype.toString = function () {
  1475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1476. };
  1477. Quaternion.prototype.getClassName = function () {
  1478. return "Quaternion";
  1479. };
  1480. Quaternion.prototype.getHashCode = function () {
  1481. var hash = this.x || 0;
  1482. hash = (hash * 397) ^ (this.y || 0);
  1483. hash = (hash * 397) ^ (this.z || 0);
  1484. hash = (hash * 397) ^ (this.w || 0);
  1485. return hash;
  1486. };
  1487. Quaternion.prototype.asArray = function () {
  1488. return [this.x, this.y, this.z, this.w];
  1489. };
  1490. Quaternion.prototype.equals = function (otherQuaternion) {
  1491. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1492. };
  1493. Quaternion.prototype.clone = function () {
  1494. return new Quaternion(this.x, this.y, this.z, this.w);
  1495. };
  1496. Quaternion.prototype.copyFrom = function (other) {
  1497. this.x = other.x;
  1498. this.y = other.y;
  1499. this.z = other.z;
  1500. this.w = other.w;
  1501. return this;
  1502. };
  1503. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.z = z;
  1507. this.w = w;
  1508. return this;
  1509. };
  1510. Quaternion.prototype.add = function (other) {
  1511. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1512. };
  1513. Quaternion.prototype.subtract = function (other) {
  1514. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1515. };
  1516. Quaternion.prototype.scale = function (value) {
  1517. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1518. };
  1519. Quaternion.prototype.multiply = function (q1) {
  1520. var result = new Quaternion(0, 0, 0, 1.0);
  1521. this.multiplyToRef(q1, result);
  1522. return result;
  1523. };
  1524. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1525. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1526. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1527. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1528. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1529. result.copyFromFloats(x, y, z, w);
  1530. return this;
  1531. };
  1532. Quaternion.prototype.multiplyInPlace = function (q1) {
  1533. this.multiplyToRef(q1, this);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.conjugateToRef = function (ref) {
  1537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateInPlace = function () {
  1541. this.x *= -1;
  1542. this.y *= -1;
  1543. this.z *= -1;
  1544. return this;
  1545. };
  1546. Quaternion.prototype.conjugate = function () {
  1547. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1548. return result;
  1549. };
  1550. Quaternion.prototype.length = function () {
  1551. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1552. };
  1553. Quaternion.prototype.normalize = function () {
  1554. var length = 1.0 / this.length();
  1555. this.x *= length;
  1556. this.y *= length;
  1557. this.z *= length;
  1558. this.w *= length;
  1559. return this;
  1560. };
  1561. Quaternion.prototype.toEulerAngles = function (order) {
  1562. if (order === void 0) { order = "YZX"; }
  1563. var result = Vector3.Zero();
  1564. this.toEulerAnglesToRef(result, order);
  1565. return result;
  1566. };
  1567. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1568. if (order === void 0) { order = "YZX"; }
  1569. var qx = this.x;
  1570. var qy = this.y;
  1571. var qz = this.z;
  1572. var qw = this.w;
  1573. var xsqr = qx * qx;
  1574. var t0 = -2.0 * (xsqr + qy * qy) + 1.0;
  1575. var t1 = 2.0 * (qz * qx + qw * qy);
  1576. var t2 = -2.0 * (qz * qy - qw * qx);
  1577. var t3 = 2.0 * (qx * qy + qw * qz);
  1578. var t4 = -2.0 * (qz * qz + xsqr) + 1.0;
  1579. t2 = t2 > 1.0 ? 1.0 : t2;
  1580. t2 = t2 < -1.0 ? -1.0 : t2;
  1581. result.x = Math.asin(t2);
  1582. result.z = Math.atan2(t3, t4);
  1583. result.y = Math.atan2(t1, t0);
  1584. return this;
  1585. };
  1586. ;
  1587. Quaternion.prototype.toRotationMatrix = function (result) {
  1588. var xx = this.x * this.x;
  1589. var yy = this.y * this.y;
  1590. var zz = this.z * this.z;
  1591. var xy = this.x * this.y;
  1592. var zw = this.z * this.w;
  1593. var zx = this.z * this.x;
  1594. var yw = this.y * this.w;
  1595. var yz = this.y * this.z;
  1596. var xw = this.x * this.w;
  1597. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1598. result.m[1] = 2.0 * (xy + zw);
  1599. result.m[2] = 2.0 * (zx - yw);
  1600. result.m[3] = 0;
  1601. result.m[4] = 2.0 * (xy - zw);
  1602. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1603. result.m[6] = 2.0 * (yz + xw);
  1604. result.m[7] = 0;
  1605. result.m[8] = 2.0 * (zx + yw);
  1606. result.m[9] = 2.0 * (yz - xw);
  1607. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1608. result.m[11] = 0;
  1609. result.m[12] = 0;
  1610. result.m[13] = 0;
  1611. result.m[14] = 0;
  1612. result.m[15] = 1.0;
  1613. return this;
  1614. };
  1615. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1616. Quaternion.FromRotationMatrixToRef(matrix, this);
  1617. return this;
  1618. };
  1619. // Statics
  1620. Quaternion.FromRotationMatrix = function (matrix) {
  1621. var result = new Quaternion();
  1622. Quaternion.FromRotationMatrixToRef(matrix, result);
  1623. return result;
  1624. };
  1625. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1626. var data = matrix.m;
  1627. var m11 = data[0], m12 = data[4], m13 = data[8];
  1628. var m21 = data[1], m22 = data[5], m23 = data[9];
  1629. var m31 = data[2], m32 = data[6], m33 = data[10];
  1630. var trace = m11 + m22 + m33;
  1631. var s;
  1632. if (trace > 0) {
  1633. s = 0.5 / Math.sqrt(trace + 1.0);
  1634. result.w = 0.25 / s;
  1635. result.x = (m32 - m23) * s;
  1636. result.y = (m13 - m31) * s;
  1637. result.z = (m21 - m12) * s;
  1638. }
  1639. else if (m11 > m22 && m11 > m33) {
  1640. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1641. result.w = (m32 - m23) / s;
  1642. result.x = 0.25 * s;
  1643. result.y = (m12 + m21) / s;
  1644. result.z = (m13 + m31) / s;
  1645. }
  1646. else if (m22 > m33) {
  1647. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1648. result.w = (m13 - m31) / s;
  1649. result.x = (m12 + m21) / s;
  1650. result.y = 0.25 * s;
  1651. result.z = (m23 + m32) / s;
  1652. }
  1653. else {
  1654. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1655. result.w = (m21 - m12) / s;
  1656. result.x = (m13 + m31) / s;
  1657. result.y = (m23 + m32) / s;
  1658. result.z = 0.25 * s;
  1659. }
  1660. };
  1661. Quaternion.Inverse = function (q) {
  1662. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1663. };
  1664. Quaternion.Identity = function () {
  1665. return new Quaternion(0, 0, 0, 1);
  1666. };
  1667. Quaternion.RotationAxis = function (axis, angle) {
  1668. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1669. };
  1670. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1671. var sin = Math.sin(angle / 2);
  1672. axis.normalize();
  1673. result.w = Math.cos(angle / 2);
  1674. result.x = axis.x * sin;
  1675. result.y = axis.y * sin;
  1676. result.z = axis.z * sin;
  1677. return result;
  1678. };
  1679. Quaternion.FromArray = function (array, offset) {
  1680. if (!offset) {
  1681. offset = 0;
  1682. }
  1683. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1684. };
  1685. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1686. var q = new Quaternion();
  1687. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1688. return q;
  1689. };
  1690. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1691. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1692. var halfRoll = roll * 0.5;
  1693. var halfPitch = pitch * 0.5;
  1694. var halfYaw = yaw * 0.5;
  1695. var sinRoll = Math.sin(halfRoll);
  1696. var cosRoll = Math.cos(halfRoll);
  1697. var sinPitch = Math.sin(halfPitch);
  1698. var cosPitch = Math.cos(halfPitch);
  1699. var sinYaw = Math.sin(halfYaw);
  1700. var cosYaw = Math.cos(halfYaw);
  1701. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1702. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1703. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1704. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1705. };
  1706. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1707. var result = new Quaternion();
  1708. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1709. return result;
  1710. };
  1711. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1712. // Produces a quaternion from Euler angles in the z-x-z orientation
  1713. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1714. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1715. var halfBeta = beta * 0.5;
  1716. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1717. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1718. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1719. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1720. };
  1721. Quaternion.Slerp = function (left, right, amount) {
  1722. var num2;
  1723. var num3;
  1724. var num = amount;
  1725. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1726. var flag = false;
  1727. if (num4 < 0) {
  1728. flag = true;
  1729. num4 = -num4;
  1730. }
  1731. if (num4 > 0.999999) {
  1732. num3 = 1 - num;
  1733. num2 = flag ? -num : num;
  1734. }
  1735. else {
  1736. var num5 = Math.acos(num4);
  1737. var num6 = (1.0 / Math.sin(num5));
  1738. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1739. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1740. }
  1741. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1742. };
  1743. return Quaternion;
  1744. }());
  1745. BABYLON.Quaternion = Quaternion;
  1746. var Matrix = (function () {
  1747. function Matrix() {
  1748. this.m = new Float32Array(16);
  1749. }
  1750. // Properties
  1751. Matrix.prototype.isIdentity = function () {
  1752. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1753. return false;
  1754. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1755. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1756. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1757. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1758. return false;
  1759. return true;
  1760. };
  1761. Matrix.prototype.determinant = function () {
  1762. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1763. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1764. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1765. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1766. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1767. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1768. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1769. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1770. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1771. };
  1772. // Methods
  1773. Matrix.prototype.toArray = function () {
  1774. return this.m;
  1775. };
  1776. Matrix.prototype.asArray = function () {
  1777. return this.toArray();
  1778. };
  1779. Matrix.prototype.invert = function () {
  1780. this.invertToRef(this);
  1781. return this;
  1782. };
  1783. Matrix.prototype.reset = function () {
  1784. for (var index = 0; index < 16; index++) {
  1785. this.m[index] = 0;
  1786. }
  1787. return this;
  1788. };
  1789. Matrix.prototype.add = function (other) {
  1790. var result = new Matrix();
  1791. this.addToRef(other, result);
  1792. return result;
  1793. };
  1794. Matrix.prototype.addToRef = function (other, result) {
  1795. for (var index = 0; index < 16; index++) {
  1796. result.m[index] = this.m[index] + other.m[index];
  1797. }
  1798. return this;
  1799. };
  1800. Matrix.prototype.addToSelf = function (other) {
  1801. for (var index = 0; index < 16; index++) {
  1802. this.m[index] += other.m[index];
  1803. }
  1804. return this;
  1805. };
  1806. Matrix.prototype.invertToRef = function (other) {
  1807. var l1 = this.m[0];
  1808. var l2 = this.m[1];
  1809. var l3 = this.m[2];
  1810. var l4 = this.m[3];
  1811. var l5 = this.m[4];
  1812. var l6 = this.m[5];
  1813. var l7 = this.m[6];
  1814. var l8 = this.m[7];
  1815. var l9 = this.m[8];
  1816. var l10 = this.m[9];
  1817. var l11 = this.m[10];
  1818. var l12 = this.m[11];
  1819. var l13 = this.m[12];
  1820. var l14 = this.m[13];
  1821. var l15 = this.m[14];
  1822. var l16 = this.m[15];
  1823. var l17 = (l11 * l16) - (l12 * l15);
  1824. var l18 = (l10 * l16) - (l12 * l14);
  1825. var l19 = (l10 * l15) - (l11 * l14);
  1826. var l20 = (l9 * l16) - (l12 * l13);
  1827. var l21 = (l9 * l15) - (l11 * l13);
  1828. var l22 = (l9 * l14) - (l10 * l13);
  1829. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1830. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1831. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1832. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1833. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1834. var l28 = (l7 * l16) - (l8 * l15);
  1835. var l29 = (l6 * l16) - (l8 * l14);
  1836. var l30 = (l6 * l15) - (l7 * l14);
  1837. var l31 = (l5 * l16) - (l8 * l13);
  1838. var l32 = (l5 * l15) - (l7 * l13);
  1839. var l33 = (l5 * l14) - (l6 * l13);
  1840. var l34 = (l7 * l12) - (l8 * l11);
  1841. var l35 = (l6 * l12) - (l8 * l10);
  1842. var l36 = (l6 * l11) - (l7 * l10);
  1843. var l37 = (l5 * l12) - (l8 * l9);
  1844. var l38 = (l5 * l11) - (l7 * l9);
  1845. var l39 = (l5 * l10) - (l6 * l9);
  1846. other.m[0] = l23 * l27;
  1847. other.m[4] = l24 * l27;
  1848. other.m[8] = l25 * l27;
  1849. other.m[12] = l26 * l27;
  1850. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1851. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1852. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1853. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1854. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1855. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1856. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1857. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1858. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1859. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1860. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1861. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1862. return this;
  1863. };
  1864. Matrix.prototype.setTranslation = function (vector3) {
  1865. this.m[12] = vector3.x;
  1866. this.m[13] = vector3.y;
  1867. this.m[14] = vector3.z;
  1868. return this;
  1869. };
  1870. Matrix.prototype.getTranslation = function () {
  1871. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1872. };
  1873. Matrix.prototype.multiply = function (other) {
  1874. var result = new Matrix();
  1875. this.multiplyToRef(other, result);
  1876. return result;
  1877. };
  1878. Matrix.prototype.copyFrom = function (other) {
  1879. for (var index = 0; index < 16; index++) {
  1880. this.m[index] = other.m[index];
  1881. }
  1882. return this;
  1883. };
  1884. Matrix.prototype.copyToArray = function (array, offset) {
  1885. if (offset === void 0) { offset = 0; }
  1886. for (var index = 0; index < 16; index++) {
  1887. array[offset + index] = this.m[index];
  1888. }
  1889. return this;
  1890. };
  1891. Matrix.prototype.multiplyToRef = function (other, result) {
  1892. this.multiplyToArray(other, result.m, 0);
  1893. return this;
  1894. };
  1895. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1896. var tm0 = this.m[0];
  1897. var tm1 = this.m[1];
  1898. var tm2 = this.m[2];
  1899. var tm3 = this.m[3];
  1900. var tm4 = this.m[4];
  1901. var tm5 = this.m[5];
  1902. var tm6 = this.m[6];
  1903. var tm7 = this.m[7];
  1904. var tm8 = this.m[8];
  1905. var tm9 = this.m[9];
  1906. var tm10 = this.m[10];
  1907. var tm11 = this.m[11];
  1908. var tm12 = this.m[12];
  1909. var tm13 = this.m[13];
  1910. var tm14 = this.m[14];
  1911. var tm15 = this.m[15];
  1912. var om0 = other.m[0];
  1913. var om1 = other.m[1];
  1914. var om2 = other.m[2];
  1915. var om3 = other.m[3];
  1916. var om4 = other.m[4];
  1917. var om5 = other.m[5];
  1918. var om6 = other.m[6];
  1919. var om7 = other.m[7];
  1920. var om8 = other.m[8];
  1921. var om9 = other.m[9];
  1922. var om10 = other.m[10];
  1923. var om11 = other.m[11];
  1924. var om12 = other.m[12];
  1925. var om13 = other.m[13];
  1926. var om14 = other.m[14];
  1927. var om15 = other.m[15];
  1928. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1929. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1930. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1931. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1932. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1933. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1934. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1935. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1936. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1937. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1938. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1939. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1940. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1941. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1942. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1943. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1944. return this;
  1945. };
  1946. Matrix.prototype.equals = function (value) {
  1947. return value &&
  1948. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1949. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1950. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1951. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1952. };
  1953. Matrix.prototype.clone = function () {
  1954. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1955. };
  1956. Matrix.prototype.getClassName = function () {
  1957. return "Matrix";
  1958. };
  1959. Matrix.prototype.getHashCode = function () {
  1960. var hash = this.m[0] || 0;
  1961. for (var i = 1; i < 16; i++) {
  1962. hash = (hash * 397) ^ (this.m[i] || 0);
  1963. }
  1964. return hash;
  1965. };
  1966. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1967. translation.x = this.m[12];
  1968. translation.y = this.m[13];
  1969. translation.z = this.m[14];
  1970. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1971. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1972. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1973. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1974. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1975. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1976. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1977. rotation.x = 0;
  1978. rotation.y = 0;
  1979. rotation.z = 0;
  1980. rotation.w = 1;
  1981. return false;
  1982. }
  1983. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, Tmp.Matrix[0]);
  1984. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  1985. return true;
  1986. };
  1987. // Statics
  1988. Matrix.FromArray = function (array, offset) {
  1989. var result = new Matrix();
  1990. if (!offset) {
  1991. offset = 0;
  1992. }
  1993. Matrix.FromArrayToRef(array, offset, result);
  1994. return result;
  1995. };
  1996. Matrix.FromArrayToRef = function (array, offset, result) {
  1997. for (var index = 0; index < 16; index++) {
  1998. result.m[index] = array[index + offset];
  1999. }
  2000. };
  2001. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2002. for (var index = 0; index < 16; index++) {
  2003. result.m[index] = array[index + offset] * scale;
  2004. }
  2005. };
  2006. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2007. result.m[0] = initialM11;
  2008. result.m[1] = initialM12;
  2009. result.m[2] = initialM13;
  2010. result.m[3] = initialM14;
  2011. result.m[4] = initialM21;
  2012. result.m[5] = initialM22;
  2013. result.m[6] = initialM23;
  2014. result.m[7] = initialM24;
  2015. result.m[8] = initialM31;
  2016. result.m[9] = initialM32;
  2017. result.m[10] = initialM33;
  2018. result.m[11] = initialM34;
  2019. result.m[12] = initialM41;
  2020. result.m[13] = initialM42;
  2021. result.m[14] = initialM43;
  2022. result.m[15] = initialM44;
  2023. };
  2024. Matrix.prototype.getRow = function (index) {
  2025. if (index < 0 || index > 3) {
  2026. return null;
  2027. }
  2028. var i = index * 4;
  2029. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2030. };
  2031. Matrix.prototype.setRow = function (index, row) {
  2032. if (index < 0 || index > 3) {
  2033. return this;
  2034. }
  2035. var i = index * 4;
  2036. this.m[i + 0] = row.x;
  2037. this.m[i + 1] = row.y;
  2038. this.m[i + 2] = row.z;
  2039. this.m[i + 3] = row.w;
  2040. return this;
  2041. };
  2042. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2043. var result = new Matrix();
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. return result;
  2061. };
  2062. Matrix.Compose = function (scale, rotation, translation) {
  2063. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2064. var rotationMatrix = Matrix.Identity();
  2065. rotation.toRotationMatrix(rotationMatrix);
  2066. result = result.multiply(rotationMatrix);
  2067. result.setTranslation(translation);
  2068. return result;
  2069. };
  2070. Matrix.Identity = function () {
  2071. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2072. };
  2073. Matrix.IdentityToRef = function (result) {
  2074. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2075. };
  2076. Matrix.Zero = function () {
  2077. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2078. };
  2079. Matrix.RotationX = function (angle) {
  2080. var result = new Matrix();
  2081. Matrix.RotationXToRef(angle, result);
  2082. return result;
  2083. };
  2084. Matrix.Invert = function (source) {
  2085. var result = new Matrix();
  2086. source.invertToRef(result);
  2087. return result;
  2088. };
  2089. Matrix.RotationXToRef = function (angle, result) {
  2090. var s = Math.sin(angle);
  2091. var c = Math.cos(angle);
  2092. result.m[0] = 1.0;
  2093. result.m[15] = 1.0;
  2094. result.m[5] = c;
  2095. result.m[10] = c;
  2096. result.m[9] = -s;
  2097. result.m[6] = s;
  2098. result.m[1] = 0;
  2099. result.m[2] = 0;
  2100. result.m[3] = 0;
  2101. result.m[4] = 0;
  2102. result.m[7] = 0;
  2103. result.m[8] = 0;
  2104. result.m[11] = 0;
  2105. result.m[12] = 0;
  2106. result.m[13] = 0;
  2107. result.m[14] = 0;
  2108. };
  2109. Matrix.RotationY = function (angle) {
  2110. var result = new Matrix();
  2111. Matrix.RotationYToRef(angle, result);
  2112. return result;
  2113. };
  2114. Matrix.RotationYToRef = function (angle, result) {
  2115. var s = Math.sin(angle);
  2116. var c = Math.cos(angle);
  2117. result.m[5] = 1.0;
  2118. result.m[15] = 1.0;
  2119. result.m[0] = c;
  2120. result.m[2] = -s;
  2121. result.m[8] = s;
  2122. result.m[10] = c;
  2123. result.m[1] = 0;
  2124. result.m[3] = 0;
  2125. result.m[4] = 0;
  2126. result.m[6] = 0;
  2127. result.m[7] = 0;
  2128. result.m[9] = 0;
  2129. result.m[11] = 0;
  2130. result.m[12] = 0;
  2131. result.m[13] = 0;
  2132. result.m[14] = 0;
  2133. };
  2134. Matrix.RotationZ = function (angle) {
  2135. var result = new Matrix();
  2136. Matrix.RotationZToRef(angle, result);
  2137. return result;
  2138. };
  2139. Matrix.RotationZToRef = function (angle, result) {
  2140. var s = Math.sin(angle);
  2141. var c = Math.cos(angle);
  2142. result.m[10] = 1.0;
  2143. result.m[15] = 1.0;
  2144. result.m[0] = c;
  2145. result.m[1] = s;
  2146. result.m[4] = -s;
  2147. result.m[5] = c;
  2148. result.m[2] = 0;
  2149. result.m[3] = 0;
  2150. result.m[6] = 0;
  2151. result.m[7] = 0;
  2152. result.m[8] = 0;
  2153. result.m[9] = 0;
  2154. result.m[11] = 0;
  2155. result.m[12] = 0;
  2156. result.m[13] = 0;
  2157. result.m[14] = 0;
  2158. };
  2159. Matrix.RotationAxis = function (axis, angle) {
  2160. var result = Matrix.Zero();
  2161. Matrix.RotationAxisToRef(axis, angle, result);
  2162. return result;
  2163. };
  2164. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2165. var s = Math.sin(-angle);
  2166. var c = Math.cos(-angle);
  2167. var c1 = 1 - c;
  2168. axis.normalize();
  2169. result.m[0] = (axis.x * axis.x) * c1 + c;
  2170. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2171. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2172. result.m[3] = 0.0;
  2173. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2174. result.m[5] = (axis.y * axis.y) * c1 + c;
  2175. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2176. result.m[7] = 0.0;
  2177. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2178. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2179. result.m[10] = (axis.z * axis.z) * c1 + c;
  2180. result.m[11] = 0.0;
  2181. result.m[15] = 1.0;
  2182. };
  2183. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2184. var result = new Matrix();
  2185. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2186. return result;
  2187. };
  2188. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2189. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2190. this._tempQuaternion.toRotationMatrix(result);
  2191. };
  2192. Matrix.Scaling = function (x, y, z) {
  2193. var result = Matrix.Zero();
  2194. Matrix.ScalingToRef(x, y, z, result);
  2195. return result;
  2196. };
  2197. Matrix.ScalingToRef = function (x, y, z, result) {
  2198. result.m[0] = x;
  2199. result.m[1] = 0;
  2200. result.m[2] = 0;
  2201. result.m[3] = 0;
  2202. result.m[4] = 0;
  2203. result.m[5] = y;
  2204. result.m[6] = 0;
  2205. result.m[7] = 0;
  2206. result.m[8] = 0;
  2207. result.m[9] = 0;
  2208. result.m[10] = z;
  2209. result.m[11] = 0;
  2210. result.m[12] = 0;
  2211. result.m[13] = 0;
  2212. result.m[14] = 0;
  2213. result.m[15] = 1.0;
  2214. };
  2215. Matrix.Translation = function (x, y, z) {
  2216. var result = Matrix.Identity();
  2217. Matrix.TranslationToRef(x, y, z, result);
  2218. return result;
  2219. };
  2220. Matrix.TranslationToRef = function (x, y, z, result) {
  2221. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2222. };
  2223. Matrix.Lerp = function (startValue, endValue, gradient) {
  2224. var result = Matrix.Zero();
  2225. for (var index = 0; index < 16; index++) {
  2226. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2227. }
  2228. return result;
  2229. };
  2230. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2231. var startScale = new Vector3(0, 0, 0);
  2232. var startRotation = new Quaternion();
  2233. var startTranslation = new Vector3(0, 0, 0);
  2234. startValue.decompose(startScale, startRotation, startTranslation);
  2235. var endScale = new Vector3(0, 0, 0);
  2236. var endRotation = new Quaternion();
  2237. var endTranslation = new Vector3(0, 0, 0);
  2238. endValue.decompose(endScale, endRotation, endTranslation);
  2239. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2240. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2241. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2242. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2243. };
  2244. Matrix.LookAtLH = function (eye, target, up) {
  2245. var result = Matrix.Zero();
  2246. Matrix.LookAtLHToRef(eye, target, up, result);
  2247. return result;
  2248. };
  2249. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2250. // Z axis
  2251. target.subtractToRef(eye, this._zAxis);
  2252. this._zAxis.normalize();
  2253. // X axis
  2254. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2255. if (this._xAxis.lengthSquared() === 0) {
  2256. this._xAxis.x = 1.0;
  2257. }
  2258. else {
  2259. this._xAxis.normalize();
  2260. }
  2261. // Y axis
  2262. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2263. this._yAxis.normalize();
  2264. // Eye angles
  2265. var ex = -Vector3.Dot(this._xAxis, eye);
  2266. var ey = -Vector3.Dot(this._yAxis, eye);
  2267. var ez = -Vector3.Dot(this._zAxis, eye);
  2268. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2269. };
  2270. Matrix.LookAtRH = function (eye, target, up) {
  2271. var result = Matrix.Zero();
  2272. Matrix.LookAtRHToRef(eye, target, up, result);
  2273. return result;
  2274. };
  2275. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2276. // Z axis
  2277. eye.subtractToRef(target, this._zAxis);
  2278. this._zAxis.normalize();
  2279. // X axis
  2280. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2281. if (this._xAxis.lengthSquared() === 0) {
  2282. this._xAxis.x = 1.0;
  2283. }
  2284. else {
  2285. this._xAxis.normalize();
  2286. }
  2287. // Y axis
  2288. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2289. this._yAxis.normalize();
  2290. // Eye angles
  2291. var ex = -Vector3.Dot(this._xAxis, eye);
  2292. var ey = -Vector3.Dot(this._yAxis, eye);
  2293. var ez = -Vector3.Dot(this._zAxis, eye);
  2294. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2295. };
  2296. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2297. var matrix = Matrix.Zero();
  2298. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2299. return matrix;
  2300. };
  2301. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2302. var hw = 2.0 / width;
  2303. var hh = 2.0 / height;
  2304. var id = 1.0 / (zfar - znear);
  2305. var nid = znear / (znear - zfar);
  2306. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2307. };
  2308. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2309. var matrix = Matrix.Zero();
  2310. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2311. return matrix;
  2312. };
  2313. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2314. result.m[0] = 2.0 / (right - left);
  2315. result.m[1] = result.m[2] = result.m[3] = 0;
  2316. result.m[5] = 2.0 / (top - bottom);
  2317. result.m[4] = result.m[6] = result.m[7] = 0;
  2318. result.m[10] = 1.0 / (zfar - znear);
  2319. result.m[8] = result.m[9] = result.m[11] = 0;
  2320. result.m[12] = (left + right) / (left - right);
  2321. result.m[13] = (top + bottom) / (bottom - top);
  2322. result.m[14] = -znear / (zfar - znear);
  2323. result.m[15] = 1.0;
  2324. };
  2325. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2326. var matrix = Matrix.Zero();
  2327. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2328. return matrix;
  2329. };
  2330. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2331. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2332. result.m[10] *= -1.0;
  2333. };
  2334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2335. var matrix = Matrix.Zero();
  2336. matrix.m[0] = (2.0 * znear) / width;
  2337. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2338. matrix.m[5] = (2.0 * znear) / height;
  2339. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2340. matrix.m[10] = -zfar / (znear - zfar);
  2341. matrix.m[8] = matrix.m[9] = 0.0;
  2342. matrix.m[11] = 1.0;
  2343. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2344. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2345. return matrix;
  2346. };
  2347. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2353. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2354. var tan = 1.0 / (Math.tan(fov * 0.5));
  2355. if (isVerticalFovFixed) {
  2356. result.m[0] = tan / aspect;
  2357. }
  2358. else {
  2359. result.m[0] = tan;
  2360. }
  2361. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2362. if (isVerticalFovFixed) {
  2363. result.m[5] = tan;
  2364. }
  2365. else {
  2366. result.m[5] = tan * aspect;
  2367. }
  2368. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2369. result.m[8] = result.m[9] = 0.0;
  2370. result.m[10] = zfar / (zfar - znear);
  2371. result.m[11] = 1.0;
  2372. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2373. result.m[14] = -(znear * zfar) / (zfar - znear);
  2374. };
  2375. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2376. var matrix = Matrix.Zero();
  2377. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2378. return matrix;
  2379. };
  2380. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2382. var tan = 1.0 / (Math.tan(fov * 0.5));
  2383. if (isVerticalFovFixed) {
  2384. result.m[0] = tan / aspect;
  2385. }
  2386. else {
  2387. result.m[0] = tan;
  2388. }
  2389. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2390. if (isVerticalFovFixed) {
  2391. result.m[5] = tan;
  2392. }
  2393. else {
  2394. result.m[5] = tan * aspect;
  2395. }
  2396. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2397. result.m[8] = result.m[9] = 0.0;
  2398. result.m[10] = zfar / (znear - zfar);
  2399. result.m[11] = -1.0;
  2400. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2401. result.m[14] = (znear * zfar) / (znear - zfar);
  2402. };
  2403. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2404. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2405. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2406. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2407. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2408. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2409. var xScale = 2.0 / (leftTan + rightTan);
  2410. var yScale = 2.0 / (upTan + downTan);
  2411. result.m[0] = xScale;
  2412. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2413. result.m[5] = yScale;
  2414. result.m[6] = result.m[7] = 0.0;
  2415. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2416. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2417. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2418. result.m[10] = -zfar / (znear - zfar);
  2419. result.m[11] = 1.0;
  2420. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2421. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2422. result.m[14] = (znear * zfar) / (znear - zfar);
  2423. };
  2424. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2425. var cw = viewport.width;
  2426. var ch = viewport.height;
  2427. var cx = viewport.x;
  2428. var cy = viewport.y;
  2429. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2430. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2431. };
  2432. Matrix.GetAsMatrix2x2 = function (matrix) {
  2433. return new Float32Array([
  2434. matrix.m[0], matrix.m[1],
  2435. matrix.m[4], matrix.m[5]
  2436. ]);
  2437. };
  2438. Matrix.GetAsMatrix3x3 = function (matrix) {
  2439. return new Float32Array([
  2440. matrix.m[0], matrix.m[1], matrix.m[2],
  2441. matrix.m[4], matrix.m[5], matrix.m[6],
  2442. matrix.m[8], matrix.m[9], matrix.m[10]
  2443. ]);
  2444. };
  2445. Matrix.Transpose = function (matrix) {
  2446. var result = new Matrix();
  2447. result.m[0] = matrix.m[0];
  2448. result.m[1] = matrix.m[4];
  2449. result.m[2] = matrix.m[8];
  2450. result.m[3] = matrix.m[12];
  2451. result.m[4] = matrix.m[1];
  2452. result.m[5] = matrix.m[5];
  2453. result.m[6] = matrix.m[9];
  2454. result.m[7] = matrix.m[13];
  2455. result.m[8] = matrix.m[2];
  2456. result.m[9] = matrix.m[6];
  2457. result.m[10] = matrix.m[10];
  2458. result.m[11] = matrix.m[14];
  2459. result.m[12] = matrix.m[3];
  2460. result.m[13] = matrix.m[7];
  2461. result.m[14] = matrix.m[11];
  2462. result.m[15] = matrix.m[15];
  2463. return result;
  2464. };
  2465. Matrix.Reflection = function (plane) {
  2466. var matrix = new Matrix();
  2467. Matrix.ReflectionToRef(plane, matrix);
  2468. return matrix;
  2469. };
  2470. Matrix.ReflectionToRef = function (plane, result) {
  2471. plane.normalize();
  2472. var x = plane.normal.x;
  2473. var y = plane.normal.y;
  2474. var z = plane.normal.z;
  2475. var temp = -2 * x;
  2476. var temp2 = -2 * y;
  2477. var temp3 = -2 * z;
  2478. result.m[0] = (temp * x) + 1;
  2479. result.m[1] = temp2 * x;
  2480. result.m[2] = temp3 * x;
  2481. result.m[3] = 0.0;
  2482. result.m[4] = temp * y;
  2483. result.m[5] = (temp2 * y) + 1;
  2484. result.m[6] = temp3 * y;
  2485. result.m[7] = 0.0;
  2486. result.m[8] = temp * z;
  2487. result.m[9] = temp2 * z;
  2488. result.m[10] = (temp3 * z) + 1;
  2489. result.m[11] = 0.0;
  2490. result.m[12] = temp * plane.d;
  2491. result.m[13] = temp2 * plane.d;
  2492. result.m[14] = temp3 * plane.d;
  2493. result.m[15] = 1.0;
  2494. };
  2495. Matrix._tempQuaternion = new Quaternion();
  2496. Matrix._xAxis = Vector3.Zero();
  2497. Matrix._yAxis = Vector3.Zero();
  2498. Matrix._zAxis = Vector3.Zero();
  2499. return Matrix;
  2500. }());
  2501. BABYLON.Matrix = Matrix;
  2502. var Plane = (function () {
  2503. function Plane(a, b, c, d) {
  2504. this.normal = new Vector3(a, b, c);
  2505. this.d = d;
  2506. }
  2507. Plane.prototype.asArray = function () {
  2508. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2509. };
  2510. // Methods
  2511. Plane.prototype.clone = function () {
  2512. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2513. };
  2514. Plane.prototype.getClassName = function () {
  2515. return "Plane";
  2516. };
  2517. Plane.prototype.getHashCode = function () {
  2518. var hash = this.normal.getHashCode();
  2519. hash = (hash * 397) ^ (this.d || 0);
  2520. return hash;
  2521. };
  2522. Plane.prototype.normalize = function () {
  2523. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2524. var magnitude = 0;
  2525. if (norm !== 0) {
  2526. magnitude = 1.0 / norm;
  2527. }
  2528. this.normal.x *= magnitude;
  2529. this.normal.y *= magnitude;
  2530. this.normal.z *= magnitude;
  2531. this.d *= magnitude;
  2532. return this;
  2533. };
  2534. Plane.prototype.transform = function (transformation) {
  2535. var transposedMatrix = Matrix.Transpose(transformation);
  2536. var x = this.normal.x;
  2537. var y = this.normal.y;
  2538. var z = this.normal.z;
  2539. var d = this.d;
  2540. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2541. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2542. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2543. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2544. return new Plane(normalX, normalY, normalZ, finalD);
  2545. };
  2546. Plane.prototype.dotCoordinate = function (point) {
  2547. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2548. };
  2549. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2550. var x1 = point2.x - point1.x;
  2551. var y1 = point2.y - point1.y;
  2552. var z1 = point2.z - point1.z;
  2553. var x2 = point3.x - point1.x;
  2554. var y2 = point3.y - point1.y;
  2555. var z2 = point3.z - point1.z;
  2556. var yz = (y1 * z2) - (z1 * y2);
  2557. var xz = (z1 * x2) - (x1 * z2);
  2558. var xy = (x1 * y2) - (y1 * x2);
  2559. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2560. var invPyth;
  2561. if (pyth !== 0) {
  2562. invPyth = 1.0 / pyth;
  2563. }
  2564. else {
  2565. invPyth = 0;
  2566. }
  2567. this.normal.x = yz * invPyth;
  2568. this.normal.y = xz * invPyth;
  2569. this.normal.z = xy * invPyth;
  2570. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2571. return this;
  2572. };
  2573. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2574. var dot = Vector3.Dot(this.normal, direction);
  2575. return (dot <= epsilon);
  2576. };
  2577. Plane.prototype.signedDistanceTo = function (point) {
  2578. return Vector3.Dot(point, this.normal) + this.d;
  2579. };
  2580. // Statics
  2581. Plane.FromArray = function (array) {
  2582. return new Plane(array[0], array[1], array[2], array[3]);
  2583. };
  2584. Plane.FromPoints = function (point1, point2, point3) {
  2585. var result = new Plane(0, 0, 0, 0);
  2586. result.copyFromPoints(point1, point2, point3);
  2587. return result;
  2588. };
  2589. Plane.FromPositionAndNormal = function (origin, normal) {
  2590. var result = new Plane(0, 0, 0, 0);
  2591. normal.normalize();
  2592. result.normal = normal;
  2593. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2594. return result;
  2595. };
  2596. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2597. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2598. return Vector3.Dot(point, normal) + d;
  2599. };
  2600. return Plane;
  2601. }());
  2602. BABYLON.Plane = Plane;
  2603. var Viewport = (function () {
  2604. function Viewport(x, y, width, height) {
  2605. this.x = x;
  2606. this.y = y;
  2607. this.width = width;
  2608. this.height = height;
  2609. }
  2610. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2611. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2612. };
  2613. return Viewport;
  2614. }());
  2615. BABYLON.Viewport = Viewport;
  2616. var Frustum = (function () {
  2617. function Frustum() {
  2618. }
  2619. Frustum.GetPlanes = function (transform) {
  2620. var frustumPlanes = [];
  2621. for (var index = 0; index < 6; index++) {
  2622. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2623. }
  2624. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2625. return frustumPlanes;
  2626. };
  2627. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2628. // Near
  2629. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2630. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2631. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2632. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2633. frustumPlanes[0].normalize();
  2634. // Far
  2635. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2636. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2637. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2638. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2639. frustumPlanes[1].normalize();
  2640. // Left
  2641. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2642. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2643. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2644. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2645. frustumPlanes[2].normalize();
  2646. // Right
  2647. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2648. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2649. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2650. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2651. frustumPlanes[3].normalize();
  2652. // Top
  2653. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2654. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2655. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2656. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2657. frustumPlanes[4].normalize();
  2658. // Bottom
  2659. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2660. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2661. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2662. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2663. frustumPlanes[5].normalize();
  2664. };
  2665. return Frustum;
  2666. }());
  2667. BABYLON.Frustum = Frustum;
  2668. (function (Space) {
  2669. Space[Space["LOCAL"] = 0] = "LOCAL";
  2670. Space[Space["WORLD"] = 1] = "WORLD";
  2671. })(BABYLON.Space || (BABYLON.Space = {}));
  2672. var Space = BABYLON.Space;
  2673. var Axis = (function () {
  2674. function Axis() {
  2675. }
  2676. Axis.X = new Vector3(1, 0, 0);
  2677. Axis.Y = new Vector3(0, 1, 0);
  2678. Axis.Z = new Vector3(0, 0, 1);
  2679. return Axis;
  2680. }());
  2681. BABYLON.Axis = Axis;
  2682. ;
  2683. var BezierCurve = (function () {
  2684. function BezierCurve() {
  2685. }
  2686. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2687. // Extract X (which is equal to time here)
  2688. var f0 = 1 - 3 * x2 + 3 * x1;
  2689. var f1 = 3 * x2 - 6 * x1;
  2690. var f2 = 3 * x1;
  2691. var refinedT = t;
  2692. for (var i = 0; i < 5; i++) {
  2693. var refinedT2 = refinedT * refinedT;
  2694. var refinedT3 = refinedT2 * refinedT;
  2695. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2696. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2697. refinedT -= (x - t) * slope;
  2698. refinedT = Math.min(1, Math.max(0, refinedT));
  2699. }
  2700. // Resolve cubic bezier for the given x
  2701. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2702. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2703. Math.pow(refinedT, 3);
  2704. };
  2705. return BezierCurve;
  2706. }());
  2707. BABYLON.BezierCurve = BezierCurve;
  2708. (function (Orientation) {
  2709. Orientation[Orientation["CW"] = 0] = "CW";
  2710. Orientation[Orientation["CCW"] = 1] = "CCW";
  2711. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2712. var Orientation = BABYLON.Orientation;
  2713. var Angle = (function () {
  2714. function Angle(radians) {
  2715. var _this = this;
  2716. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2717. this.radians = function () { return _this._radians; };
  2718. this._radians = radians;
  2719. if (this._radians < 0)
  2720. this._radians += (2 * Math.PI);
  2721. }
  2722. Angle.BetweenTwoPoints = function (a, b) {
  2723. var delta = b.subtract(a);
  2724. var theta = Math.atan2(delta.y, delta.x);
  2725. return new Angle(theta);
  2726. };
  2727. Angle.FromRadians = function (radians) {
  2728. return new Angle(radians);
  2729. };
  2730. Angle.FromDegrees = function (degrees) {
  2731. return new Angle(degrees * Math.PI / 180);
  2732. };
  2733. return Angle;
  2734. }());
  2735. BABYLON.Angle = Angle;
  2736. var Arc2 = (function () {
  2737. function Arc2(startPoint, midPoint, endPoint) {
  2738. this.startPoint = startPoint;
  2739. this.midPoint = midPoint;
  2740. this.endPoint = endPoint;
  2741. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2742. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2743. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2744. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2745. 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);
  2746. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2747. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2748. var a1 = this.startAngle.degrees();
  2749. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2750. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2751. // angles correction
  2752. if (a2 - a1 > +180.0)
  2753. a2 -= 360.0;
  2754. if (a2 - a1 < -180.0)
  2755. a2 += 360.0;
  2756. if (a3 - a2 > +180.0)
  2757. a3 -= 360.0;
  2758. if (a3 - a2 < -180.0)
  2759. a3 += 360.0;
  2760. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2761. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2762. }
  2763. return Arc2;
  2764. }());
  2765. BABYLON.Arc2 = Arc2;
  2766. var Path2 = (function () {
  2767. function Path2(x, y) {
  2768. this._points = new Array();
  2769. this._length = 0;
  2770. this.closed = false;
  2771. this._points.push(new Vector2(x, y));
  2772. }
  2773. Path2.prototype.addLineTo = function (x, y) {
  2774. if (closed) {
  2775. //Tools.Error("cannot add lines to closed paths");
  2776. return this;
  2777. }
  2778. var newPoint = new Vector2(x, y);
  2779. var previousPoint = this._points[this._points.length - 1];
  2780. this._points.push(newPoint);
  2781. this._length += newPoint.subtract(previousPoint).length();
  2782. return this;
  2783. };
  2784. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2785. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2786. if (closed) {
  2787. //Tools.Error("cannot add arcs to closed paths");
  2788. return this;
  2789. }
  2790. var startPoint = this._points[this._points.length - 1];
  2791. var midPoint = new Vector2(midX, midY);
  2792. var endPoint = new Vector2(endX, endY);
  2793. var arc = new Arc2(startPoint, midPoint, endPoint);
  2794. var increment = arc.angle.radians() / numberOfSegments;
  2795. if (arc.orientation === Orientation.CW)
  2796. increment *= -1;
  2797. var currentAngle = arc.startAngle.radians() + increment;
  2798. for (var i = 0; i < numberOfSegments; i++) {
  2799. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2800. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2801. this.addLineTo(x, y);
  2802. currentAngle += increment;
  2803. }
  2804. return this;
  2805. };
  2806. Path2.prototype.close = function () {
  2807. this.closed = true;
  2808. return this;
  2809. };
  2810. Path2.prototype.length = function () {
  2811. var result = this._length;
  2812. if (!this.closed) {
  2813. var lastPoint = this._points[this._points.length - 1];
  2814. var firstPoint = this._points[0];
  2815. result += (firstPoint.subtract(lastPoint).length());
  2816. }
  2817. return result;
  2818. };
  2819. Path2.prototype.getPoints = function () {
  2820. return this._points;
  2821. };
  2822. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2823. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2824. //Tools.Error("normalized length position should be between 0 and 1.");
  2825. return Vector2.Zero();
  2826. }
  2827. var lengthPosition = normalizedLengthPosition * this.length();
  2828. var previousOffset = 0;
  2829. for (var i = 0; i < this._points.length; i++) {
  2830. var j = (i + 1) % this._points.length;
  2831. var a = this._points[i];
  2832. var b = this._points[j];
  2833. var bToA = b.subtract(a);
  2834. var nextOffset = (bToA.length() + previousOffset);
  2835. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2836. var dir = bToA.normalize();
  2837. var localOffset = lengthPosition - previousOffset;
  2838. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2839. }
  2840. previousOffset = nextOffset;
  2841. }
  2842. //Tools.Error("internal error");
  2843. return Vector2.Zero();
  2844. };
  2845. Path2.StartingAt = function (x, y) {
  2846. return new Path2(x, y);
  2847. };
  2848. return Path2;
  2849. }());
  2850. BABYLON.Path2 = Path2;
  2851. var Path3D = (function () {
  2852. /**
  2853. * new Path3D(path, normal, raw)
  2854. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2855. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2856. * path : an array of Vector3, the curve axis of the Path3D
  2857. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2858. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2859. */
  2860. function Path3D(path, firstNormal, raw) {
  2861. this.path = path;
  2862. this._curve = new Array();
  2863. this._distances = new Array();
  2864. this._tangents = new Array();
  2865. this._normals = new Array();
  2866. this._binormals = new Array();
  2867. for (var p = 0; p < path.length; p++) {
  2868. this._curve[p] = path[p].clone(); // hard copy
  2869. }
  2870. this._raw = raw || false;
  2871. this._compute(firstNormal);
  2872. }
  2873. /**
  2874. * Returns the Path3D array of successive Vector3 designing its curve.
  2875. */
  2876. Path3D.prototype.getCurve = function () {
  2877. return this._curve;
  2878. };
  2879. /**
  2880. * Returns an array populated with tangent vectors on each Path3D curve point.
  2881. */
  2882. Path3D.prototype.getTangents = function () {
  2883. return this._tangents;
  2884. };
  2885. /**
  2886. * Returns an array populated with normal vectors on each Path3D curve point.
  2887. */
  2888. Path3D.prototype.getNormals = function () {
  2889. return this._normals;
  2890. };
  2891. /**
  2892. * Returns an array populated with binormal vectors on each Path3D curve point.
  2893. */
  2894. Path3D.prototype.getBinormals = function () {
  2895. return this._binormals;
  2896. };
  2897. /**
  2898. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2899. */
  2900. Path3D.prototype.getDistances = function () {
  2901. return this._distances;
  2902. };
  2903. /**
  2904. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2905. * Returns the same object updated.
  2906. */
  2907. Path3D.prototype.update = function (path, firstNormal) {
  2908. for (var p = 0; p < path.length; p++) {
  2909. this._curve[p].x = path[p].x;
  2910. this._curve[p].y = path[p].y;
  2911. this._curve[p].z = path[p].z;
  2912. }
  2913. this._compute(firstNormal);
  2914. return this;
  2915. };
  2916. // private function compute() : computes tangents, normals and binormals
  2917. Path3D.prototype._compute = function (firstNormal) {
  2918. var l = this._curve.length;
  2919. // first and last tangents
  2920. this._tangents[0] = this._getFirstNonNullVector(0);
  2921. if (!this._raw) {
  2922. this._tangents[0].normalize();
  2923. }
  2924. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2925. if (!this._raw) {
  2926. this._tangents[l - 1].normalize();
  2927. }
  2928. // normals and binormals at first point : arbitrary vector with _normalVector()
  2929. var tg0 = this._tangents[0];
  2930. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2931. this._normals[0] = pp0;
  2932. if (!this._raw) {
  2933. this._normals[0].normalize();
  2934. }
  2935. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2936. if (!this._raw) {
  2937. this._binormals[0].normalize();
  2938. }
  2939. this._distances[0] = 0.0;
  2940. // normals and binormals : next points
  2941. var prev; // previous vector (segment)
  2942. var cur; // current vector (segment)
  2943. var curTang; // current tangent
  2944. // previous normal
  2945. var prevBinor; // previous binormal
  2946. for (var i = 1; i < l; i++) {
  2947. // tangents
  2948. prev = this._getLastNonNullVector(i);
  2949. if (i < l - 1) {
  2950. cur = this._getFirstNonNullVector(i);
  2951. this._tangents[i] = prev.add(cur);
  2952. this._tangents[i].normalize();
  2953. }
  2954. this._distances[i] = this._distances[i - 1] + prev.length();
  2955. // normals and binormals
  2956. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2957. curTang = this._tangents[i];
  2958. prevBinor = this._binormals[i - 1];
  2959. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2960. if (!this._raw) {
  2961. this._normals[i].normalize();
  2962. }
  2963. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2964. if (!this._raw) {
  2965. this._binormals[i].normalize();
  2966. }
  2967. }
  2968. };
  2969. // private function getFirstNonNullVector(index)
  2970. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2971. Path3D.prototype._getFirstNonNullVector = function (index) {
  2972. var i = 1;
  2973. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2974. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2975. i++;
  2976. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. }
  2978. return nNVector;
  2979. };
  2980. // private function getLastNonNullVector(index)
  2981. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2982. Path3D.prototype._getLastNonNullVector = function (index) {
  2983. var i = 1;
  2984. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2985. while (nLVector.length() === 0 && index > i + 1) {
  2986. i++;
  2987. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. }
  2989. return nLVector;
  2990. };
  2991. // private function normalVector(v0, vt, va) :
  2992. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2993. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2994. Path3D.prototype._normalVector = function (v0, vt, va) {
  2995. var normal0;
  2996. var tgl = vt.length();
  2997. if (tgl === 0.0) {
  2998. tgl = 1.0;
  2999. }
  3000. if (va === undefined || va === null) {
  3001. var point;
  3002. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3003. point = new Vector3(0.0, -1.0, 0.0);
  3004. }
  3005. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(1.0, 0.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(0.0, 0.0, 1.0);
  3010. }
  3011. normal0 = Vector3.Cross(vt, point);
  3012. }
  3013. else {
  3014. normal0 = Vector3.Cross(vt, va);
  3015. Vector3.CrossToRef(normal0, vt, normal0);
  3016. }
  3017. normal0.normalize();
  3018. return normal0;
  3019. };
  3020. return Path3D;
  3021. }());
  3022. BABYLON.Path3D = Path3D;
  3023. var Curve3 = (function () {
  3024. /**
  3025. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3026. * A Curve3 is designed from a series of successive Vector3.
  3027. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3028. */
  3029. function Curve3(points) {
  3030. this._length = 0.0;
  3031. this._points = points;
  3032. this._length = this._computeLength(points);
  3033. }
  3034. /**
  3035. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3036. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3037. * @param v1 (Vector3) the control point
  3038. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3039. * @param nbPoints (integer) the wanted number of points in the curve
  3040. */
  3041. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3042. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3043. var bez = new Array();
  3044. var equation = function (t, val0, val1, val2) {
  3045. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3046. return res;
  3047. };
  3048. for (var i = 0; i <= nbPoints; i++) {
  3049. 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)));
  3050. }
  3051. return new Curve3(bez);
  3052. };
  3053. /**
  3054. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3055. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3056. * @param v1 (Vector3) the first control point
  3057. * @param v2 (Vector3) the second control point
  3058. * @param v3 (Vector3) the end point of the Cubic Bezier
  3059. * @param nbPoints (integer) the wanted number of points in the curve
  3060. */
  3061. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3062. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3063. var bez = new Array();
  3064. var equation = function (t, val0, val1, val2, val3) {
  3065. 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;
  3066. return res;
  3067. };
  3068. for (var i = 0; i <= nbPoints; i++) {
  3069. 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)));
  3070. }
  3071. return new Curve3(bez);
  3072. };
  3073. /**
  3074. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3075. * @param p1 (Vector3) the origin point of the Hermite Spline
  3076. * @param t1 (Vector3) the tangent vector at the origin point
  3077. * @param p2 (Vector3) the end point of the Hermite Spline
  3078. * @param t2 (Vector3) the tangent vector at the end point
  3079. * @param nbPoints (integer) the wanted number of points in the curve
  3080. */
  3081. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3082. var hermite = new Array();
  3083. var step = 1.0 / nbPoints;
  3084. for (var i = 0; i <= nbPoints; i++) {
  3085. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3086. }
  3087. return new Curve3(hermite);
  3088. };
  3089. /**
  3090. * Returns the Curve3 stored array of successive Vector3
  3091. */
  3092. Curve3.prototype.getPoints = function () {
  3093. return this._points;
  3094. };
  3095. /**
  3096. * Returns the computed length (float) of the curve.
  3097. */
  3098. Curve3.prototype.length = function () {
  3099. return this._length;
  3100. };
  3101. /**
  3102. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3103. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3104. * curveA and curveB keep unchanged.
  3105. */
  3106. Curve3.prototype.continue = function (curve) {
  3107. var lastPoint = this._points[this._points.length - 1];
  3108. var continuedPoints = this._points.slice();
  3109. var curvePoints = curve.getPoints();
  3110. for (var i = 1; i < curvePoints.length; i++) {
  3111. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3112. }
  3113. var continuedCurve = new Curve3(continuedPoints);
  3114. return continuedCurve;
  3115. };
  3116. Curve3.prototype._computeLength = function (path) {
  3117. var l = 0;
  3118. for (var i = 1; i < path.length; i++) {
  3119. l += (path[i].subtract(path[i - 1])).length();
  3120. }
  3121. return l;
  3122. };
  3123. return Curve3;
  3124. }());
  3125. BABYLON.Curve3 = Curve3;
  3126. // SphericalHarmonics
  3127. var SphericalHarmonics = (function () {
  3128. function SphericalHarmonics() {
  3129. this.L00 = Vector3.Zero();
  3130. this.L1_1 = Vector3.Zero();
  3131. this.L10 = Vector3.Zero();
  3132. this.L11 = Vector3.Zero();
  3133. this.L2_2 = Vector3.Zero();
  3134. this.L2_1 = Vector3.Zero();
  3135. this.L20 = Vector3.Zero();
  3136. this.L21 = Vector3.Zero();
  3137. this.L22 = Vector3.Zero();
  3138. }
  3139. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3140. var colorVector = new Vector3(color.r, color.g, color.b);
  3141. var c = colorVector.scale(deltaSolidAngle);
  3142. this.L00 = this.L00.add(c.scale(0.282095));
  3143. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3144. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3145. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3146. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3147. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3148. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3149. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3150. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3151. };
  3152. SphericalHarmonics.prototype.scale = function (scale) {
  3153. this.L00 = this.L00.scale(scale);
  3154. this.L1_1 = this.L1_1.scale(scale);
  3155. this.L10 = this.L10.scale(scale);
  3156. this.L11 = this.L11.scale(scale);
  3157. this.L2_2 = this.L2_2.scale(scale);
  3158. this.L2_1 = this.L2_1.scale(scale);
  3159. this.L20 = this.L20.scale(scale);
  3160. this.L21 = this.L21.scale(scale);
  3161. this.L22 = this.L22.scale(scale);
  3162. };
  3163. return SphericalHarmonics;
  3164. }());
  3165. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3166. // SphericalPolynomial
  3167. var SphericalPolynomial = (function () {
  3168. function SphericalPolynomial() {
  3169. this.x = Vector3.Zero();
  3170. this.y = Vector3.Zero();
  3171. this.z = Vector3.Zero();
  3172. this.xx = Vector3.Zero();
  3173. this.yy = Vector3.Zero();
  3174. this.zz = Vector3.Zero();
  3175. this.xy = Vector3.Zero();
  3176. this.yz = Vector3.Zero();
  3177. this.zx = Vector3.Zero();
  3178. }
  3179. SphericalPolynomial.prototype.addAmbient = function (color) {
  3180. var colorVector = new Vector3(color.r, color.g, color.b);
  3181. this.xx = this.xx.add(colorVector);
  3182. this.yy = this.yy.add(colorVector);
  3183. this.zz = this.zz.add(colorVector);
  3184. };
  3185. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3186. var result = new SphericalPolynomial();
  3187. result.x = harmonics.L11.scale(1.02333);
  3188. result.y = harmonics.L1_1.scale(1.02333);
  3189. result.z = harmonics.L10.scale(1.02333);
  3190. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3191. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3192. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3193. result.yz = harmonics.L2_1.scale(0.858086);
  3194. result.zx = harmonics.L21.scale(0.858086);
  3195. result.xy = harmonics.L2_2.scale(0.858086);
  3196. return result;
  3197. };
  3198. return SphericalPolynomial;
  3199. }());
  3200. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3201. // Vertex formats
  3202. var PositionNormalVertex = (function () {
  3203. function PositionNormalVertex(position, normal) {
  3204. if (position === void 0) { position = Vector3.Zero(); }
  3205. if (normal === void 0) { normal = Vector3.Up(); }
  3206. this.position = position;
  3207. this.normal = normal;
  3208. }
  3209. PositionNormalVertex.prototype.clone = function () {
  3210. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3211. };
  3212. return PositionNormalVertex;
  3213. }());
  3214. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3215. var PositionNormalTextureVertex = (function () {
  3216. function PositionNormalTextureVertex(position, normal, uv) {
  3217. if (position === void 0) { position = Vector3.Zero(); }
  3218. if (normal === void 0) { normal = Vector3.Up(); }
  3219. if (uv === void 0) { uv = Vector2.Zero(); }
  3220. this.position = position;
  3221. this.normal = normal;
  3222. this.uv = uv;
  3223. }
  3224. PositionNormalTextureVertex.prototype.clone = function () {
  3225. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3226. };
  3227. return PositionNormalTextureVertex;
  3228. }());
  3229. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3230. // Temporary pre-allocated objects for engine internal use
  3231. // usage in any internal function :
  3232. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3233. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3234. var Tmp = (function () {
  3235. function Tmp() {
  3236. }
  3237. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3238. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3239. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3240. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3241. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3242. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3243. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3244. Matrix.Zero(), Matrix.Zero(),
  3245. Matrix.Zero(), Matrix.Zero(),
  3246. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3247. return Tmp;
  3248. }());
  3249. BABYLON.Tmp = Tmp;
  3250. })(BABYLON || (BABYLON = {}));
  3251. var BABYLON;
  3252. (function (BABYLON) {
  3253. function generateSerializableMember(type, sourceName) {
  3254. return function (target, propertyKey) {
  3255. if (!target.__serializableMembers) {
  3256. target.__serializableMembers = {};
  3257. }
  3258. if (!target.__serializableMembers[propertyKey]) {
  3259. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3260. }
  3261. };
  3262. }
  3263. function serialize(sourceName) {
  3264. return generateSerializableMember(0, sourceName); // value member
  3265. }
  3266. BABYLON.serialize = serialize;
  3267. function serializeAsTexture(sourceName) {
  3268. return generateSerializableMember(1, sourceName); // texture member
  3269. }
  3270. BABYLON.serializeAsTexture = serializeAsTexture;
  3271. function serializeAsColor3(sourceName) {
  3272. return generateSerializableMember(2, sourceName); // color3 member
  3273. }
  3274. BABYLON.serializeAsColor3 = serializeAsColor3;
  3275. function serializeAsFresnelParameters(sourceName) {
  3276. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3277. }
  3278. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3279. function serializeAsVector2(sourceName) {
  3280. return generateSerializableMember(4, sourceName); // vector2 member
  3281. }
  3282. BABYLON.serializeAsVector2 = serializeAsVector2;
  3283. function serializeAsVector3(sourceName) {
  3284. return generateSerializableMember(5, sourceName); // vector3 member
  3285. }
  3286. BABYLON.serializeAsVector3 = serializeAsVector3;
  3287. function serializeAsMeshReference(sourceName) {
  3288. return generateSerializableMember(6, sourceName); // mesh reference member
  3289. }
  3290. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3291. function serializeAsColorCurves(sourceName) {
  3292. return generateSerializableMember(7, sourceName); // color curves
  3293. }
  3294. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3295. var SerializationHelper = (function () {
  3296. function SerializationHelper() {
  3297. }
  3298. SerializationHelper.Serialize = function (entity, serializationObject) {
  3299. if (!serializationObject) {
  3300. serializationObject = {};
  3301. }
  3302. // Tags
  3303. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3304. // Properties
  3305. for (var property in entity.__serializableMembers) {
  3306. var propertyDescriptor = entity.__serializableMembers[property];
  3307. var targetPropertyName = propertyDescriptor.sourceName || property;
  3308. var propertyType = propertyDescriptor.type;
  3309. var sourceProperty = entity[property];
  3310. if (sourceProperty !== undefined && sourceProperty !== null) {
  3311. switch (propertyType) {
  3312. case 0:
  3313. serializationObject[targetPropertyName] = sourceProperty;
  3314. break;
  3315. case 1:
  3316. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3317. break;
  3318. case 2:
  3319. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3320. break;
  3321. case 3:
  3322. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3323. break;
  3324. case 4:
  3325. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3326. break;
  3327. case 5:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 6:
  3331. serializationObject[targetPropertyName] = sourceProperty.id;
  3332. break;
  3333. case 7:
  3334. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3335. break;
  3336. }
  3337. }
  3338. }
  3339. return serializationObject;
  3340. };
  3341. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3342. var destination = creationFunction();
  3343. // Tags
  3344. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3345. // Properties
  3346. for (var property in destination.__serializableMembers) {
  3347. var propertyDescriptor = destination.__serializableMembers[property];
  3348. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3349. var propertyType = propertyDescriptor.type;
  3350. if (sourceProperty !== undefined && sourceProperty !== null) {
  3351. switch (propertyType) {
  3352. case 0:
  3353. destination[property] = sourceProperty;
  3354. break;
  3355. case 1:
  3356. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3357. break;
  3358. case 2:
  3359. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3360. break;
  3361. case 3:
  3362. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3363. break;
  3364. case 4:
  3365. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3366. break;
  3367. case 5:
  3368. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3369. break;
  3370. case 6:
  3371. destination[property] = scene.getLastMeshByID(sourceProperty);
  3372. break;
  3373. case 7:
  3374. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3375. break;
  3376. }
  3377. }
  3378. }
  3379. return destination;
  3380. };
  3381. SerializationHelper.Clone = function (creationFunction, source) {
  3382. var destination = creationFunction();
  3383. // Tags
  3384. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3385. // Properties
  3386. for (var property in destination.__serializableMembers) {
  3387. var propertyDescriptor = destination.__serializableMembers[property];
  3388. var sourceProperty = source[property];
  3389. var propertyType = propertyDescriptor.type;
  3390. if (sourceProperty !== undefined && sourceProperty !== null) {
  3391. switch (propertyType) {
  3392. case 0: // Value
  3393. case 6:
  3394. destination[property] = sourceProperty;
  3395. break;
  3396. case 1: // Texture
  3397. case 2: // Color3
  3398. case 3: // FresnelParameters
  3399. case 4: // Vector2
  3400. case 5: // Vector3
  3401. case 7:
  3402. destination[property] = sourceProperty.clone();
  3403. break;
  3404. }
  3405. }
  3406. }
  3407. return destination;
  3408. };
  3409. return SerializationHelper;
  3410. }());
  3411. BABYLON.SerializationHelper = SerializationHelper;
  3412. })(BABYLON || (BABYLON = {}));
  3413. var BABYLON;
  3414. (function (BABYLON) {
  3415. /**
  3416. * A class serves as a medium between the observable and its observers
  3417. */
  3418. var EventState = (function () {
  3419. /**
  3420. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3421. */
  3422. function EventState(mask, skipNextObservers) {
  3423. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3424. this.initalize(mask, skipNextObservers);
  3425. }
  3426. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3427. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3428. this.mask = mask;
  3429. this.skipNextObservers = skipNextObservers;
  3430. return this;
  3431. };
  3432. return EventState;
  3433. }());
  3434. BABYLON.EventState = EventState;
  3435. /**
  3436. * Represent an Observer registered to a given Observable object.
  3437. */
  3438. var Observer = (function () {
  3439. function Observer(callback, mask) {
  3440. this.callback = callback;
  3441. this.mask = mask;
  3442. }
  3443. return Observer;
  3444. }());
  3445. BABYLON.Observer = Observer;
  3446. /**
  3447. * The Observable class is a simple implementation of the Observable pattern.
  3448. * 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.
  3449. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3450. * 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).
  3451. * 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.
  3452. */
  3453. var Observable = (function () {
  3454. function Observable() {
  3455. this._observers = new Array();
  3456. this._eventState = new EventState(0);
  3457. }
  3458. /**
  3459. * Create a new Observer with the specified callback
  3460. * @param callback the callback that will be executed for that Observer
  3461. * @param mask the mask used to filter observers
  3462. * @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.
  3463. */
  3464. Observable.prototype.add = function (callback, mask, insertFirst) {
  3465. if (mask === void 0) { mask = -1; }
  3466. if (insertFirst === void 0) { insertFirst = false; }
  3467. if (!callback) {
  3468. return null;
  3469. }
  3470. var observer = new Observer(callback, mask);
  3471. if (insertFirst) {
  3472. this._observers.unshift(observer);
  3473. }
  3474. else {
  3475. this._observers.push(observer);
  3476. }
  3477. return observer;
  3478. };
  3479. /**
  3480. * Remove an Observer from the Observable object
  3481. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3482. */
  3483. Observable.prototype.remove = function (observer) {
  3484. var index = this._observers.indexOf(observer);
  3485. if (index !== -1) {
  3486. this._observers.splice(index, 1);
  3487. return true;
  3488. }
  3489. return false;
  3490. };
  3491. /**
  3492. * Remove a callback from the Observable object
  3493. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3494. */
  3495. Observable.prototype.removeCallback = function (callback) {
  3496. for (var index = 0; index < this._observers.length; index++) {
  3497. if (this._observers[index].callback === callback) {
  3498. this._observers.splice(index, 1);
  3499. return true;
  3500. }
  3501. }
  3502. return false;
  3503. };
  3504. /**
  3505. * Notify all Observers by calling their respective callback with the given data
  3506. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3507. * @param eventData
  3508. * @param mask
  3509. */
  3510. Observable.prototype.notifyObservers = function (eventData, mask) {
  3511. if (mask === void 0) { mask = -1; }
  3512. var state = this._eventState;
  3513. state.mask = mask;
  3514. state.skipNextObservers = false;
  3515. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3516. var obs = _a[_i];
  3517. if (obs.mask & mask) {
  3518. obs.callback(eventData, state);
  3519. }
  3520. if (state.skipNextObservers) {
  3521. return false;
  3522. }
  3523. }
  3524. return true;
  3525. };
  3526. /**
  3527. * return true is the Observable has at least one Observer registered
  3528. */
  3529. Observable.prototype.hasObservers = function () {
  3530. return this._observers.length > 0;
  3531. };
  3532. /**
  3533. * Clear the list of observers
  3534. */
  3535. Observable.prototype.clear = function () {
  3536. this._observers = new Array();
  3537. };
  3538. /**
  3539. * Clone the current observable
  3540. */
  3541. Observable.prototype.clone = function () {
  3542. var result = new Observable();
  3543. result._observers = this._observers.slice(0);
  3544. return result;
  3545. };
  3546. return Observable;
  3547. }());
  3548. BABYLON.Observable = Observable;
  3549. })(BABYLON || (BABYLON = {}));
  3550. var BABYLON;
  3551. (function (BABYLON) {
  3552. var Database = (function () {
  3553. function Database(urlToScene, callbackManifestChecked) {
  3554. // Handling various flavors of prefixed version of IndexedDB
  3555. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3556. this.callbackManifestChecked = callbackManifestChecked;
  3557. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3558. this.db = null;
  3559. this.enableSceneOffline = false;
  3560. this.enableTexturesOffline = false;
  3561. this.manifestVersionFound = 0;
  3562. this.mustUpdateRessources = false;
  3563. this.hasReachedQuota = false;
  3564. if (!Database.IDBStorageEnabled) {
  3565. this.callbackManifestChecked(true);
  3566. }
  3567. else {
  3568. this.checkManifestFile();
  3569. }
  3570. }
  3571. Database.prototype.checkManifestFile = function () {
  3572. var _this = this;
  3573. function noManifestFile() {
  3574. that.enableSceneOffline = false;
  3575. that.enableTexturesOffline = false;
  3576. that.callbackManifestChecked(false);
  3577. }
  3578. var that = this;
  3579. var timeStampUsed = false;
  3580. var manifestURL = this.currentSceneUrl + ".manifest";
  3581. var xhr = new XMLHttpRequest();
  3582. if (navigator.onLine) {
  3583. // Adding a timestamp to by-pass browsers' cache
  3584. timeStampUsed = true;
  3585. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3586. }
  3587. xhr.open("GET", manifestURL, true);
  3588. xhr.addEventListener("load", function () {
  3589. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3590. try {
  3591. var manifestFile = JSON.parse(xhr.response);
  3592. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3593. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3594. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3595. _this.manifestVersionFound = manifestFile.version;
  3596. }
  3597. if (_this.callbackManifestChecked) {
  3598. _this.callbackManifestChecked(true);
  3599. }
  3600. }
  3601. catch (ex) {
  3602. noManifestFile();
  3603. }
  3604. }
  3605. else {
  3606. noManifestFile();
  3607. }
  3608. }, false);
  3609. xhr.addEventListener("error", function (event) {
  3610. if (timeStampUsed) {
  3611. timeStampUsed = false;
  3612. // Let's retry without the timeStamp
  3613. // It could fail when coupled with HTML5 Offline API
  3614. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3615. xhr.open("GET", retryManifestURL, true);
  3616. xhr.send();
  3617. }
  3618. else {
  3619. noManifestFile();
  3620. }
  3621. }, false);
  3622. try {
  3623. xhr.send();
  3624. }
  3625. catch (ex) {
  3626. BABYLON.Tools.Error("Error on XHR send request.");
  3627. that.callbackManifestChecked(false);
  3628. }
  3629. };
  3630. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3631. var _this = this;
  3632. function handleError() {
  3633. that.isSupported = false;
  3634. if (errorCallback)
  3635. errorCallback();
  3636. }
  3637. var that = this;
  3638. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3639. // Your browser doesn't support IndexedDB
  3640. this.isSupported = false;
  3641. if (errorCallback)
  3642. errorCallback();
  3643. }
  3644. else {
  3645. // If the DB hasn't been opened or created yet
  3646. if (!this.db) {
  3647. this.hasReachedQuota = false;
  3648. this.isSupported = true;
  3649. var request = this.idbFactory.open("babylonjs", 1);
  3650. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3651. request.onerror = function (event) {
  3652. handleError();
  3653. };
  3654. // executes when a version change transaction cannot complete due to other active transactions
  3655. request.onblocked = function (event) {
  3656. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3657. handleError();
  3658. };
  3659. // DB has been opened successfully
  3660. request.onsuccess = function (event) {
  3661. _this.db = request.result;
  3662. successCallback();
  3663. };
  3664. // Initialization of the DB. Creating Scenes & Textures stores
  3665. request.onupgradeneeded = function (event) {
  3666. _this.db = (event.target).result;
  3667. try {
  3668. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3669. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3670. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3671. }
  3672. catch (ex) {
  3673. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3674. handleError();
  3675. }
  3676. };
  3677. }
  3678. else {
  3679. if (successCallback)
  3680. successCallback();
  3681. }
  3682. }
  3683. };
  3684. Database.prototype.loadImageFromDB = function (url, image) {
  3685. var _this = this;
  3686. var completeURL = Database.ReturnFullUrlLocation(url);
  3687. var saveAndLoadImage = function () {
  3688. if (!_this.hasReachedQuota && _this.db !== null) {
  3689. // the texture is not yet in the DB, let's try to save it
  3690. _this._saveImageIntoDBAsync(completeURL, image);
  3691. }
  3692. else {
  3693. image.src = url;
  3694. }
  3695. };
  3696. if (!this.mustUpdateRessources) {
  3697. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3698. }
  3699. else {
  3700. saveAndLoadImage();
  3701. }
  3702. };
  3703. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3704. if (this.isSupported && this.db !== null) {
  3705. var texture;
  3706. var transaction = this.db.transaction(["textures"]);
  3707. transaction.onabort = function (event) {
  3708. image.src = url;
  3709. };
  3710. transaction.oncomplete = function (event) {
  3711. var blobTextureURL;
  3712. if (texture) {
  3713. var URL = window.URL || window.webkitURL;
  3714. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3715. image.onerror = function () {
  3716. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3717. image.src = url;
  3718. };
  3719. image.src = blobTextureURL;
  3720. }
  3721. else {
  3722. notInDBCallback();
  3723. }
  3724. };
  3725. var getRequest = transaction.objectStore("textures").get(url);
  3726. getRequest.onsuccess = function (event) {
  3727. texture = (event.target).result;
  3728. };
  3729. getRequest.onerror = function (event) {
  3730. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3731. image.src = url;
  3732. };
  3733. }
  3734. else {
  3735. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3736. image.src = url;
  3737. }
  3738. };
  3739. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3740. var _this = this;
  3741. if (this.isSupported) {
  3742. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3743. var generateBlobUrl = function () {
  3744. var blobTextureURL;
  3745. if (blob) {
  3746. var URL = window.URL || window.webkitURL;
  3747. try {
  3748. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3749. }
  3750. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3751. catch (ex) {
  3752. blobTextureURL = URL.createObjectURL(blob);
  3753. }
  3754. }
  3755. image.src = blobTextureURL;
  3756. };
  3757. if (Database.IsUASupportingBlobStorage) {
  3758. var xhr = new XMLHttpRequest(), blob;
  3759. xhr.open("GET", url, true);
  3760. xhr.responseType = "blob";
  3761. xhr.addEventListener("load", function () {
  3762. if (xhr.status === 200) {
  3763. // Blob as response (XHR2)
  3764. blob = xhr.response;
  3765. var transaction = _this.db.transaction(["textures"], "readwrite");
  3766. // the transaction could abort because of a QuotaExceededError error
  3767. transaction.onabort = function (event) {
  3768. try {
  3769. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3770. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3771. _this.hasReachedQuota = true;
  3772. }
  3773. }
  3774. catch (ex) { }
  3775. generateBlobUrl();
  3776. };
  3777. transaction.oncomplete = function (event) {
  3778. generateBlobUrl();
  3779. };
  3780. var newTexture = { textureUrl: url, data: blob };
  3781. try {
  3782. // Put the blob into the dabase
  3783. var addRequest = transaction.objectStore("textures").put(newTexture);
  3784. addRequest.onsuccess = function (event) {
  3785. };
  3786. addRequest.onerror = function (event) {
  3787. generateBlobUrl();
  3788. };
  3789. }
  3790. catch (ex) {
  3791. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3792. if (ex.code === 25) {
  3793. Database.IsUASupportingBlobStorage = false;
  3794. }
  3795. image.src = url;
  3796. }
  3797. }
  3798. else {
  3799. image.src = url;
  3800. }
  3801. }, false);
  3802. xhr.addEventListener("error", function (event) {
  3803. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3804. image.src = url;
  3805. }, false);
  3806. xhr.send();
  3807. }
  3808. else {
  3809. image.src = url;
  3810. }
  3811. }
  3812. else {
  3813. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3814. image.src = url;
  3815. }
  3816. };
  3817. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3818. var _this = this;
  3819. var updateVersion = function (event) {
  3820. // the version is not yet in the DB or we need to update it
  3821. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3822. };
  3823. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3824. };
  3825. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3826. var _this = this;
  3827. if (this.isSupported) {
  3828. var version;
  3829. try {
  3830. var transaction = this.db.transaction(["versions"]);
  3831. transaction.oncomplete = function (event) {
  3832. if (version) {
  3833. // If the version in the JSON file is > than the version in DB
  3834. if (_this.manifestVersionFound > version.data) {
  3835. _this.mustUpdateRessources = true;
  3836. updateInDBCallback();
  3837. }
  3838. else {
  3839. callback(version.data);
  3840. }
  3841. }
  3842. else {
  3843. _this.mustUpdateRessources = true;
  3844. updateInDBCallback();
  3845. }
  3846. };
  3847. transaction.onabort = function (event) {
  3848. callback(-1);
  3849. };
  3850. var getRequest = transaction.objectStore("versions").get(url);
  3851. getRequest.onsuccess = function (event) {
  3852. version = (event.target).result;
  3853. };
  3854. getRequest.onerror = function (event) {
  3855. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3856. callback(-1);
  3857. };
  3858. }
  3859. catch (ex) {
  3860. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3861. callback(-1);
  3862. }
  3863. }
  3864. else {
  3865. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3866. callback(-1);
  3867. }
  3868. };
  3869. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3870. var _this = this;
  3871. if (this.isSupported && !this.hasReachedQuota) {
  3872. try {
  3873. // Open a transaction to the database
  3874. var transaction = this.db.transaction(["versions"], "readwrite");
  3875. // the transaction could abort because of a QuotaExceededError error
  3876. transaction.onabort = function (event) {
  3877. try {
  3878. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3879. _this.hasReachedQuota = true;
  3880. }
  3881. }
  3882. catch (ex) { }
  3883. callback(-1);
  3884. };
  3885. transaction.oncomplete = function (event) {
  3886. callback(_this.manifestVersionFound);
  3887. };
  3888. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3889. // Put the scene into the database
  3890. var addRequest = transaction.objectStore("versions").put(newVersion);
  3891. addRequest.onsuccess = function (event) {
  3892. };
  3893. addRequest.onerror = function (event) {
  3894. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3895. };
  3896. }
  3897. catch (ex) {
  3898. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3899. callback(-1);
  3900. }
  3901. }
  3902. else {
  3903. callback(-1);
  3904. }
  3905. };
  3906. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3907. var _this = this;
  3908. var completeUrl = Database.ReturnFullUrlLocation(url);
  3909. var saveAndLoadFile = function (event) {
  3910. // the scene is not yet in the DB, let's try to save it
  3911. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3912. };
  3913. this._checkVersionFromDB(completeUrl, function (version) {
  3914. if (version !== -1) {
  3915. if (!_this.mustUpdateRessources) {
  3916. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3917. }
  3918. else {
  3919. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3920. }
  3921. }
  3922. else {
  3923. errorCallback();
  3924. }
  3925. });
  3926. };
  3927. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3928. if (this.isSupported) {
  3929. var targetStore;
  3930. if (url.indexOf(".babylon") !== -1) {
  3931. targetStore = "scenes";
  3932. }
  3933. else {
  3934. targetStore = "textures";
  3935. }
  3936. var file;
  3937. var transaction = this.db.transaction([targetStore]);
  3938. transaction.oncomplete = function (event) {
  3939. if (file) {
  3940. callback(file.data);
  3941. }
  3942. else {
  3943. notInDBCallback();
  3944. }
  3945. };
  3946. transaction.onabort = function (event) {
  3947. notInDBCallback();
  3948. };
  3949. var getRequest = transaction.objectStore(targetStore).get(url);
  3950. getRequest.onsuccess = function (event) {
  3951. file = (event.target).result;
  3952. };
  3953. getRequest.onerror = function (event) {
  3954. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3955. notInDBCallback();
  3956. };
  3957. }
  3958. else {
  3959. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3960. callback();
  3961. }
  3962. };
  3963. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3964. var _this = this;
  3965. if (this.isSupported) {
  3966. var targetStore;
  3967. if (url.indexOf(".babylon") !== -1) {
  3968. targetStore = "scenes";
  3969. }
  3970. else {
  3971. targetStore = "textures";
  3972. }
  3973. // Create XHR
  3974. var xhr = new XMLHttpRequest(), fileData;
  3975. xhr.open("GET", url, true);
  3976. if (useArrayBuffer) {
  3977. xhr.responseType = "arraybuffer";
  3978. }
  3979. xhr.onprogress = progressCallback;
  3980. xhr.addEventListener("load", function () {
  3981. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3982. // Blob as response (XHR2)
  3983. //fileData = xhr.responseText;
  3984. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3985. if (!_this.hasReachedQuota) {
  3986. // Open a transaction to the database
  3987. var transaction = _this.db.transaction([targetStore], "readwrite");
  3988. // the transaction could abort because of a QuotaExceededError error
  3989. transaction.onabort = function (event) {
  3990. try {
  3991. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3992. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3993. _this.hasReachedQuota = true;
  3994. }
  3995. }
  3996. catch (ex) { }
  3997. callback(fileData);
  3998. };
  3999. transaction.oncomplete = function (event) {
  4000. callback(fileData);
  4001. };
  4002. var newFile;
  4003. if (targetStore === "scenes") {
  4004. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4005. }
  4006. else {
  4007. newFile = { textureUrl: url, data: fileData };
  4008. }
  4009. try {
  4010. // Put the scene into the database
  4011. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4012. addRequest.onsuccess = function (event) {
  4013. };
  4014. addRequest.onerror = function (event) {
  4015. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4016. };
  4017. }
  4018. catch (ex) {
  4019. callback(fileData);
  4020. }
  4021. }
  4022. else {
  4023. callback(fileData);
  4024. }
  4025. }
  4026. else {
  4027. callback();
  4028. }
  4029. }, false);
  4030. xhr.addEventListener("error", function (event) {
  4031. BABYLON.Tools.Error("error on XHR request.");
  4032. callback();
  4033. }, false);
  4034. xhr.send();
  4035. }
  4036. else {
  4037. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4038. callback();
  4039. }
  4040. };
  4041. Database.IsUASupportingBlobStorage = true;
  4042. Database.IDBStorageEnabled = true;
  4043. Database.parseURL = function (url) {
  4044. var a = document.createElement('a');
  4045. a.href = url;
  4046. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4047. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4048. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4049. return absLocation;
  4050. };
  4051. Database.ReturnFullUrlLocation = function (url) {
  4052. if (url.indexOf("http:/") === -1) {
  4053. return (Database.parseURL(window.location.href) + url);
  4054. }
  4055. else {
  4056. return url;
  4057. }
  4058. };
  4059. return Database;
  4060. }());
  4061. BABYLON.Database = Database;
  4062. })(BABYLON || (BABYLON = {}));
  4063. var BABYLON;
  4064. (function (BABYLON) {
  4065. var Internals;
  4066. (function (Internals) {
  4067. /*
  4068. * Based on jsTGALoader - Javascript loader for TGA file
  4069. * By Vincent Thibault
  4070. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4071. */
  4072. var TGATools = (function () {
  4073. function TGATools() {
  4074. }
  4075. TGATools.GetTGAHeader = function (data) {
  4076. var offset = 0;
  4077. var header = {
  4078. id_length: data[offset++],
  4079. colormap_type: data[offset++],
  4080. image_type: data[offset++],
  4081. colormap_index: data[offset++] | data[offset++] << 8,
  4082. colormap_length: data[offset++] | data[offset++] << 8,
  4083. colormap_size: data[offset++],
  4084. origin: [
  4085. data[offset++] | data[offset++] << 8,
  4086. data[offset++] | data[offset++] << 8
  4087. ],
  4088. width: data[offset++] | data[offset++] << 8,
  4089. height: data[offset++] | data[offset++] << 8,
  4090. pixel_size: data[offset++],
  4091. flags: data[offset++]
  4092. };
  4093. return header;
  4094. };
  4095. TGATools.UploadContent = function (gl, data) {
  4096. // Not enough data to contain header ?
  4097. if (data.length < 19) {
  4098. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4099. return;
  4100. }
  4101. // Read Header
  4102. var offset = 18;
  4103. var header = TGATools.GetTGAHeader(data);
  4104. // Assume it's a valid Targa file.
  4105. if (header.id_length + offset > data.length) {
  4106. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4107. return;
  4108. }
  4109. // Skip not needed data
  4110. offset += header.id_length;
  4111. var use_rle = false;
  4112. var use_pal = false;
  4113. var use_rgb = false;
  4114. var use_grey = false;
  4115. // Get some informations.
  4116. switch (header.image_type) {
  4117. case TGATools._TYPE_RLE_INDEXED:
  4118. use_rle = true;
  4119. case TGATools._TYPE_INDEXED:
  4120. use_pal = true;
  4121. break;
  4122. case TGATools._TYPE_RLE_RGB:
  4123. use_rle = true;
  4124. case TGATools._TYPE_RGB:
  4125. use_rgb = true;
  4126. break;
  4127. case TGATools._TYPE_RLE_GREY:
  4128. use_rle = true;
  4129. case TGATools._TYPE_GREY:
  4130. use_grey = true;
  4131. break;
  4132. }
  4133. var pixel_data;
  4134. var numAlphaBits = header.flags & 0xf;
  4135. var pixel_size = header.pixel_size >> 3;
  4136. var pixel_total = header.width * header.height * pixel_size;
  4137. // Read palettes
  4138. var palettes;
  4139. if (use_pal) {
  4140. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4141. }
  4142. // Read LRE
  4143. if (use_rle) {
  4144. pixel_data = new Uint8Array(pixel_total);
  4145. var c, count, i;
  4146. var localOffset = 0;
  4147. var pixels = new Uint8Array(pixel_size);
  4148. while (offset < pixel_total && localOffset < pixel_total) {
  4149. c = data[offset++];
  4150. count = (c & 0x7f) + 1;
  4151. // RLE pixels
  4152. if (c & 0x80) {
  4153. // Bind pixel tmp array
  4154. for (i = 0; i < pixel_size; ++i) {
  4155. pixels[i] = data[offset++];
  4156. }
  4157. // Copy pixel array
  4158. for (i = 0; i < count; ++i) {
  4159. pixel_data.set(pixels, localOffset + i * pixel_size);
  4160. }
  4161. localOffset += pixel_size * count;
  4162. }
  4163. else {
  4164. count *= pixel_size;
  4165. for (i = 0; i < count; ++i) {
  4166. pixel_data[localOffset + i] = data[offset++];
  4167. }
  4168. localOffset += count;
  4169. }
  4170. }
  4171. }
  4172. else {
  4173. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4174. }
  4175. // Load to texture
  4176. var x_start, y_start, x_step, y_step, y_end, x_end;
  4177. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4178. default:
  4179. case TGATools._ORIGIN_UL:
  4180. x_start = 0;
  4181. x_step = 1;
  4182. x_end = header.width;
  4183. y_start = 0;
  4184. y_step = 1;
  4185. y_end = header.height;
  4186. break;
  4187. case TGATools._ORIGIN_BL:
  4188. x_start = 0;
  4189. x_step = 1;
  4190. x_end = header.width;
  4191. y_start = header.height - 1;
  4192. y_step = -1;
  4193. y_end = -1;
  4194. break;
  4195. case TGATools._ORIGIN_UR:
  4196. x_start = header.width - 1;
  4197. x_step = -1;
  4198. x_end = -1;
  4199. y_start = 0;
  4200. y_step = 1;
  4201. y_end = header.height;
  4202. break;
  4203. case TGATools._ORIGIN_BR:
  4204. x_start = header.width - 1;
  4205. x_step = -1;
  4206. x_end = -1;
  4207. y_start = header.height - 1;
  4208. y_step = -1;
  4209. y_end = -1;
  4210. break;
  4211. }
  4212. // Load the specify method
  4213. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4214. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4215. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4216. };
  4217. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4218. var image = pixel_data, colormap = palettes;
  4219. var width = header.width, height = header.height;
  4220. var color, i = 0, x, y;
  4221. var imageData = new Uint8Array(width * height * 4);
  4222. for (y = y_start; y !== y_end; y += y_step) {
  4223. for (x = x_start; x !== x_end; x += x_step, i++) {
  4224. color = image[i];
  4225. imageData[(x + width * y) * 4 + 3] = 255;
  4226. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4227. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4228. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4229. }
  4230. }
  4231. return imageData;
  4232. };
  4233. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4234. var image = pixel_data;
  4235. var width = header.width, height = header.height;
  4236. var color, i = 0, x, y;
  4237. var imageData = new Uint8Array(width * height * 4);
  4238. for (y = y_start; y !== y_end; y += y_step) {
  4239. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4240. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4241. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4242. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4243. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4244. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4245. }
  4246. }
  4247. return imageData;
  4248. };
  4249. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4250. var image = pixel_data;
  4251. var width = header.width, height = header.height;
  4252. var i = 0, x, y;
  4253. var imageData = new Uint8Array(width * height * 4);
  4254. for (y = y_start; y !== y_end; y += y_step) {
  4255. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4256. imageData[(x + width * y) * 4 + 3] = 255;
  4257. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4258. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4259. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4260. }
  4261. }
  4262. return imageData;
  4263. };
  4264. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4265. var image = pixel_data;
  4266. var width = header.width, height = header.height;
  4267. var i = 0, x, y;
  4268. var imageData = new Uint8Array(width * height * 4);
  4269. for (y = y_start; y !== y_end; y += y_step) {
  4270. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4271. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4272. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4273. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4274. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4275. }
  4276. }
  4277. return imageData;
  4278. };
  4279. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4280. var image = pixel_data;
  4281. var width = header.width, height = header.height;
  4282. var color, i = 0, x, y;
  4283. var imageData = new Uint8Array(width * height * 4);
  4284. for (y = y_start; y !== y_end; y += y_step) {
  4285. for (x = x_start; x !== x_end; x += x_step, i++) {
  4286. color = image[i];
  4287. imageData[(x + width * y) * 4 + 0] = color;
  4288. imageData[(x + width * y) * 4 + 1] = color;
  4289. imageData[(x + width * y) * 4 + 2] = color;
  4290. imageData[(x + width * y) * 4 + 3] = 255;
  4291. }
  4292. }
  4293. return imageData;
  4294. };
  4295. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4296. var image = pixel_data;
  4297. var width = header.width, height = header.height;
  4298. var i = 0, x, y;
  4299. var imageData = new Uint8Array(width * height * 4);
  4300. for (y = y_start; y !== y_end; y += y_step) {
  4301. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4302. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4303. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4304. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4305. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4306. }
  4307. }
  4308. return imageData;
  4309. };
  4310. TGATools._TYPE_NO_DATA = 0;
  4311. TGATools._TYPE_INDEXED = 1;
  4312. TGATools._TYPE_RGB = 2;
  4313. TGATools._TYPE_GREY = 3;
  4314. TGATools._TYPE_RLE_INDEXED = 9;
  4315. TGATools._TYPE_RLE_RGB = 10;
  4316. TGATools._TYPE_RLE_GREY = 11;
  4317. TGATools._ORIGIN_MASK = 0x30;
  4318. TGATools._ORIGIN_SHIFT = 0x04;
  4319. TGATools._ORIGIN_BL = 0x00;
  4320. TGATools._ORIGIN_BR = 0x01;
  4321. TGATools._ORIGIN_UL = 0x02;
  4322. TGATools._ORIGIN_UR = 0x03;
  4323. return TGATools;
  4324. }());
  4325. Internals.TGATools = TGATools;
  4326. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4327. })(BABYLON || (BABYLON = {}));
  4328. var BABYLON;
  4329. (function (BABYLON) {
  4330. var SmartArray = (function () {
  4331. function SmartArray(capacity) {
  4332. this.length = 0;
  4333. this._duplicateId = 0;
  4334. this.data = new Array(capacity);
  4335. this._id = SmartArray._GlobalId++;
  4336. }
  4337. SmartArray.prototype.push = function (value) {
  4338. this.data[this.length++] = value;
  4339. if (this.length > this.data.length) {
  4340. this.data.length *= 2;
  4341. }
  4342. if (!value.__smartArrayFlags) {
  4343. value.__smartArrayFlags = {};
  4344. }
  4345. value.__smartArrayFlags[this._id] = this._duplicateId;
  4346. };
  4347. SmartArray.prototype.pushNoDuplicate = function (value) {
  4348. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4349. return false;
  4350. }
  4351. this.push(value);
  4352. return true;
  4353. };
  4354. SmartArray.prototype.sort = function (compareFn) {
  4355. this.data.sort(compareFn);
  4356. };
  4357. SmartArray.prototype.reset = function () {
  4358. this.length = 0;
  4359. this._duplicateId++;
  4360. };
  4361. SmartArray.prototype.concat = function (array) {
  4362. if (array.length === 0) {
  4363. return;
  4364. }
  4365. if (this.length + array.length > this.data.length) {
  4366. this.data.length = (this.length + array.length) * 2;
  4367. }
  4368. for (var index = 0; index < array.length; index++) {
  4369. this.data[this.length++] = (array.data || array)[index];
  4370. }
  4371. };
  4372. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4373. if (array.length === 0) {
  4374. return;
  4375. }
  4376. if (this.length + array.length > this.data.length) {
  4377. this.data.length = (this.length + array.length) * 2;
  4378. }
  4379. for (var index = 0; index < array.length; index++) {
  4380. var item = (array.data || array)[index];
  4381. this.pushNoDuplicate(item);
  4382. }
  4383. };
  4384. SmartArray.prototype.indexOf = function (value) {
  4385. var position = this.data.indexOf(value);
  4386. if (position >= this.length) {
  4387. return -1;
  4388. }
  4389. return position;
  4390. };
  4391. // Statics
  4392. SmartArray._GlobalId = 0;
  4393. return SmartArray;
  4394. }());
  4395. BABYLON.SmartArray = SmartArray;
  4396. })(BABYLON || (BABYLON = {}));
  4397. var BABYLON;
  4398. (function (BABYLON) {
  4399. /**
  4400. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4401. * The underlying implementation relies on an associative array to ensure the best performances.
  4402. * The value can be anything including 'null' but except 'undefined'
  4403. */
  4404. var StringDictionary = (function () {
  4405. function StringDictionary() {
  4406. this._count = 0;
  4407. this._data = {};
  4408. }
  4409. /**
  4410. * This will clear this dictionary and copy the content from the 'source' one.
  4411. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4412. * @param source the dictionary to take the content from and copy to this dictionary
  4413. */
  4414. StringDictionary.prototype.copyFrom = function (source) {
  4415. var _this = this;
  4416. this.clear();
  4417. source.forEach(function (t, v) { return _this.add(t, v); });
  4418. };
  4419. /**
  4420. * Get a value based from its key
  4421. * @param key the given key to get the matching value from
  4422. * @return the value if found, otherwise undefined is returned
  4423. */
  4424. StringDictionary.prototype.get = function (key) {
  4425. var val = this._data[key];
  4426. if (val !== undefined) {
  4427. return val;
  4428. }
  4429. return undefined;
  4430. };
  4431. /**
  4432. * Get a value from its key or add it if it doesn't exist.
  4433. * This method will ensure you that a given key/data will be present in the dictionary.
  4434. * @param key the given key to get the matching value from
  4435. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4436. * The factory will only be invoked if there's no data for the given key.
  4437. * @return the value corresponding to the key.
  4438. */
  4439. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4440. var val = this.get(key);
  4441. if (val !== undefined) {
  4442. return val;
  4443. }
  4444. val = factory(key);
  4445. if (val) {
  4446. this.add(key, val);
  4447. }
  4448. return val;
  4449. };
  4450. /**
  4451. * Get a value from its key if present in the dictionary otherwise add it
  4452. * @param key the key to get the value from
  4453. * @param val if there's no such key/value pair in the dictionary add it with this value
  4454. * @return the value corresponding to the key
  4455. */
  4456. StringDictionary.prototype.getOrAdd = function (key, val) {
  4457. var curVal = this.get(key);
  4458. if (curVal !== undefined) {
  4459. return curVal;
  4460. }
  4461. this.add(key, val);
  4462. return val;
  4463. };
  4464. /**
  4465. * Check if there's a given key in the dictionary
  4466. * @param key the key to check for
  4467. * @return true if the key is present, false otherwise
  4468. */
  4469. StringDictionary.prototype.contains = function (key) {
  4470. return this._data[key] !== undefined;
  4471. };
  4472. /**
  4473. * Add a new key and its corresponding value
  4474. * @param key the key to add
  4475. * @param value the value corresponding to the key
  4476. * @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
  4477. */
  4478. StringDictionary.prototype.add = function (key, value) {
  4479. if (this._data[key] !== undefined) {
  4480. return false;
  4481. }
  4482. this._data[key] = value;
  4483. ++this._count;
  4484. return true;
  4485. };
  4486. StringDictionary.prototype.set = function (key, value) {
  4487. if (this._data[key] === undefined) {
  4488. return false;
  4489. }
  4490. this._data[key] = value;
  4491. return true;
  4492. };
  4493. /**
  4494. * Get the element of the given key and remove it from the dictionary
  4495. * @param key
  4496. */
  4497. StringDictionary.prototype.getAndRemove = function (key) {
  4498. var val = this.get(key);
  4499. if (val !== undefined) {
  4500. delete this._data[key];
  4501. --this._count;
  4502. return val;
  4503. }
  4504. return null;
  4505. };
  4506. /**
  4507. * Remove a key/value from the dictionary.
  4508. * @param key the key to remove
  4509. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4510. */
  4511. StringDictionary.prototype.remove = function (key) {
  4512. if (this.contains(key)) {
  4513. delete this._data[key];
  4514. --this._count;
  4515. return true;
  4516. }
  4517. return false;
  4518. };
  4519. /**
  4520. * Clear the whole content of the dictionary
  4521. */
  4522. StringDictionary.prototype.clear = function () {
  4523. this._data = {};
  4524. this._count = 0;
  4525. };
  4526. Object.defineProperty(StringDictionary.prototype, "count", {
  4527. get: function () {
  4528. return this._count;
  4529. },
  4530. enumerable: true,
  4531. configurable: true
  4532. });
  4533. /**
  4534. * Execute a callback on each key/val of the dictionary.
  4535. * Note that you can remove any element in this dictionary in the callback implementation
  4536. * @param callback the callback to execute on a given key/value pair
  4537. */
  4538. StringDictionary.prototype.forEach = function (callback) {
  4539. for (var cur in this._data) {
  4540. var val = this._data[cur];
  4541. callback(cur, val);
  4542. }
  4543. };
  4544. /**
  4545. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4546. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4547. * Note that you can remove any element in this dictionary in the callback implementation
  4548. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4549. */
  4550. StringDictionary.prototype.first = function (callback) {
  4551. for (var cur in this._data) {
  4552. var val = this._data[cur];
  4553. var res = callback(cur, val);
  4554. if (res) {
  4555. return res;
  4556. }
  4557. }
  4558. return null;
  4559. };
  4560. return StringDictionary;
  4561. }());
  4562. BABYLON.StringDictionary = StringDictionary;
  4563. })(BABYLON || (BABYLON = {}));
  4564. var BABYLON;
  4565. (function (BABYLON) {
  4566. // Screenshots
  4567. var screenshotCanvas;
  4568. var cloneValue = function (source, destinationObject) {
  4569. if (!source)
  4570. return null;
  4571. if (source instanceof BABYLON.Mesh) {
  4572. return null;
  4573. }
  4574. if (source instanceof BABYLON.SubMesh) {
  4575. return source.clone(destinationObject);
  4576. }
  4577. else if (source.clone) {
  4578. return source.clone();
  4579. }
  4580. return null;
  4581. };
  4582. var Tools = (function () {
  4583. function Tools() {
  4584. }
  4585. Tools.Instantiate = function (className) {
  4586. var arr = className.split(".");
  4587. var fn = (window || this);
  4588. for (var i = 0, len = arr.length; i < len; i++) {
  4589. fn = fn[arr[i]];
  4590. }
  4591. if (typeof fn !== "function") {
  4592. return null;
  4593. }
  4594. return fn;
  4595. };
  4596. Tools.SetImmediate = function (action) {
  4597. if (window.setImmediate) {
  4598. window.setImmediate(action);
  4599. }
  4600. else {
  4601. setTimeout(action, 1);
  4602. }
  4603. };
  4604. Tools.IsExponentOfTwo = function (value) {
  4605. var count = 1;
  4606. do {
  4607. count *= 2;
  4608. } while (count < value);
  4609. return count === value;
  4610. };
  4611. Tools.GetExponentOfTwo = function (value, max) {
  4612. var count = 1;
  4613. do {
  4614. count *= 2;
  4615. } while (count < value);
  4616. if (count > max)
  4617. count = max;
  4618. return count;
  4619. };
  4620. Tools.GetFilename = function (path) {
  4621. var index = path.lastIndexOf("/");
  4622. if (index < 0)
  4623. return path;
  4624. return path.substring(index + 1);
  4625. };
  4626. Tools.GetDOMTextContent = function (element) {
  4627. var result = "";
  4628. var child = element.firstChild;
  4629. while (child) {
  4630. if (child.nodeType === 3) {
  4631. result += child.textContent;
  4632. }
  4633. child = child.nextSibling;
  4634. }
  4635. return result;
  4636. };
  4637. Tools.ToDegrees = function (angle) {
  4638. return angle * 180 / Math.PI;
  4639. };
  4640. Tools.ToRadians = function (angle) {
  4641. return angle * Math.PI / 180;
  4642. };
  4643. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4644. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4645. var output = "";
  4646. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4647. var i = 0;
  4648. var bytes = new Uint8Array(buffer);
  4649. while (i < bytes.length) {
  4650. chr1 = bytes[i++];
  4651. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4652. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4653. enc1 = chr1 >> 2;
  4654. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4655. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4656. enc4 = chr3 & 63;
  4657. if (isNaN(chr2)) {
  4658. enc3 = enc4 = 64;
  4659. }
  4660. else if (isNaN(chr3)) {
  4661. enc4 = 64;
  4662. }
  4663. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4664. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4665. }
  4666. return "data:image/png;base64," + output;
  4667. };
  4668. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4669. if (bias === void 0) { bias = null; }
  4670. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4671. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4672. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4673. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4674. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4675. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4676. }
  4677. if (bias) {
  4678. minimum.x -= minimum.x * bias.x + bias.y;
  4679. minimum.y -= minimum.y * bias.x + bias.y;
  4680. minimum.z -= minimum.z * bias.x + bias.y;
  4681. maximum.x += maximum.x * bias.x + bias.y;
  4682. maximum.y += maximum.y * bias.x + bias.y;
  4683. maximum.z += maximum.z * bias.x + bias.y;
  4684. }
  4685. return {
  4686. minimum: minimum,
  4687. maximum: maximum
  4688. };
  4689. };
  4690. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4691. if (bias === void 0) { bias = null; }
  4692. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4693. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4694. if (!stride) {
  4695. stride = 3;
  4696. }
  4697. for (var index = start; index < start + count; index++) {
  4698. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4699. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4700. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4701. }
  4702. if (bias) {
  4703. minimum.x -= minimum.x * bias.x + bias.y;
  4704. minimum.y -= minimum.y * bias.x + bias.y;
  4705. minimum.z -= minimum.z * bias.x + bias.y;
  4706. maximum.x += maximum.x * bias.x + bias.y;
  4707. maximum.y += maximum.y * bias.x + bias.y;
  4708. maximum.z += maximum.z * bias.x + bias.y;
  4709. }
  4710. return {
  4711. minimum: minimum,
  4712. maximum: maximum
  4713. };
  4714. };
  4715. Tools.Vector2ArrayFeeder = function (array) {
  4716. return function (index) {
  4717. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4718. var length = isFloatArray ? array.length / 2 : array.length;
  4719. if (index >= length) {
  4720. return null;
  4721. }
  4722. if (isFloatArray) {
  4723. var fa = array;
  4724. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4725. }
  4726. var a = array;
  4727. return a[index];
  4728. };
  4729. };
  4730. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4731. if (bias === void 0) { bias = null; }
  4732. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4733. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4734. var i = 0;
  4735. var cur = feeder(i++);
  4736. while (cur) {
  4737. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4738. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4739. cur = feeder(i++);
  4740. }
  4741. if (bias) {
  4742. minimum.x -= minimum.x * bias.x + bias.y;
  4743. minimum.y -= minimum.y * bias.x + bias.y;
  4744. maximum.x += maximum.x * bias.x + bias.y;
  4745. maximum.y += maximum.y * bias.x + bias.y;
  4746. }
  4747. return {
  4748. minimum: minimum,
  4749. maximum: maximum
  4750. };
  4751. };
  4752. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4753. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4754. return undefined;
  4755. return Array.isArray(obj) ? obj : [obj];
  4756. };
  4757. // Misc.
  4758. Tools.GetPointerPrefix = function () {
  4759. var eventPrefix = "pointer";
  4760. // Check if pointer events are supported
  4761. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4762. eventPrefix = "mouse";
  4763. }
  4764. return eventPrefix;
  4765. };
  4766. /**
  4767. * @param func - the function to be called
  4768. * @param requester - the object that will request the next frame. Falls back to window.
  4769. */
  4770. Tools.QueueNewFrame = function (func, requester) {
  4771. if (requester === void 0) { requester = window; }
  4772. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4773. /*if(requester.isPresenting) {
  4774. return;
  4775. } else*/ if (requester.requestAnimationFrame)
  4776. requester.requestAnimationFrame(func);
  4777. else if (requester.msRequestAnimationFrame)
  4778. requester.msRequestAnimationFrame(func);
  4779. else if (requester.webkitRequestAnimationFrame)
  4780. requester.webkitRequestAnimationFrame(func);
  4781. else if (requester.mozRequestAnimationFrame)
  4782. requester.mozRequestAnimationFrame(func);
  4783. else if (requester.oRequestAnimationFrame)
  4784. requester.oRequestAnimationFrame(func);
  4785. else {
  4786. window.setTimeout(func, 16);
  4787. }
  4788. };
  4789. Tools.RequestFullscreen = function (element) {
  4790. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4791. if (!requestFunction)
  4792. return;
  4793. requestFunction.call(element);
  4794. };
  4795. Tools.ExitFullscreen = function () {
  4796. if (document.exitFullscreen) {
  4797. document.exitFullscreen();
  4798. }
  4799. else if (document.mozCancelFullScreen) {
  4800. document.mozCancelFullScreen();
  4801. }
  4802. else if (document.webkitCancelFullScreen) {
  4803. document.webkitCancelFullScreen();
  4804. }
  4805. else if (document.msCancelFullScreen) {
  4806. document.msCancelFullScreen();
  4807. }
  4808. };
  4809. Tools.SetCorsBehavior = function (url, img) {
  4810. if (Tools.CorsBehavior) {
  4811. switch (typeof (Tools.CorsBehavior)) {
  4812. case "function":
  4813. var result = Tools.CorsBehavior(url);
  4814. if (result) {
  4815. return result;
  4816. }
  4817. break;
  4818. case "string":
  4819. default:
  4820. img.crossOrigin = Tools.CorsBehavior;
  4821. break;
  4822. }
  4823. }
  4824. };
  4825. // External files
  4826. Tools.CleanUrl = function (url) {
  4827. url = url.replace(/#/mg, "%23");
  4828. return url;
  4829. };
  4830. Tools.LoadImage = function (url, onload, onerror, database) {
  4831. if (url instanceof ArrayBuffer) {
  4832. url = Tools.EncodeArrayBufferTobase64(url);
  4833. }
  4834. url = Tools.CleanUrl(url);
  4835. var img = new Image();
  4836. if (url.substr(0, 5) !== "data:") {
  4837. Tools.SetCorsBehavior(url, img);
  4838. }
  4839. img.onload = function () {
  4840. onload(img);
  4841. };
  4842. img.onerror = function (err) {
  4843. Tools.Error("Error while trying to load texture: " + url);
  4844. if (Tools.UseFallbackTexture) {
  4845. 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";
  4846. onload(img);
  4847. }
  4848. else {
  4849. onerror();
  4850. }
  4851. };
  4852. var noIndexedDB = function () {
  4853. img.src = url;
  4854. };
  4855. var loadFromIndexedDB = function () {
  4856. database.loadImageFromDB(url, img);
  4857. };
  4858. //ANY database to do!
  4859. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4860. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4861. }
  4862. else {
  4863. if (url.indexOf("file:") === -1) {
  4864. noIndexedDB();
  4865. }
  4866. else {
  4867. try {
  4868. var textureName = url.substring(5).toLowerCase();
  4869. var blobURL;
  4870. try {
  4871. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4872. }
  4873. catch (ex) {
  4874. // Chrome doesn't support oneTimeOnly parameter
  4875. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4876. }
  4877. img.src = blobURL;
  4878. }
  4879. catch (e) {
  4880. img.src = null;
  4881. }
  4882. }
  4883. }
  4884. return img;
  4885. };
  4886. //ANY
  4887. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4888. url = Tools.CleanUrl(url);
  4889. var noIndexedDB = function () {
  4890. var request = new XMLHttpRequest();
  4891. var loadUrl = Tools.BaseUrl + url;
  4892. request.open('GET', loadUrl, true);
  4893. if (useArrayBuffer) {
  4894. request.responseType = "arraybuffer";
  4895. }
  4896. request.onprogress = progressCallBack;
  4897. request.onreadystatechange = function () {
  4898. if (request.readyState === 4) {
  4899. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4900. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4901. callback(!useArrayBuffer ? request.responseText : request.response);
  4902. }
  4903. else {
  4904. if (onError) {
  4905. onError();
  4906. }
  4907. else {
  4908. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4909. }
  4910. }
  4911. }
  4912. };
  4913. request.send(null);
  4914. };
  4915. var loadFromIndexedDB = function () {
  4916. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4917. };
  4918. if (url.indexOf("file:") !== -1) {
  4919. var fileName = url.substring(5).toLowerCase();
  4920. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4921. }
  4922. else {
  4923. // Caching all files
  4924. if (database && database.enableSceneOffline) {
  4925. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4926. }
  4927. else {
  4928. noIndexedDB();
  4929. }
  4930. }
  4931. };
  4932. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4933. var reader = new FileReader();
  4934. reader.onload = function (e) {
  4935. //target doesn't have result from ts 1.3
  4936. callback(e.target['result']);
  4937. };
  4938. reader.onprogress = progressCallback;
  4939. reader.readAsDataURL(fileToLoad);
  4940. };
  4941. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4942. var reader = new FileReader();
  4943. reader.onerror = function (e) {
  4944. Tools.Log("Error while reading file: " + fileToLoad.name);
  4945. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4946. };
  4947. reader.onload = function (e) {
  4948. //target doesn't have result from ts 1.3
  4949. callback(e.target['result']);
  4950. };
  4951. reader.onprogress = progressCallBack;
  4952. if (!useArrayBuffer) {
  4953. // Asynchronous read
  4954. reader.readAsText(fileToLoad);
  4955. }
  4956. else {
  4957. reader.readAsArrayBuffer(fileToLoad);
  4958. }
  4959. };
  4960. //returns a downloadable url to a file content.
  4961. Tools.FileAsURL = function (content) {
  4962. var fileBlob = new Blob([content]);
  4963. var url = window.URL || window.webkitURL;
  4964. var link = url.createObjectURL(fileBlob);
  4965. return link;
  4966. };
  4967. // Misc.
  4968. Tools.Format = function (value, decimals) {
  4969. if (decimals === void 0) { decimals = 2; }
  4970. return value.toFixed(decimals);
  4971. };
  4972. Tools.CheckExtends = function (v, min, max) {
  4973. if (v.x < min.x)
  4974. min.x = v.x;
  4975. if (v.y < min.y)
  4976. min.y = v.y;
  4977. if (v.z < min.z)
  4978. min.z = v.z;
  4979. if (v.x > max.x)
  4980. max.x = v.x;
  4981. if (v.y > max.y)
  4982. max.y = v.y;
  4983. if (v.z > max.z)
  4984. max.z = v.z;
  4985. };
  4986. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4987. for (var prop in source) {
  4988. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4989. continue;
  4990. }
  4991. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4992. continue;
  4993. }
  4994. var sourceValue = source[prop];
  4995. var typeOfSourceValue = typeof sourceValue;
  4996. if (typeOfSourceValue === "function") {
  4997. continue;
  4998. }
  4999. if (typeOfSourceValue === "object") {
  5000. if (sourceValue instanceof Array) {
  5001. destination[prop] = [];
  5002. if (sourceValue.length > 0) {
  5003. if (typeof sourceValue[0] == "object") {
  5004. for (var index = 0; index < sourceValue.length; index++) {
  5005. var clonedValue = cloneValue(sourceValue[index], destination);
  5006. if (destination[prop].indexOf(clonedValue) === -1) {
  5007. destination[prop].push(clonedValue);
  5008. }
  5009. }
  5010. }
  5011. else {
  5012. destination[prop] = sourceValue.slice(0);
  5013. }
  5014. }
  5015. }
  5016. else {
  5017. destination[prop] = cloneValue(sourceValue, destination);
  5018. }
  5019. }
  5020. else {
  5021. destination[prop] = sourceValue;
  5022. }
  5023. }
  5024. };
  5025. Tools.IsEmpty = function (obj) {
  5026. for (var i in obj) {
  5027. return false;
  5028. }
  5029. return true;
  5030. };
  5031. Tools.RegisterTopRootEvents = function (events) {
  5032. for (var index = 0; index < events.length; index++) {
  5033. var event = events[index];
  5034. window.addEventListener(event.name, event.handler, false);
  5035. try {
  5036. if (window.parent) {
  5037. window.parent.addEventListener(event.name, event.handler, false);
  5038. }
  5039. }
  5040. catch (e) {
  5041. }
  5042. }
  5043. };
  5044. Tools.UnregisterTopRootEvents = function (events) {
  5045. for (var index = 0; index < events.length; index++) {
  5046. var event = events[index];
  5047. window.removeEventListener(event.name, event.handler);
  5048. try {
  5049. if (window.parent) {
  5050. window.parent.removeEventListener(event.name, event.handler);
  5051. }
  5052. }
  5053. catch (e) {
  5054. }
  5055. }
  5056. };
  5057. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5058. if (mimeType === void 0) { mimeType = "image/png"; }
  5059. // Read the contents of the framebuffer
  5060. var numberOfChannelsByLine = width * 4;
  5061. var halfHeight = height / 2;
  5062. //Reading datas from WebGL
  5063. var data = engine.readPixels(0, 0, width, height);
  5064. //To flip image on Y axis.
  5065. for (var i = 0; i < halfHeight; i++) {
  5066. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5067. var currentCell = j + i * numberOfChannelsByLine;
  5068. var targetLine = height - i - 1;
  5069. var targetCell = j + targetLine * numberOfChannelsByLine;
  5070. var temp = data[currentCell];
  5071. data[currentCell] = data[targetCell];
  5072. data[targetCell] = temp;
  5073. }
  5074. }
  5075. // Create a 2D canvas to store the result
  5076. if (!screenshotCanvas) {
  5077. screenshotCanvas = document.createElement('canvas');
  5078. }
  5079. screenshotCanvas.width = width;
  5080. screenshotCanvas.height = height;
  5081. var context = screenshotCanvas.getContext('2d');
  5082. // Copy the pixels to a 2D canvas
  5083. var imageData = context.createImageData(width, height);
  5084. var castData = (imageData.data);
  5085. castData.set(data);
  5086. context.putImageData(imageData, 0, 0);
  5087. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5088. };
  5089. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5090. if (mimeType === void 0) { mimeType = "image/png"; }
  5091. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5092. if (successCallback) {
  5093. successCallback(base64Image);
  5094. }
  5095. else {
  5096. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5097. if (("download" in document.createElement("a"))) {
  5098. var a = window.document.createElement("a");
  5099. a.href = base64Image;
  5100. var date = new Date();
  5101. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5102. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5103. window.document.body.appendChild(a);
  5104. a.addEventListener("click", function () {
  5105. a.parentElement.removeChild(a);
  5106. });
  5107. a.click();
  5108. }
  5109. else {
  5110. var newWindow = window.open("");
  5111. var img = newWindow.document.createElement("img");
  5112. img.src = base64Image;
  5113. newWindow.document.body.appendChild(img);
  5114. }
  5115. }
  5116. };
  5117. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5118. if (mimeType === void 0) { mimeType = "image/png"; }
  5119. var width;
  5120. var height;
  5121. // If a precision value is specified
  5122. if (size.precision) {
  5123. width = Math.round(engine.getRenderWidth() * size.precision);
  5124. height = Math.round(width / engine.getAspectRatio(camera));
  5125. }
  5126. else if (size.width && size.height) {
  5127. width = size.width;
  5128. height = size.height;
  5129. }
  5130. else if (size.width && !size.height) {
  5131. width = size.width;
  5132. height = Math.round(width / engine.getAspectRatio(camera));
  5133. }
  5134. else if (size.height && !size.width) {
  5135. height = size.height;
  5136. width = Math.round(height * engine.getAspectRatio(camera));
  5137. }
  5138. else if (!isNaN(size)) {
  5139. height = size;
  5140. width = size;
  5141. }
  5142. else {
  5143. Tools.Error("Invalid 'size' parameter !");
  5144. return;
  5145. }
  5146. if (!screenshotCanvas) {
  5147. screenshotCanvas = document.createElement('canvas');
  5148. }
  5149. screenshotCanvas.width = width;
  5150. screenshotCanvas.height = height;
  5151. var renderContext = screenshotCanvas.getContext("2d");
  5152. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5153. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5154. };
  5155. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5156. if (mimeType === void 0) { mimeType = "image/png"; }
  5157. var width;
  5158. var height;
  5159. //If a precision value is specified
  5160. if (size.precision) {
  5161. width = Math.round(engine.getRenderWidth() * size.precision);
  5162. height = Math.round(width / engine.getAspectRatio(camera));
  5163. size = { width: width, height: height };
  5164. }
  5165. else if (size.width && size.height) {
  5166. width = size.width;
  5167. height = size.height;
  5168. }
  5169. else if (size.width && !size.height) {
  5170. width = size.width;
  5171. height = Math.round(width / engine.getAspectRatio(camera));
  5172. size = { width: width, height: height };
  5173. }
  5174. else if (size.height && !size.width) {
  5175. height = size.height;
  5176. width = Math.round(height * engine.getAspectRatio(camera));
  5177. size = { width: width, height: height };
  5178. }
  5179. else if (!isNaN(size)) {
  5180. height = size;
  5181. width = size;
  5182. }
  5183. else {
  5184. Tools.Error("Invalid 'size' parameter !");
  5185. return;
  5186. }
  5187. var scene = camera.getScene();
  5188. var previousCamera = null;
  5189. if (scene.activeCamera !== camera) {
  5190. previousCamera = scene.activeCamera;
  5191. scene.activeCamera = camera;
  5192. }
  5193. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5194. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5195. texture.renderList = scene.meshes;
  5196. texture.onAfterRenderObservable.add(function () {
  5197. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5198. });
  5199. scene.incrementRenderId();
  5200. scene.resetCachedMaterial();
  5201. texture.render(true);
  5202. texture.dispose();
  5203. if (previousCamera) {
  5204. scene.activeCamera = previousCamera;
  5205. }
  5206. camera.getProjectionMatrix(true); // Force cache refresh;
  5207. };
  5208. // XHR response validator for local file scenario
  5209. Tools.ValidateXHRData = function (xhr, dataType) {
  5210. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5211. if (dataType === void 0) { dataType = 7; }
  5212. try {
  5213. if (dataType & 1) {
  5214. if (xhr.responseText && xhr.responseText.length > 0) {
  5215. return true;
  5216. }
  5217. else if (dataType === 1) {
  5218. return false;
  5219. }
  5220. }
  5221. if (dataType & 2) {
  5222. // Check header width and height since there is no "TGA" magic number
  5223. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5224. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5225. return true;
  5226. }
  5227. else if (dataType === 2) {
  5228. return false;
  5229. }
  5230. }
  5231. if (dataType & 4) {
  5232. // Check for the "DDS" magic number
  5233. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5234. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5235. return true;
  5236. }
  5237. else {
  5238. return false;
  5239. }
  5240. }
  5241. }
  5242. catch (e) {
  5243. }
  5244. return false;
  5245. };
  5246. /**
  5247. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5248. * Be aware Math.random() could cause collisions, but:
  5249. * "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"
  5250. */
  5251. Tools.RandomId = function () {
  5252. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5253. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5254. return v.toString(16);
  5255. });
  5256. };
  5257. Object.defineProperty(Tools, "NoneLogLevel", {
  5258. get: function () {
  5259. return Tools._NoneLogLevel;
  5260. },
  5261. enumerable: true,
  5262. configurable: true
  5263. });
  5264. Object.defineProperty(Tools, "MessageLogLevel", {
  5265. get: function () {
  5266. return Tools._MessageLogLevel;
  5267. },
  5268. enumerable: true,
  5269. configurable: true
  5270. });
  5271. Object.defineProperty(Tools, "WarningLogLevel", {
  5272. get: function () {
  5273. return Tools._WarningLogLevel;
  5274. },
  5275. enumerable: true,
  5276. configurable: true
  5277. });
  5278. Object.defineProperty(Tools, "ErrorLogLevel", {
  5279. get: function () {
  5280. return Tools._ErrorLogLevel;
  5281. },
  5282. enumerable: true,
  5283. configurable: true
  5284. });
  5285. Object.defineProperty(Tools, "AllLogLevel", {
  5286. get: function () {
  5287. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5288. },
  5289. enumerable: true,
  5290. configurable: true
  5291. });
  5292. Tools._AddLogEntry = function (entry) {
  5293. Tools._LogCache = entry + Tools._LogCache;
  5294. if (Tools.OnNewCacheEntry) {
  5295. Tools.OnNewCacheEntry(entry);
  5296. }
  5297. };
  5298. Tools._FormatMessage = function (message) {
  5299. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5300. var date = new Date();
  5301. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5302. };
  5303. Tools._LogDisabled = function (message) {
  5304. // nothing to do
  5305. };
  5306. Tools._LogEnabled = function (message) {
  5307. var formattedMessage = Tools._FormatMessage(message);
  5308. console.log("BJS - " + formattedMessage);
  5309. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5310. Tools._AddLogEntry(entry);
  5311. };
  5312. Tools._WarnDisabled = function (message) {
  5313. // nothing to do
  5314. };
  5315. Tools._WarnEnabled = function (message) {
  5316. var formattedMessage = Tools._FormatMessage(message);
  5317. console.warn("BJS - " + formattedMessage);
  5318. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5319. Tools._AddLogEntry(entry);
  5320. };
  5321. Tools._ErrorDisabled = function (message) {
  5322. // nothing to do
  5323. };
  5324. Tools._ErrorEnabled = function (message) {
  5325. Tools.errorsCount++;
  5326. var formattedMessage = Tools._FormatMessage(message);
  5327. console.error("BJS - " + formattedMessage);
  5328. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5329. Tools._AddLogEntry(entry);
  5330. };
  5331. Object.defineProperty(Tools, "LogCache", {
  5332. get: function () {
  5333. return Tools._LogCache;
  5334. },
  5335. enumerable: true,
  5336. configurable: true
  5337. });
  5338. Tools.ClearLogCache = function () {
  5339. Tools._LogCache = "";
  5340. Tools.errorsCount = 0;
  5341. };
  5342. Object.defineProperty(Tools, "LogLevels", {
  5343. set: function (level) {
  5344. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5345. Tools.Log = Tools._LogEnabled;
  5346. }
  5347. else {
  5348. Tools.Log = Tools._LogDisabled;
  5349. }
  5350. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5351. Tools.Warn = Tools._WarnEnabled;
  5352. }
  5353. else {
  5354. Tools.Warn = Tools._WarnDisabled;
  5355. }
  5356. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5357. Tools.Error = Tools._ErrorEnabled;
  5358. }
  5359. else {
  5360. Tools.Error = Tools._ErrorDisabled;
  5361. }
  5362. },
  5363. enumerable: true,
  5364. configurable: true
  5365. });
  5366. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5367. get: function () {
  5368. return Tools._PerformanceNoneLogLevel;
  5369. },
  5370. enumerable: true,
  5371. configurable: true
  5372. });
  5373. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5374. get: function () {
  5375. return Tools._PerformanceUserMarkLogLevel;
  5376. },
  5377. enumerable: true,
  5378. configurable: true
  5379. });
  5380. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5381. get: function () {
  5382. return Tools._PerformanceConsoleLogLevel;
  5383. },
  5384. enumerable: true,
  5385. configurable: true
  5386. });
  5387. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5388. set: function (level) {
  5389. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5390. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5391. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5392. return;
  5393. }
  5394. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5395. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5396. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5397. return;
  5398. }
  5399. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5400. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5406. };
  5407. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5408. };
  5409. Tools._StartUserMark = function (counterName, condition) {
  5410. if (condition === void 0) { condition = true; }
  5411. if (!condition || !Tools._performance.mark) {
  5412. return;
  5413. }
  5414. Tools._performance.mark(counterName + "-Begin");
  5415. };
  5416. Tools._EndUserMark = function (counterName, condition) {
  5417. if (condition === void 0) { condition = true; }
  5418. if (!condition || !Tools._performance.mark) {
  5419. return;
  5420. }
  5421. Tools._performance.mark(counterName + "-End");
  5422. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5423. };
  5424. Tools._StartPerformanceConsole = function (counterName, condition) {
  5425. if (condition === void 0) { condition = true; }
  5426. if (!condition) {
  5427. return;
  5428. }
  5429. Tools._StartUserMark(counterName, condition);
  5430. if (console.time) {
  5431. console.time(counterName);
  5432. }
  5433. };
  5434. Tools._EndPerformanceConsole = function (counterName, condition) {
  5435. if (condition === void 0) { condition = true; }
  5436. if (!condition) {
  5437. return;
  5438. }
  5439. Tools._EndUserMark(counterName, condition);
  5440. if (console.time) {
  5441. console.timeEnd(counterName);
  5442. }
  5443. };
  5444. Object.defineProperty(Tools, "Now", {
  5445. get: function () {
  5446. if (window.performance && window.performance.now) {
  5447. return window.performance.now();
  5448. }
  5449. return new Date().getTime();
  5450. },
  5451. enumerable: true,
  5452. configurable: true
  5453. });
  5454. /**
  5455. * This method will return the name of the class used to create the instance of the given object.
  5456. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5457. * @param object the object to get the class name from
  5458. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5459. */
  5460. Tools.getClassName = function (object, isType) {
  5461. if (isType === void 0) { isType = false; }
  5462. var name = null;
  5463. if (!isType && object.getClassName) {
  5464. name = object.getClassName();
  5465. }
  5466. else {
  5467. if (object instanceof Object) {
  5468. var classObj = isType ? object : Object.getPrototypeOf(object);
  5469. name = classObj.constructor["__bjsclassName__"];
  5470. }
  5471. if (!name) {
  5472. name = typeof object;
  5473. }
  5474. }
  5475. return name;
  5476. };
  5477. Tools.first = function (array, predicate) {
  5478. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5479. var el = array_1[_i];
  5480. if (predicate(el)) {
  5481. return el;
  5482. }
  5483. }
  5484. };
  5485. /**
  5486. * This method will return the name of the full name of the class, including its owning module (if any).
  5487. * 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).
  5488. * @param object the object to get the class name from
  5489. * @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.
  5490. */
  5491. Tools.getFullClassName = function (object, isType) {
  5492. if (isType === void 0) { isType = false; }
  5493. var className = null;
  5494. var moduleName = null;
  5495. if (!isType && object.getClassName) {
  5496. className = object.getClassName();
  5497. }
  5498. else {
  5499. if (object instanceof Object) {
  5500. var classObj = isType ? object : Object.getPrototypeOf(object);
  5501. className = classObj.constructor["__bjsclassName__"];
  5502. moduleName = classObj.constructor["__bjsmoduleName__"];
  5503. }
  5504. if (!className) {
  5505. className = typeof object;
  5506. }
  5507. }
  5508. if (!className) {
  5509. return null;
  5510. }
  5511. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5512. };
  5513. /**
  5514. * 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.
  5515. * @param array
  5516. */
  5517. Tools.arrayOrStringFeeder = function (array) {
  5518. return function (index) {
  5519. if (index >= array.length) {
  5520. return null;
  5521. }
  5522. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5523. if (val && val.getHashCode) {
  5524. val = val.getHashCode();
  5525. }
  5526. if (typeof val === "string") {
  5527. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5528. }
  5529. return val;
  5530. };
  5531. };
  5532. /**
  5533. * Compute the hashCode of a stream of number
  5534. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5535. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5536. * @return the hash code computed
  5537. */
  5538. Tools.hashCodeFromStream = function (feeder) {
  5539. // Based from here: http://stackoverflow.com/a/7616484/802124
  5540. var hash = 0;
  5541. var index = 0;
  5542. var chr = feeder(index++);
  5543. while (chr != null) {
  5544. hash = ((hash << 5) - hash) + chr;
  5545. hash |= 0; // Convert to 32bit integer
  5546. chr = feeder(index++);
  5547. }
  5548. return hash;
  5549. };
  5550. Tools.BaseUrl = "";
  5551. Tools.CorsBehavior = "anonymous";
  5552. Tools.UseFallbackTexture = true;
  5553. // Logs
  5554. Tools._NoneLogLevel = 0;
  5555. Tools._MessageLogLevel = 1;
  5556. Tools._WarningLogLevel = 2;
  5557. Tools._ErrorLogLevel = 4;
  5558. Tools._LogCache = "";
  5559. Tools.errorsCount = 0;
  5560. Tools.Log = Tools._LogEnabled;
  5561. Tools.Warn = Tools._WarnEnabled;
  5562. Tools.Error = Tools._ErrorEnabled;
  5563. // Performances
  5564. Tools._PerformanceNoneLogLevel = 0;
  5565. Tools._PerformanceUserMarkLogLevel = 1;
  5566. Tools._PerformanceConsoleLogLevel = 2;
  5567. Tools._performance = window.performance;
  5568. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5569. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5570. return Tools;
  5571. }());
  5572. BABYLON.Tools = Tools;
  5573. /**
  5574. * This class is used to track a performance counter which is number based.
  5575. * The user has access to many properties which give statistics of different nature
  5576. *
  5577. * The implementer can track two kinds of Performance Counter: time and count
  5578. * 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.
  5579. * 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.
  5580. */
  5581. var PerfCounter = (function () {
  5582. function PerfCounter() {
  5583. this._startMonitoringTime = 0;
  5584. this._min = 0;
  5585. this._max = 0;
  5586. this._average = 0;
  5587. this._lastSecAverage = 0;
  5588. this._current = 0;
  5589. this._totalValueCount = 0;
  5590. this._totalAccumulated = 0;
  5591. this._lastSecAccumulated = 0;
  5592. this._lastSecTime = 0;
  5593. this._lastSecValueCount = 0;
  5594. }
  5595. Object.defineProperty(PerfCounter.prototype, "min", {
  5596. /**
  5597. * Returns the smallest value ever
  5598. */
  5599. get: function () {
  5600. return this._min;
  5601. },
  5602. enumerable: true,
  5603. configurable: true
  5604. });
  5605. Object.defineProperty(PerfCounter.prototype, "max", {
  5606. /**
  5607. * Returns the biggest value ever
  5608. */
  5609. get: function () {
  5610. return this._max;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(PerfCounter.prototype, "average", {
  5616. /**
  5617. * Returns the average value since the performance counter is running
  5618. */
  5619. get: function () {
  5620. return this._average;
  5621. },
  5622. enumerable: true,
  5623. configurable: true
  5624. });
  5625. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5626. /**
  5627. * Returns the average value of the last second the counter was monitored
  5628. */
  5629. get: function () {
  5630. return this._lastSecAverage;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(PerfCounter.prototype, "current", {
  5636. /**
  5637. * Returns the current value
  5638. */
  5639. get: function () {
  5640. return this._current;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. Object.defineProperty(PerfCounter.prototype, "total", {
  5646. get: function () {
  5647. return this._totalAccumulated;
  5648. },
  5649. enumerable: true,
  5650. configurable: true
  5651. });
  5652. /**
  5653. * Call this method to start monitoring a new frame.
  5654. * 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.
  5655. */
  5656. PerfCounter.prototype.fetchNewFrame = function () {
  5657. this._totalValueCount++;
  5658. this._current = 0;
  5659. this._lastSecValueCount++;
  5660. };
  5661. /**
  5662. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5663. * @param newCount the count value to add to the monitored count
  5664. * @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.
  5665. */
  5666. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5667. this._current += newCount;
  5668. if (fetchResult) {
  5669. this._fetchResult();
  5670. }
  5671. };
  5672. /**
  5673. * Start monitoring this performance counter
  5674. */
  5675. PerfCounter.prototype.beginMonitoring = function () {
  5676. this._startMonitoringTime = Tools.Now;
  5677. };
  5678. /**
  5679. * Compute the time lapsed since the previous beginMonitoring() call.
  5680. * @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
  5681. */
  5682. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5683. if (newFrame === void 0) { newFrame = true; }
  5684. if (newFrame) {
  5685. this.fetchNewFrame();
  5686. }
  5687. var currentTime = Tools.Now;
  5688. this._current = currentTime - this._startMonitoringTime;
  5689. if (newFrame) {
  5690. this._fetchResult();
  5691. }
  5692. };
  5693. PerfCounter.prototype._fetchResult = function () {
  5694. this._totalAccumulated += this._current;
  5695. this._lastSecAccumulated += this._current;
  5696. // Min/Max update
  5697. this._min = Math.min(this._min, this._current);
  5698. this._max = Math.max(this._max, this._current);
  5699. this._average = this._totalAccumulated / this._totalValueCount;
  5700. // Reset last sec?
  5701. var now = Tools.Now;
  5702. if ((now - this._lastSecTime) > 1000) {
  5703. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5704. this._lastSecTime = now;
  5705. this._lastSecAccumulated = 0;
  5706. this._lastSecValueCount = 0;
  5707. }
  5708. };
  5709. return PerfCounter;
  5710. }());
  5711. BABYLON.PerfCounter = PerfCounter;
  5712. /**
  5713. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5714. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5715. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5716. * @param name The name of the class, case should be preserved
  5717. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5718. */
  5719. function className(name, module) {
  5720. return function (target) {
  5721. target["__bjsclassName__"] = name;
  5722. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5723. };
  5724. }
  5725. BABYLON.className = className;
  5726. /**
  5727. * An implementation of a loop for asynchronous functions.
  5728. */
  5729. var AsyncLoop = (function () {
  5730. /**
  5731. * Constroctor.
  5732. * @param iterations the number of iterations.
  5733. * @param _fn the function to run each iteration
  5734. * @param _successCallback the callback that will be called upon succesful execution
  5735. * @param offset starting offset.
  5736. */
  5737. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5738. if (offset === void 0) { offset = 0; }
  5739. this.iterations = iterations;
  5740. this._fn = _fn;
  5741. this._successCallback = _successCallback;
  5742. this.index = offset - 1;
  5743. this._done = false;
  5744. }
  5745. /**
  5746. * Execute the next iteration. Must be called after the last iteration was finished.
  5747. */
  5748. AsyncLoop.prototype.executeNext = function () {
  5749. if (!this._done) {
  5750. if (this.index + 1 < this.iterations) {
  5751. ++this.index;
  5752. this._fn(this);
  5753. }
  5754. else {
  5755. this.breakLoop();
  5756. }
  5757. }
  5758. };
  5759. /**
  5760. * Break the loop and run the success callback.
  5761. */
  5762. AsyncLoop.prototype.breakLoop = function () {
  5763. this._done = true;
  5764. this._successCallback();
  5765. };
  5766. /**
  5767. * Helper function
  5768. */
  5769. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5770. if (offset === void 0) { offset = 0; }
  5771. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5772. loop.executeNext();
  5773. return loop;
  5774. };
  5775. /**
  5776. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5777. * @param iterations total number of iterations
  5778. * @param syncedIterations number of synchronous iterations in each async iteration.
  5779. * @param fn the function to call each iteration.
  5780. * @param callback a success call back that will be called when iterating stops.
  5781. * @param breakFunction a break condition (optional)
  5782. * @param timeout timeout settings for the setTimeout function. default - 0.
  5783. * @constructor
  5784. */
  5785. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5786. if (timeout === void 0) { timeout = 0; }
  5787. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5788. if (breakFunction && breakFunction())
  5789. loop.breakLoop();
  5790. else {
  5791. setTimeout(function () {
  5792. for (var i = 0; i < syncedIterations; ++i) {
  5793. var iteration = (loop.index * syncedIterations) + i;
  5794. if (iteration >= iterations)
  5795. break;
  5796. fn(iteration);
  5797. if (breakFunction && breakFunction()) {
  5798. loop.breakLoop();
  5799. break;
  5800. }
  5801. }
  5802. loop.executeNext();
  5803. }, timeout);
  5804. }
  5805. }, callback);
  5806. };
  5807. return AsyncLoop;
  5808. }());
  5809. BABYLON.AsyncLoop = AsyncLoop;
  5810. })(BABYLON || (BABYLON = {}));
  5811. var BABYLON;
  5812. (function (BABYLON) {
  5813. var Internals;
  5814. (function (Internals) {
  5815. var _AlphaState = (function () {
  5816. /**
  5817. * Initializes the state.
  5818. */
  5819. function _AlphaState() {
  5820. this._isAlphaBlendDirty = false;
  5821. this._isBlendFunctionParametersDirty = false;
  5822. this._alphaBlend = false;
  5823. this._blendFunctionParameters = new Array(4);
  5824. this.reset();
  5825. }
  5826. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5827. get: function () {
  5828. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5829. },
  5830. enumerable: true,
  5831. configurable: true
  5832. });
  5833. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5834. get: function () {
  5835. return this._alphaBlend;
  5836. },
  5837. set: function (value) {
  5838. if (this._alphaBlend === value) {
  5839. return;
  5840. }
  5841. this._alphaBlend = value;
  5842. this._isAlphaBlendDirty = true;
  5843. },
  5844. enumerable: true,
  5845. configurable: true
  5846. });
  5847. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5848. if (this._blendFunctionParameters[0] === value0 &&
  5849. this._blendFunctionParameters[1] === value1 &&
  5850. this._blendFunctionParameters[2] === value2 &&
  5851. this._blendFunctionParameters[3] === value3) {
  5852. return;
  5853. }
  5854. this._blendFunctionParameters[0] = value0;
  5855. this._blendFunctionParameters[1] = value1;
  5856. this._blendFunctionParameters[2] = value2;
  5857. this._blendFunctionParameters[3] = value3;
  5858. this._isBlendFunctionParametersDirty = true;
  5859. };
  5860. _AlphaState.prototype.reset = function () {
  5861. this._alphaBlend = false;
  5862. this._blendFunctionParameters[0] = null;
  5863. this._blendFunctionParameters[1] = null;
  5864. this._blendFunctionParameters[2] = null;
  5865. this._blendFunctionParameters[3] = null;
  5866. this._isAlphaBlendDirty = true;
  5867. this._isBlendFunctionParametersDirty = false;
  5868. };
  5869. _AlphaState.prototype.apply = function (gl) {
  5870. if (!this.isDirty) {
  5871. return;
  5872. }
  5873. // Alpha blend
  5874. if (this._isAlphaBlendDirty) {
  5875. if (this._alphaBlend) {
  5876. gl.enable(gl.BLEND);
  5877. }
  5878. else {
  5879. gl.disable(gl.BLEND);
  5880. }
  5881. this._isAlphaBlendDirty = false;
  5882. }
  5883. // Alpha function
  5884. if (this._isBlendFunctionParametersDirty) {
  5885. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5886. this._isBlendFunctionParametersDirty = false;
  5887. }
  5888. };
  5889. return _AlphaState;
  5890. }());
  5891. Internals._AlphaState = _AlphaState;
  5892. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5893. })(BABYLON || (BABYLON = {}));
  5894. var BABYLON;
  5895. (function (BABYLON) {
  5896. var Internals;
  5897. (function (Internals) {
  5898. var _DepthCullingState = (function () {
  5899. /**
  5900. * Initializes the state.
  5901. */
  5902. function _DepthCullingState() {
  5903. this._isDepthTestDirty = false;
  5904. this._isDepthMaskDirty = false;
  5905. this._isDepthFuncDirty = false;
  5906. this._isCullFaceDirty = false;
  5907. this._isCullDirty = false;
  5908. this._isZOffsetDirty = false;
  5909. this.reset();
  5910. }
  5911. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5912. get: function () {
  5913. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5914. },
  5915. enumerable: true,
  5916. configurable: true
  5917. });
  5918. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5919. get: function () {
  5920. return this._zOffset;
  5921. },
  5922. set: function (value) {
  5923. if (this._zOffset === value) {
  5924. return;
  5925. }
  5926. this._zOffset = value;
  5927. this._isZOffsetDirty = true;
  5928. },
  5929. enumerable: true,
  5930. configurable: true
  5931. });
  5932. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5933. get: function () {
  5934. return this._cullFace;
  5935. },
  5936. set: function (value) {
  5937. if (this._cullFace === value) {
  5938. return;
  5939. }
  5940. this._cullFace = value;
  5941. this._isCullFaceDirty = true;
  5942. },
  5943. enumerable: true,
  5944. configurable: true
  5945. });
  5946. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5947. get: function () {
  5948. return this._cull;
  5949. },
  5950. set: function (value) {
  5951. if (this._cull === value) {
  5952. return;
  5953. }
  5954. this._cull = value;
  5955. this._isCullDirty = true;
  5956. },
  5957. enumerable: true,
  5958. configurable: true
  5959. });
  5960. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5961. get: function () {
  5962. return this._depthFunc;
  5963. },
  5964. set: function (value) {
  5965. if (this._depthFunc === value) {
  5966. return;
  5967. }
  5968. this._depthFunc = value;
  5969. this._isDepthFuncDirty = true;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5975. get: function () {
  5976. return this._depthMask;
  5977. },
  5978. set: function (value) {
  5979. if (this._depthMask === value) {
  5980. return;
  5981. }
  5982. this._depthMask = value;
  5983. this._isDepthMaskDirty = true;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5989. get: function () {
  5990. return this._depthTest;
  5991. },
  5992. set: function (value) {
  5993. if (this._depthTest === value) {
  5994. return;
  5995. }
  5996. this._depthTest = value;
  5997. this._isDepthTestDirty = true;
  5998. },
  5999. enumerable: true,
  6000. configurable: true
  6001. });
  6002. _DepthCullingState.prototype.reset = function () {
  6003. this._depthMask = true;
  6004. this._depthTest = true;
  6005. this._depthFunc = null;
  6006. this._cullFace = null;
  6007. this._cull = null;
  6008. this._zOffset = 0;
  6009. this._isDepthTestDirty = true;
  6010. this._isDepthMaskDirty = true;
  6011. this._isDepthFuncDirty = false;
  6012. this._isCullFaceDirty = false;
  6013. this._isCullDirty = false;
  6014. this._isZOffsetDirty = false;
  6015. };
  6016. _DepthCullingState.prototype.apply = function (gl) {
  6017. if (!this.isDirty) {
  6018. return;
  6019. }
  6020. // Cull
  6021. if (this._isCullDirty) {
  6022. if (this.cull) {
  6023. gl.enable(gl.CULL_FACE);
  6024. }
  6025. else {
  6026. gl.disable(gl.CULL_FACE);
  6027. }
  6028. this._isCullDirty = false;
  6029. }
  6030. // Cull face
  6031. if (this._isCullFaceDirty) {
  6032. gl.cullFace(this.cullFace);
  6033. this._isCullFaceDirty = false;
  6034. }
  6035. // Depth mask
  6036. if (this._isDepthMaskDirty) {
  6037. gl.depthMask(this.depthMask);
  6038. this._isDepthMaskDirty = false;
  6039. }
  6040. // Depth test
  6041. if (this._isDepthTestDirty) {
  6042. if (this.depthTest) {
  6043. gl.enable(gl.DEPTH_TEST);
  6044. }
  6045. else {
  6046. gl.disable(gl.DEPTH_TEST);
  6047. }
  6048. this._isDepthTestDirty = false;
  6049. }
  6050. // Depth func
  6051. if (this._isDepthFuncDirty) {
  6052. gl.depthFunc(this.depthFunc);
  6053. this._isDepthFuncDirty = false;
  6054. }
  6055. // zOffset
  6056. if (this._isZOffsetDirty) {
  6057. if (this.zOffset) {
  6058. gl.enable(gl.POLYGON_OFFSET_FILL);
  6059. gl.polygonOffset(this.zOffset, 0);
  6060. }
  6061. else {
  6062. gl.disable(gl.POLYGON_OFFSET_FILL);
  6063. }
  6064. this._isZOffsetDirty = false;
  6065. }
  6066. };
  6067. return _DepthCullingState;
  6068. }());
  6069. Internals._DepthCullingState = _DepthCullingState;
  6070. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6071. })(BABYLON || (BABYLON = {}));
  6072. var BABYLON;
  6073. (function (BABYLON) {
  6074. var Internals;
  6075. (function (Internals) {
  6076. var _StencilState = (function () {
  6077. function _StencilState() {
  6078. this._isStencilTestDirty = false;
  6079. this._isStencilMaskDirty = false;
  6080. this._isStencilFuncDirty = false;
  6081. this._isStencilOpDirty = false;
  6082. this.reset();
  6083. }
  6084. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6085. get: function () {
  6086. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6087. },
  6088. enumerable: true,
  6089. configurable: true
  6090. });
  6091. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6092. get: function () {
  6093. return this._stencilFunc;
  6094. },
  6095. set: function (value) {
  6096. if (this._stencilFunc === value) {
  6097. return;
  6098. }
  6099. this._stencilFunc = value;
  6100. this._isStencilFuncDirty = true;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6106. get: function () {
  6107. return this._stencilFuncRef;
  6108. },
  6109. set: function (value) {
  6110. if (this._stencilFuncRef === value) {
  6111. return;
  6112. }
  6113. this._stencilFuncRef = value;
  6114. this._isStencilFuncDirty = true;
  6115. },
  6116. enumerable: true,
  6117. configurable: true
  6118. });
  6119. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6120. get: function () {
  6121. return this._stencilFuncMask;
  6122. },
  6123. set: function (value) {
  6124. if (this._stencilFuncMask === value) {
  6125. return;
  6126. }
  6127. this._stencilFuncMask = value;
  6128. this._isStencilFuncDirty = true;
  6129. },
  6130. enumerable: true,
  6131. configurable: true
  6132. });
  6133. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6134. get: function () {
  6135. return this._stencilOpStencilFail;
  6136. },
  6137. set: function (value) {
  6138. if (this._stencilOpStencilFail === value) {
  6139. return;
  6140. }
  6141. this._stencilOpStencilFail = value;
  6142. this._isStencilOpDirty = true;
  6143. },
  6144. enumerable: true,
  6145. configurable: true
  6146. });
  6147. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6148. get: function () {
  6149. return this._stencilOpDepthFail;
  6150. },
  6151. set: function (value) {
  6152. if (this._stencilOpDepthFail === value) {
  6153. return;
  6154. }
  6155. this._stencilOpDepthFail = value;
  6156. this._isStencilOpDirty = true;
  6157. },
  6158. enumerable: true,
  6159. configurable: true
  6160. });
  6161. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6162. get: function () {
  6163. return this._stencilOpStencilDepthPass;
  6164. },
  6165. set: function (value) {
  6166. if (this._stencilOpStencilDepthPass === value) {
  6167. return;
  6168. }
  6169. this._stencilOpStencilDepthPass = value;
  6170. this._isStencilOpDirty = true;
  6171. },
  6172. enumerable: true,
  6173. configurable: true
  6174. });
  6175. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6176. get: function () {
  6177. return this._stencilMask;
  6178. },
  6179. set: function (value) {
  6180. if (this._stencilMask === value) {
  6181. return;
  6182. }
  6183. this._stencilMask = value;
  6184. this._isStencilMaskDirty = true;
  6185. },
  6186. enumerable: true,
  6187. configurable: true
  6188. });
  6189. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6190. get: function () {
  6191. return this._stencilTest;
  6192. },
  6193. set: function (value) {
  6194. if (this._stencilTest === value) {
  6195. return;
  6196. }
  6197. this._stencilTest = value;
  6198. this._isStencilTestDirty = true;
  6199. },
  6200. enumerable: true,
  6201. configurable: true
  6202. });
  6203. _StencilState.prototype.reset = function () {
  6204. this._stencilTest = false;
  6205. this._stencilMask = 0xFF;
  6206. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6207. this._stencilFuncRef = 1;
  6208. this._stencilFuncMask = 0xFF;
  6209. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6210. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6211. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6212. this._isStencilTestDirty = true;
  6213. this._isStencilMaskDirty = true;
  6214. this._isStencilFuncDirty = true;
  6215. this._isStencilOpDirty = true;
  6216. };
  6217. _StencilState.prototype.apply = function (gl) {
  6218. if (!this.isDirty) {
  6219. return;
  6220. }
  6221. // Stencil test
  6222. if (this._isStencilTestDirty) {
  6223. if (this.stencilTest) {
  6224. gl.enable(gl.STENCIL_TEST);
  6225. }
  6226. else {
  6227. gl.disable(gl.STENCIL_TEST);
  6228. }
  6229. this._isStencilTestDirty = false;
  6230. }
  6231. // Stencil mask
  6232. if (this._isStencilMaskDirty) {
  6233. gl.stencilMask(this.stencilMask);
  6234. this._isStencilMaskDirty = false;
  6235. }
  6236. // Stencil func
  6237. if (this._isStencilFuncDirty) {
  6238. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6239. this._isStencilFuncDirty = false;
  6240. }
  6241. // Stencil op
  6242. if (this._isStencilOpDirty) {
  6243. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6244. this._isStencilOpDirty = false;
  6245. }
  6246. };
  6247. return _StencilState;
  6248. }());
  6249. Internals._StencilState = _StencilState;
  6250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6251. })(BABYLON || (BABYLON = {}));
  6252. var BABYLON;
  6253. (function (BABYLON) {
  6254. var compileShader = function (gl, source, type, defines) {
  6255. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6256. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6257. gl.compileShader(shader);
  6258. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6259. throw new Error(gl.getShaderInfoLog(shader));
  6260. }
  6261. return shader;
  6262. };
  6263. var HALF_FLOAT_OES = 0x8D61;
  6264. var getWebGLTextureType = function (gl, type) {
  6265. if (type === Engine.TEXTURETYPE_FLOAT) {
  6266. return gl.FLOAT;
  6267. }
  6268. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6269. // Add Half Float Constant.
  6270. return HALF_FLOAT_OES;
  6271. }
  6272. return gl.UNSIGNED_BYTE;
  6273. };
  6274. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6275. var magFilter = gl.NEAREST;
  6276. var minFilter = gl.NEAREST;
  6277. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6278. magFilter = gl.LINEAR;
  6279. if (generateMipMaps) {
  6280. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6281. }
  6282. else {
  6283. minFilter = gl.LINEAR;
  6284. }
  6285. }
  6286. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6287. magFilter = gl.LINEAR;
  6288. if (generateMipMaps) {
  6289. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6290. }
  6291. else {
  6292. minFilter = gl.LINEAR;
  6293. }
  6294. }
  6295. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6296. magFilter = gl.NEAREST;
  6297. if (generateMipMaps) {
  6298. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6299. }
  6300. else {
  6301. minFilter = gl.NEAREST;
  6302. }
  6303. }
  6304. return {
  6305. min: minFilter,
  6306. mag: magFilter
  6307. };
  6308. };
  6309. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6311. var engine = scene.getEngine();
  6312. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6313. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6314. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6315. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6316. texture._baseWidth = width;
  6317. texture._baseHeight = height;
  6318. texture._width = potWidth;
  6319. texture._height = potHeight;
  6320. texture.isReady = true;
  6321. processFunction(potWidth, potHeight);
  6322. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6325. if (!noMipmap && !isCompressed) {
  6326. gl.generateMipmap(gl.TEXTURE_2D);
  6327. }
  6328. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6329. engine.resetTextureCache();
  6330. scene._removePendingData(texture);
  6331. texture.onLoadedCallbacks.forEach(function (callback) {
  6332. callback();
  6333. });
  6334. texture.onLoadedCallbacks = [];
  6335. };
  6336. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6337. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6338. var img;
  6339. var onload = function () {
  6340. loadedImages[index] = img;
  6341. loadedImages._internalCount++;
  6342. scene._removePendingData(img);
  6343. if (loadedImages._internalCount === 6) {
  6344. onfinish(loadedImages);
  6345. }
  6346. };
  6347. var onerror = function () {
  6348. scene._removePendingData(img);
  6349. if (onErrorCallBack) {
  6350. onErrorCallBack();
  6351. }
  6352. };
  6353. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6354. scene._addPendingData(img);
  6355. };
  6356. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6357. if (onError === void 0) { onError = null; }
  6358. var loadedImages = [];
  6359. loadedImages._internalCount = 0;
  6360. for (var index = 0; index < 6; index++) {
  6361. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6362. }
  6363. };
  6364. var InstancingAttributeInfo = (function () {
  6365. function InstancingAttributeInfo() {
  6366. }
  6367. return InstancingAttributeInfo;
  6368. }());
  6369. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6370. var EngineCapabilities = (function () {
  6371. function EngineCapabilities() {
  6372. }
  6373. return EngineCapabilities;
  6374. }());
  6375. BABYLON.EngineCapabilities = EngineCapabilities;
  6376. /**
  6377. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6378. */
  6379. var Engine = (function () {
  6380. /**
  6381. * @constructor
  6382. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6383. * @param {boolean} [antialias] - enable antialias
  6384. * @param options - further options to be sent to the getContext function
  6385. */
  6386. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6387. var _this = this;
  6388. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6389. // Public members
  6390. this.isFullscreen = false;
  6391. this.isPointerLock = false;
  6392. this.cullBackFaces = true;
  6393. this.renderEvenInBackground = true;
  6394. // To enable/disable IDB support and avoid XHR on .manifest
  6395. this.enableOfflineSupport = true;
  6396. this.scenes = new Array();
  6397. this._windowIsBackground = false;
  6398. this._webGLVersion = "1.0";
  6399. this._badOS = false;
  6400. this._drawCalls = new BABYLON.PerfCounter();
  6401. this._renderingQueueLaunched = false;
  6402. this._activeRenderLoops = [];
  6403. // FPS
  6404. this.fpsRange = 60;
  6405. this.previousFramesDuration = [];
  6406. this.fps = 60;
  6407. this.deltaTime = 0;
  6408. // States
  6409. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6410. this._stencilState = new BABYLON.Internals._StencilState();
  6411. this._alphaState = new BABYLON.Internals._AlphaState();
  6412. this._alphaMode = Engine.ALPHA_DISABLE;
  6413. // Cache
  6414. this._loadedTexturesCache = new Array();
  6415. this._maxTextureChannels = 16;
  6416. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6417. this._compiledEffects = {};
  6418. this._vertexAttribArraysEnabled = [];
  6419. this._uintIndicesCurrentlySet = false;
  6420. this._currentBoundBuffer = new Array();
  6421. this._currentBufferPointers = [];
  6422. this._currentInstanceLocations = new Array();
  6423. this._currentInstanceBuffers = new Array();
  6424. this._onVRFullScreenTriggered = function () {
  6425. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6426. //get the old size before we change
  6427. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6428. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6429. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6430. //But actually, no browser follow the specs...
  6431. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6432. //get the width and height, change the render size
  6433. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6434. var width, height;
  6435. _this.setHardwareScalingLevel(1);
  6436. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6437. }
  6438. else {
  6439. //When the specs are implemented, need to uncomment this.
  6440. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6441. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6442. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6443. _this._vrDisplayEnabled = undefined;
  6444. }
  6445. };
  6446. this._renderingCanvas = canvas;
  6447. this._externalData = new BABYLON.StringDictionary();
  6448. options = options || {};
  6449. if (antialias != null) {
  6450. options.antialias = antialias;
  6451. }
  6452. if (options.preserveDrawingBuffer === undefined) {
  6453. options.preserveDrawingBuffer = false;
  6454. }
  6455. // Checks if some of the format renders first to allow the use of webgl inspector.
  6456. var renderToFullFloat = this._canRenderToFloatTexture();
  6457. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6458. // GL
  6459. //try {
  6460. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6461. // if (this._gl) {
  6462. // this._webGLVersion = "2.0";
  6463. // }
  6464. //} catch (e) {
  6465. // // Do nothing
  6466. //}
  6467. if (!this._gl) {
  6468. try {
  6469. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6470. }
  6471. catch (e) {
  6472. throw new Error("WebGL not supported");
  6473. }
  6474. }
  6475. if (!this._gl) {
  6476. throw new Error("WebGL not supported");
  6477. }
  6478. this._onBlur = function () {
  6479. _this._windowIsBackground = true;
  6480. };
  6481. this._onFocus = function () {
  6482. _this._windowIsBackground = false;
  6483. };
  6484. window.addEventListener("blur", this._onBlur);
  6485. window.addEventListener("focus", this._onFocus);
  6486. // Viewport
  6487. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6488. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6489. this.resize();
  6490. // Caps
  6491. this._isStencilEnable = options.stencil;
  6492. this._caps = new EngineCapabilities();
  6493. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6494. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6495. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6496. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6497. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6498. // Infos
  6499. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6500. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6501. if (rendererInfo != null) {
  6502. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6503. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6504. }
  6505. if (!this._glVendor) {
  6506. this._glVendor = "Unknown vendor";
  6507. }
  6508. if (!this._glRenderer) {
  6509. this._glRenderer = "Unknown renderer";
  6510. }
  6511. // Extensions
  6512. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6513. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6514. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6515. 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');
  6516. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6517. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6518. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6519. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6520. this._caps.highPrecisionShaderSupported = true;
  6521. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6522. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6523. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6524. this._caps.textureFloatRender = renderToFullFloat;
  6525. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6526. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6527. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6528. if (this._gl.getShaderPrecisionFormat) {
  6529. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6530. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6531. }
  6532. // Depth buffer
  6533. this.setDepthBuffer(true);
  6534. this.setDepthFunctionToLessOrEqual();
  6535. this.setDepthWrite(true);
  6536. // Fullscreen
  6537. this._onFullscreenChange = function () {
  6538. if (document.fullscreen !== undefined) {
  6539. _this.isFullscreen = document.fullscreen;
  6540. }
  6541. else if (document.mozFullScreen !== undefined) {
  6542. _this.isFullscreen = document.mozFullScreen;
  6543. }
  6544. else if (document.webkitIsFullScreen !== undefined) {
  6545. _this.isFullscreen = document.webkitIsFullScreen;
  6546. }
  6547. else if (document.msIsFullScreen !== undefined) {
  6548. _this.isFullscreen = document.msIsFullScreen;
  6549. }
  6550. // Pointer lock
  6551. if (_this.isFullscreen && _this._pointerLockRequested) {
  6552. canvas.requestPointerLock = canvas.requestPointerLock ||
  6553. canvas.msRequestPointerLock ||
  6554. canvas.mozRequestPointerLock ||
  6555. canvas.webkitRequestPointerLock;
  6556. if (canvas.requestPointerLock) {
  6557. canvas.requestPointerLock();
  6558. }
  6559. }
  6560. };
  6561. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6562. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6563. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6564. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6565. // Pointer lock
  6566. this._onPointerLockChange = function () {
  6567. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6568. document.webkitPointerLockElement === canvas ||
  6569. document.msPointerLockElement === canvas ||
  6570. document.pointerLockElement === canvas);
  6571. };
  6572. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6573. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6574. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6575. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6576. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6577. Engine.audioEngine = new BABYLON.AudioEngine();
  6578. }
  6579. //default loading screen
  6580. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6581. //Load WebVR Devices
  6582. if (options.autoEnableWebVR) {
  6583. this.initWebVR();
  6584. }
  6585. //Detect if we are running on a faulty buggy OS.
  6586. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6587. //ua sniffing is the tool of the devil.
  6588. this._badOS = regexp.test(navigator.userAgent);
  6589. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6590. }
  6591. Object.defineProperty(Engine, "NEVER", {
  6592. get: function () {
  6593. return Engine._NEVER;
  6594. },
  6595. enumerable: true,
  6596. configurable: true
  6597. });
  6598. Object.defineProperty(Engine, "ALWAYS", {
  6599. get: function () {
  6600. return Engine._ALWAYS;
  6601. },
  6602. enumerable: true,
  6603. configurable: true
  6604. });
  6605. Object.defineProperty(Engine, "LESS", {
  6606. get: function () {
  6607. return Engine._LESS;
  6608. },
  6609. enumerable: true,
  6610. configurable: true
  6611. });
  6612. Object.defineProperty(Engine, "EQUAL", {
  6613. get: function () {
  6614. return Engine._EQUAL;
  6615. },
  6616. enumerable: true,
  6617. configurable: true
  6618. });
  6619. Object.defineProperty(Engine, "LEQUAL", {
  6620. get: function () {
  6621. return Engine._LEQUAL;
  6622. },
  6623. enumerable: true,
  6624. configurable: true
  6625. });
  6626. Object.defineProperty(Engine, "GREATER", {
  6627. get: function () {
  6628. return Engine._GREATER;
  6629. },
  6630. enumerable: true,
  6631. configurable: true
  6632. });
  6633. Object.defineProperty(Engine, "GEQUAL", {
  6634. get: function () {
  6635. return Engine._GEQUAL;
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Object.defineProperty(Engine, "NOTEQUAL", {
  6641. get: function () {
  6642. return Engine._NOTEQUAL;
  6643. },
  6644. enumerable: true,
  6645. configurable: true
  6646. });
  6647. Object.defineProperty(Engine, "KEEP", {
  6648. get: function () {
  6649. return Engine._KEEP;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. Object.defineProperty(Engine, "REPLACE", {
  6655. get: function () {
  6656. return Engine._REPLACE;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Engine, "INCR", {
  6662. get: function () {
  6663. return Engine._INCR;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Engine, "DECR", {
  6669. get: function () {
  6670. return Engine._DECR;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Engine, "INVERT", {
  6676. get: function () {
  6677. return Engine._INVERT;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Engine, "INCR_WRAP", {
  6683. get: function () {
  6684. return Engine._INCR_WRAP;
  6685. },
  6686. enumerable: true,
  6687. configurable: true
  6688. });
  6689. Object.defineProperty(Engine, "DECR_WRAP", {
  6690. get: function () {
  6691. return Engine._DECR_WRAP;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6697. get: function () {
  6698. return Engine._ALPHA_DISABLE;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6704. get: function () {
  6705. return Engine._ALPHA_ONEONE;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Object.defineProperty(Engine, "ALPHA_ADD", {
  6711. get: function () {
  6712. return Engine._ALPHA_ADD;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6718. get: function () {
  6719. return Engine._ALPHA_COMBINE;
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6725. get: function () {
  6726. return Engine._ALPHA_SUBTRACT;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6732. get: function () {
  6733. return Engine._ALPHA_MULTIPLY;
  6734. },
  6735. enumerable: true,
  6736. configurable: true
  6737. });
  6738. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6739. get: function () {
  6740. return Engine._ALPHA_MAXIMIZED;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6746. get: function () {
  6747. return Engine._DELAYLOADSTATE_NONE;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6753. get: function () {
  6754. return Engine._DELAYLOADSTATE_LOADED;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6760. get: function () {
  6761. return Engine._DELAYLOADSTATE_LOADING;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6767. get: function () {
  6768. return Engine._DELAYLOADSTATE_NOTLOADED;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6774. get: function () {
  6775. return Engine._TEXTUREFORMAT_ALPHA;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6781. get: function () {
  6782. return Engine._TEXTUREFORMAT_LUMINANCE;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6788. get: function () {
  6789. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6795. get: function () {
  6796. return Engine._TEXTUREFORMAT_RGB;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6802. get: function () {
  6803. return Engine._TEXTUREFORMAT_RGBA;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6809. get: function () {
  6810. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6816. get: function () {
  6817. return Engine._TEXTURETYPE_FLOAT;
  6818. },
  6819. enumerable: true,
  6820. configurable: true
  6821. });
  6822. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6823. get: function () {
  6824. return Engine._TEXTURETYPE_HALF_FLOAT;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(Engine, "Version", {
  6830. get: function () {
  6831. return "2.5.-beta";
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6837. get: function () {
  6838. return this._webGLVersion;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6844. /**
  6845. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6846. */
  6847. get: function () {
  6848. return this._isStencilEnable;
  6849. },
  6850. enumerable: true,
  6851. configurable: true
  6852. });
  6853. Engine.prototype._prepareWorkingCanvas = function () {
  6854. if (this._workingCanvas) {
  6855. return;
  6856. }
  6857. this._workingCanvas = document.createElement("canvas");
  6858. this._workingContext = this._workingCanvas.getContext("2d");
  6859. };
  6860. Engine.prototype.resetTextureCache = function () {
  6861. for (var index = 0; index < this._maxTextureChannels; index++) {
  6862. this._activeTexturesCache[index] = null;
  6863. }
  6864. };
  6865. Engine.prototype.getGlInfo = function () {
  6866. return {
  6867. vendor: this._glVendor,
  6868. renderer: this._glRenderer,
  6869. version: this._glVersion
  6870. };
  6871. };
  6872. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6873. if (useScreen === void 0) { useScreen = false; }
  6874. var viewport = camera.viewport;
  6875. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6876. };
  6877. Engine.prototype.getRenderWidth = function (useScreen) {
  6878. if (useScreen === void 0) { useScreen = false; }
  6879. if (!useScreen && this._currentRenderTarget) {
  6880. return this._currentRenderTarget._width;
  6881. }
  6882. return this._renderingCanvas.width;
  6883. };
  6884. Engine.prototype.getRenderHeight = function (useScreen) {
  6885. if (useScreen === void 0) { useScreen = false; }
  6886. if (!useScreen && this._currentRenderTarget) {
  6887. return this._currentRenderTarget._height;
  6888. }
  6889. return this._renderingCanvas.height;
  6890. };
  6891. Engine.prototype.getRenderingCanvas = function () {
  6892. return this._renderingCanvas;
  6893. };
  6894. Engine.prototype.getRenderingCanvasClientRect = function () {
  6895. return this._renderingCanvas.getBoundingClientRect();
  6896. };
  6897. Engine.prototype.setHardwareScalingLevel = function (level) {
  6898. this._hardwareScalingLevel = level;
  6899. this.resize();
  6900. };
  6901. Engine.prototype.getHardwareScalingLevel = function () {
  6902. return this._hardwareScalingLevel;
  6903. };
  6904. Engine.prototype.getLoadedTexturesCache = function () {
  6905. return this._loadedTexturesCache;
  6906. };
  6907. Engine.prototype.getCaps = function () {
  6908. return this._caps;
  6909. };
  6910. Object.defineProperty(Engine.prototype, "drawCalls", {
  6911. get: function () {
  6912. return this._drawCalls.current;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6918. get: function () {
  6919. return this._drawCalls;
  6920. },
  6921. enumerable: true,
  6922. configurable: true
  6923. });
  6924. Engine.prototype.getDepthFunction = function () {
  6925. return this._depthCullingState.depthFunc;
  6926. };
  6927. Engine.prototype.setDepthFunction = function (depthFunc) {
  6928. this._depthCullingState.depthFunc = depthFunc;
  6929. };
  6930. Engine.prototype.setDepthFunctionToGreater = function () {
  6931. this._depthCullingState.depthFunc = this._gl.GREATER;
  6932. };
  6933. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6934. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6935. };
  6936. Engine.prototype.setDepthFunctionToLess = function () {
  6937. this._depthCullingState.depthFunc = this._gl.LESS;
  6938. };
  6939. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6940. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6941. };
  6942. Engine.prototype.getStencilBuffer = function () {
  6943. return this._stencilState.stencilTest;
  6944. };
  6945. Engine.prototype.setStencilBuffer = function (enable) {
  6946. this._stencilState.stencilTest = enable;
  6947. };
  6948. Engine.prototype.getStencilMask = function () {
  6949. return this._stencilState.stencilMask;
  6950. };
  6951. Engine.prototype.setStencilMask = function (mask) {
  6952. this._stencilState.stencilMask = mask;
  6953. };
  6954. Engine.prototype.getStencilFunction = function () {
  6955. return this._stencilState.stencilFunc;
  6956. };
  6957. Engine.prototype.getStencilFunctionReference = function () {
  6958. return this._stencilState.stencilFuncRef;
  6959. };
  6960. Engine.prototype.getStencilFunctionMask = function () {
  6961. return this._stencilState.stencilFuncMask;
  6962. };
  6963. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6964. this._stencilState.stencilFunc = stencilFunc;
  6965. };
  6966. Engine.prototype.setStencilFunctionReference = function (reference) {
  6967. this._stencilState.stencilFuncRef = reference;
  6968. };
  6969. Engine.prototype.setStencilFunctionMask = function (mask) {
  6970. this._stencilState.stencilFuncMask = mask;
  6971. };
  6972. Engine.prototype.getStencilOperationFail = function () {
  6973. return this._stencilState.stencilOpStencilFail;
  6974. };
  6975. Engine.prototype.getStencilOperationDepthFail = function () {
  6976. return this._stencilState.stencilOpDepthFail;
  6977. };
  6978. Engine.prototype.getStencilOperationPass = function () {
  6979. return this._stencilState.stencilOpStencilDepthPass;
  6980. };
  6981. Engine.prototype.setStencilOperationFail = function (operation) {
  6982. this._stencilState.stencilOpStencilFail = operation;
  6983. };
  6984. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6985. this._stencilState.stencilOpDepthFail = operation;
  6986. };
  6987. Engine.prototype.setStencilOperationPass = function (operation) {
  6988. this._stencilState.stencilOpStencilDepthPass = operation;
  6989. };
  6990. /**
  6991. * stop executing a render loop function and remove it from the execution array
  6992. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6993. */
  6994. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6995. if (!renderFunction) {
  6996. this._activeRenderLoops = [];
  6997. return;
  6998. }
  6999. var index = this._activeRenderLoops.indexOf(renderFunction);
  7000. if (index >= 0) {
  7001. this._activeRenderLoops.splice(index, 1);
  7002. }
  7003. };
  7004. Engine.prototype._renderLoop = function () {
  7005. var shouldRender = true;
  7006. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7007. shouldRender = false;
  7008. }
  7009. if (shouldRender) {
  7010. // Start new frame
  7011. this.beginFrame();
  7012. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7013. var renderFunction = this._activeRenderLoops[index];
  7014. renderFunction();
  7015. }
  7016. // Present
  7017. this.endFrame();
  7018. }
  7019. if (this._activeRenderLoops.length > 0) {
  7020. // Register new frame
  7021. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7022. }
  7023. else {
  7024. this._renderingQueueLaunched = false;
  7025. }
  7026. };
  7027. /**
  7028. * Register and execute a render loop. The engine can have more than one render function.
  7029. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7030. * @example
  7031. * engine.runRenderLoop(function () {
  7032. * scene.render()
  7033. * })
  7034. */
  7035. Engine.prototype.runRenderLoop = function (renderFunction) {
  7036. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7037. return;
  7038. }
  7039. this._activeRenderLoops.push(renderFunction);
  7040. if (!this._renderingQueueLaunched) {
  7041. this._renderingQueueLaunched = true;
  7042. this._bindedRenderFunction = this._renderLoop.bind(this);
  7043. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7044. }
  7045. };
  7046. /**
  7047. * Toggle full screen mode.
  7048. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7049. * @param {any} options - an options object to be sent to the requestFullscreen function
  7050. */
  7051. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7052. if (this.isFullscreen) {
  7053. BABYLON.Tools.ExitFullscreen();
  7054. }
  7055. else {
  7056. this._pointerLockRequested = requestPointerLock;
  7057. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7058. }
  7059. };
  7060. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7061. if (stencil === void 0) { stencil = false; }
  7062. this.applyStates();
  7063. var mode = 0;
  7064. if (backBuffer) {
  7065. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7066. mode |= this._gl.COLOR_BUFFER_BIT;
  7067. }
  7068. if (depth) {
  7069. this._gl.clearDepth(1.0);
  7070. mode |= this._gl.DEPTH_BUFFER_BIT;
  7071. }
  7072. if (stencil) {
  7073. this._gl.clearStencil(0);
  7074. mode |= this._gl.STENCIL_BUFFER_BIT;
  7075. }
  7076. this._gl.clear(mode);
  7077. };
  7078. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7079. var gl = this._gl;
  7080. // Save state
  7081. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7082. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7083. // Change state
  7084. gl.enable(gl.SCISSOR_TEST);
  7085. gl.scissor(x, y, width, height);
  7086. // Clear
  7087. this.clear(clearColor, true, true, true);
  7088. // Restore state
  7089. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7090. if (curScissor === true) {
  7091. gl.enable(gl.SCISSOR_TEST);
  7092. }
  7093. else {
  7094. gl.disable(gl.SCISSOR_TEST);
  7095. }
  7096. };
  7097. /**
  7098. * Set the WebGL's viewport
  7099. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7100. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7101. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7102. */
  7103. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7104. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7105. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7106. var x = viewport.x || 0;
  7107. var y = viewport.y || 0;
  7108. this._cachedViewport = viewport;
  7109. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7110. };
  7111. /**
  7112. * Directly set the WebGL Viewport
  7113. * The x, y, width & height are directly passed to the WebGL call
  7114. * @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.
  7115. */
  7116. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7117. var currentViewport = this._cachedViewport;
  7118. this._cachedViewport = null;
  7119. this._gl.viewport(x, y, width, height);
  7120. return currentViewport;
  7121. };
  7122. Engine.prototype.beginFrame = function () {
  7123. this._measureFps();
  7124. };
  7125. Engine.prototype.endFrame = function () {
  7126. //force a flush in case we are using a bad OS.
  7127. if (this._badOS) {
  7128. this.flushFramebuffer();
  7129. }
  7130. //submit frame to the vr device, if enabled
  7131. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7132. this._vrDisplayEnabled.submitFrame();
  7133. }
  7134. };
  7135. /**
  7136. * resize the view according to the canvas' size.
  7137. * @example
  7138. * window.addEventListener("resize", function () {
  7139. * engine.resize();
  7140. * });
  7141. */
  7142. Engine.prototype.resize = function () {
  7143. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7144. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7145. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7146. for (var index = 0; index < this.scenes.length; index++) {
  7147. var scene = this.scenes[index];
  7148. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7149. scene.debugLayer._syncPositions();
  7150. }
  7151. }
  7152. };
  7153. /**
  7154. * force a specific size of the canvas
  7155. * @param {number} width - the new canvas' width
  7156. * @param {number} height - the new canvas' height
  7157. */
  7158. Engine.prototype.setSize = function (width, height) {
  7159. this._renderingCanvas.width = width;
  7160. this._renderingCanvas.height = height;
  7161. for (var index = 0; index < this.scenes.length; index++) {
  7162. var scene = this.scenes[index];
  7163. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7164. var cam = scene.cameras[camIndex];
  7165. cam._currentRenderId = 0;
  7166. }
  7167. }
  7168. };
  7169. //WebVR functions
  7170. Engine.prototype.initWebVR = function () {
  7171. if (!this.vrDisplaysPromise) {
  7172. this._getVRDisplays();
  7173. }
  7174. };
  7175. Engine.prototype.enableVR = function (vrDevice) {
  7176. this._vrDisplayEnabled = vrDevice;
  7177. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7178. };
  7179. Engine.prototype.disableVR = function () {
  7180. if (this._vrDisplayEnabled) {
  7181. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7182. }
  7183. };
  7184. Engine.prototype._getVRDisplays = function () {
  7185. var _this = this;
  7186. var getWebVRDevices = function (devices) {
  7187. var size = devices.length;
  7188. var i = 0;
  7189. _this._vrDisplays = devices.filter(function (device) {
  7190. return devices[i] instanceof VRDisplay;
  7191. });
  7192. return _this._vrDisplays;
  7193. };
  7194. //using a key due to typescript
  7195. if (navigator.getVRDisplays) {
  7196. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7197. }
  7198. };
  7199. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7200. this._currentRenderTarget = texture;
  7201. this.bindUnboundFramebuffer(texture._framebuffer);
  7202. var gl = this._gl;
  7203. if (texture.isCube) {
  7204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7205. }
  7206. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7207. this.wipeCaches();
  7208. };
  7209. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7210. if (this._currentFramebuffer !== framebuffer) {
  7211. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7212. this._currentFramebuffer = framebuffer;
  7213. }
  7214. };
  7215. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7216. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7217. this._currentRenderTarget = null;
  7218. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7219. var gl = this._gl;
  7220. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7221. gl.generateMipmap(gl.TEXTURE_2D);
  7222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7223. }
  7224. this.bindUnboundFramebuffer(null);
  7225. };
  7226. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7227. if (texture.generateMipMaps) {
  7228. var gl = this._gl;
  7229. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7230. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7232. }
  7233. };
  7234. Engine.prototype.flushFramebuffer = function () {
  7235. this._gl.flush();
  7236. };
  7237. Engine.prototype.restoreDefaultFramebuffer = function () {
  7238. this._currentRenderTarget = null;
  7239. this.bindUnboundFramebuffer(null);
  7240. this.setViewport(this._cachedViewport);
  7241. this.wipeCaches();
  7242. };
  7243. // VBOs
  7244. Engine.prototype._resetVertexBufferBinding = function () {
  7245. this.bindArrayBuffer(null);
  7246. this._cachedVertexBuffers = null;
  7247. };
  7248. Engine.prototype.createVertexBuffer = function (vertices) {
  7249. var vbo = this._gl.createBuffer();
  7250. this.bindArrayBuffer(vbo);
  7251. if (vertices instanceof Float32Array) {
  7252. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7253. }
  7254. else {
  7255. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7256. }
  7257. this._resetVertexBufferBinding();
  7258. vbo.references = 1;
  7259. return vbo;
  7260. };
  7261. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7262. var vbo = this._gl.createBuffer();
  7263. this.bindArrayBuffer(vbo);
  7264. if (vertices instanceof Float32Array) {
  7265. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7266. }
  7267. else {
  7268. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7269. }
  7270. this._resetVertexBufferBinding();
  7271. vbo.references = 1;
  7272. return vbo;
  7273. };
  7274. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7275. this.bindArrayBuffer(vertexBuffer);
  7276. if (offset === undefined) {
  7277. offset = 0;
  7278. }
  7279. if (count === undefined) {
  7280. if (vertices instanceof Float32Array) {
  7281. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7282. }
  7283. else {
  7284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7285. }
  7286. }
  7287. else {
  7288. if (vertices instanceof Float32Array) {
  7289. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7290. }
  7291. else {
  7292. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7293. }
  7294. }
  7295. this._resetVertexBufferBinding();
  7296. };
  7297. Engine.prototype._resetIndexBufferBinding = function () {
  7298. this.bindIndexBuffer(null);
  7299. this._cachedIndexBuffer = null;
  7300. };
  7301. Engine.prototype.createIndexBuffer = function (indices) {
  7302. var vbo = this._gl.createBuffer();
  7303. this.bindIndexBuffer(vbo);
  7304. // Check for 32 bits indices
  7305. var arrayBuffer;
  7306. var need32Bits = false;
  7307. if (this._caps.uintIndices) {
  7308. for (var index = 0; index < indices.length; index++) {
  7309. if (indices[index] > 65535) {
  7310. need32Bits = true;
  7311. break;
  7312. }
  7313. }
  7314. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7315. }
  7316. else {
  7317. arrayBuffer = new Uint16Array(indices);
  7318. }
  7319. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7320. this._resetIndexBufferBinding();
  7321. vbo.references = 1;
  7322. vbo.is32Bits = need32Bits;
  7323. return vbo;
  7324. };
  7325. Engine.prototype.bindArrayBuffer = function (buffer) {
  7326. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7327. };
  7328. Engine.prototype.bindIndexBuffer = function (buffer) {
  7329. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7330. };
  7331. Engine.prototype.bindBuffer = function (buffer, target) {
  7332. if (this._currentBoundBuffer[target] !== buffer) {
  7333. this._gl.bindBuffer(target, buffer);
  7334. this._currentBoundBuffer[target] = buffer;
  7335. }
  7336. };
  7337. Engine.prototype.updateArrayBuffer = function (data) {
  7338. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7339. };
  7340. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7341. var pointer = this._currentBufferPointers[indx];
  7342. var changed = false;
  7343. if (!pointer) {
  7344. changed = true;
  7345. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7346. }
  7347. else {
  7348. if (pointer.buffer !== buffer) {
  7349. pointer.buffer = buffer;
  7350. changed = true;
  7351. }
  7352. if (pointer.size !== size) {
  7353. pointer.size = size;
  7354. changed = true;
  7355. }
  7356. if (pointer.type !== type) {
  7357. pointer.type = type;
  7358. changed = true;
  7359. }
  7360. if (pointer.normalized !== normalized) {
  7361. pointer.normalized = normalized;
  7362. changed = true;
  7363. }
  7364. if (pointer.stride !== stride) {
  7365. pointer.stride = stride;
  7366. changed = true;
  7367. }
  7368. if (pointer.offset !== offset) {
  7369. pointer.offset = offset;
  7370. changed = true;
  7371. }
  7372. }
  7373. if (changed) {
  7374. this.bindArrayBuffer(buffer);
  7375. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7376. }
  7377. };
  7378. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7379. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7380. this._cachedVertexBuffers = vertexBuffer;
  7381. this._cachedEffectForVertexBuffers = effect;
  7382. var attributesCount = effect.getAttributesCount();
  7383. var offset = 0;
  7384. for (var index = 0; index < attributesCount; index++) {
  7385. if (index < vertexDeclaration.length) {
  7386. var order = effect.getAttributeLocation(index);
  7387. if (order >= 0) {
  7388. if (!this._vertexAttribArraysEnabled[order]) {
  7389. this._gl.enableVertexAttribArray(order);
  7390. this._vertexAttribArraysEnabled[order] = true;
  7391. }
  7392. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7393. }
  7394. offset += vertexDeclaration[index] * 4;
  7395. }
  7396. else {
  7397. //disable effect attributes that have no data
  7398. var order = effect.getAttributeLocation(index);
  7399. if (this._vertexAttribArraysEnabled[order]) {
  7400. this._gl.disableVertexAttribArray(order);
  7401. this._vertexAttribArraysEnabled[order] = false;
  7402. }
  7403. }
  7404. }
  7405. }
  7406. if (this._cachedIndexBuffer !== indexBuffer) {
  7407. this._cachedIndexBuffer = indexBuffer;
  7408. this.bindIndexBuffer(indexBuffer);
  7409. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7410. }
  7411. };
  7412. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7413. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7414. this._cachedVertexBuffers = vertexBuffers;
  7415. this._cachedEffectForVertexBuffers = effect;
  7416. var attributes = effect.getAttributesNames();
  7417. for (var index = 0; index < attributes.length; index++) {
  7418. var order = effect.getAttributeLocation(index);
  7419. if (order >= 0) {
  7420. var vertexBuffer = vertexBuffers[attributes[index]];
  7421. if (!vertexBuffer) {
  7422. if (this._vertexAttribArraysEnabled[order]) {
  7423. this._gl.disableVertexAttribArray(order);
  7424. this._vertexAttribArraysEnabled[order] = false;
  7425. }
  7426. continue;
  7427. }
  7428. if (!this._vertexAttribArraysEnabled[order]) {
  7429. this._gl.enableVertexAttribArray(order);
  7430. this._vertexAttribArraysEnabled[order] = true;
  7431. }
  7432. var buffer = vertexBuffer.getBuffer();
  7433. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7434. if (vertexBuffer.getIsInstanced()) {
  7435. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7436. this._currentInstanceLocations.push(order);
  7437. this._currentInstanceBuffers.push(buffer);
  7438. }
  7439. }
  7440. }
  7441. }
  7442. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7443. this._cachedIndexBuffer = indexBuffer;
  7444. this.bindIndexBuffer(indexBuffer);
  7445. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7446. }
  7447. };
  7448. Engine.prototype.unbindInstanceAttributes = function () {
  7449. var boundBuffer;
  7450. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7451. var instancesBuffer = this._currentInstanceBuffers[i];
  7452. if (boundBuffer != instancesBuffer) {
  7453. boundBuffer = instancesBuffer;
  7454. this.bindArrayBuffer(instancesBuffer);
  7455. }
  7456. var offsetLocation = this._currentInstanceLocations[i];
  7457. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7458. }
  7459. this._currentInstanceBuffers.length = 0;
  7460. this._currentInstanceLocations.length = 0;
  7461. };
  7462. Engine.prototype._releaseBuffer = function (buffer) {
  7463. buffer.references--;
  7464. if (buffer.references === 0) {
  7465. this._gl.deleteBuffer(buffer);
  7466. return true;
  7467. }
  7468. return false;
  7469. };
  7470. Engine.prototype.createInstancesBuffer = function (capacity) {
  7471. var buffer = this._gl.createBuffer();
  7472. buffer.capacity = capacity;
  7473. this.bindArrayBuffer(buffer);
  7474. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7475. return buffer;
  7476. };
  7477. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7478. this._gl.deleteBuffer(buffer);
  7479. };
  7480. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7481. this.bindArrayBuffer(instancesBuffer);
  7482. if (data) {
  7483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7484. }
  7485. if (offsetLocations[0].index !== undefined) {
  7486. var stride = 0;
  7487. for (var i = 0; i < offsetLocations.length; i++) {
  7488. var ai = offsetLocations[i];
  7489. stride += ai.attributeSize * 4;
  7490. }
  7491. for (var i = 0; i < offsetLocations.length; i++) {
  7492. var ai = offsetLocations[i];
  7493. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7494. this._gl.enableVertexAttribArray(ai.index);
  7495. this._vertexAttribArraysEnabled[ai.index] = true;
  7496. }
  7497. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7498. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7499. this._currentInstanceLocations.push(ai.index);
  7500. this._currentInstanceBuffers.push(instancesBuffer);
  7501. }
  7502. }
  7503. else {
  7504. for (var index = 0; index < 4; index++) {
  7505. var offsetLocation = offsetLocations[index];
  7506. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7507. this._gl.enableVertexAttribArray(offsetLocation);
  7508. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7509. }
  7510. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7511. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7512. this._currentInstanceLocations.push(offsetLocation);
  7513. this._currentInstanceBuffers.push(instancesBuffer);
  7514. }
  7515. }
  7516. };
  7517. Engine.prototype.applyStates = function () {
  7518. this._depthCullingState.apply(this._gl);
  7519. this._stencilState.apply(this._gl);
  7520. this._alphaState.apply(this._gl);
  7521. };
  7522. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7523. // Apply states
  7524. this.applyStates();
  7525. this._drawCalls.addCount(1, false);
  7526. // Render
  7527. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7528. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7529. if (instancesCount) {
  7530. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7531. return;
  7532. }
  7533. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7534. };
  7535. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7536. // Apply states
  7537. this.applyStates();
  7538. this._drawCalls.addCount(1, false);
  7539. if (instancesCount) {
  7540. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7541. return;
  7542. }
  7543. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7544. };
  7545. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7546. // Apply states
  7547. this.applyStates();
  7548. this._drawCalls.addCount(1, false);
  7549. if (instancesCount) {
  7550. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7551. return;
  7552. }
  7553. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7554. };
  7555. // Shaders
  7556. Engine.prototype._releaseEffect = function (effect) {
  7557. if (this._compiledEffects[effect._key]) {
  7558. delete this._compiledEffects[effect._key];
  7559. if (effect.getProgram()) {
  7560. this._gl.deleteProgram(effect.getProgram());
  7561. }
  7562. }
  7563. };
  7564. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7565. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7566. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7567. var name = vertex + "+" + fragment + "@" + defines;
  7568. if (this._compiledEffects[name]) {
  7569. return this._compiledEffects[name];
  7570. }
  7571. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7572. effect._key = name;
  7573. this._compiledEffects[name] = effect;
  7574. return effect;
  7575. };
  7576. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7577. if (uniformsNames === void 0) { uniformsNames = []; }
  7578. if (samplers === void 0) { samplers = []; }
  7579. if (defines === void 0) { defines = ""; }
  7580. return this.createEffect({
  7581. vertex: "particles",
  7582. fragmentElement: fragmentName
  7583. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7584. };
  7585. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7586. context = context || this._gl;
  7587. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7588. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7589. var shaderProgram = context.createProgram();
  7590. context.attachShader(shaderProgram, vertexShader);
  7591. context.attachShader(shaderProgram, fragmentShader);
  7592. context.linkProgram(shaderProgram);
  7593. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7594. if (!linked) {
  7595. var error = context.getProgramInfoLog(shaderProgram);
  7596. if (error) {
  7597. throw new Error(error);
  7598. }
  7599. }
  7600. context.deleteShader(vertexShader);
  7601. context.deleteShader(fragmentShader);
  7602. return shaderProgram;
  7603. };
  7604. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7605. var results = [];
  7606. for (var index = 0; index < uniformsNames.length; index++) {
  7607. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7608. }
  7609. return results;
  7610. };
  7611. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7612. var results = [];
  7613. for (var index = 0; index < attributesNames.length; index++) {
  7614. try {
  7615. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7616. }
  7617. catch (e) {
  7618. results.push(-1);
  7619. }
  7620. }
  7621. return results;
  7622. };
  7623. Engine.prototype.enableEffect = function (effect) {
  7624. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7625. // if (effect && effect.onBind) {
  7626. // effect.onBind(effect);
  7627. // }
  7628. // return;
  7629. //}
  7630. // Use program
  7631. this.setProgram(effect.getProgram());
  7632. this._currentEffect = effect;
  7633. if (effect.onBind) {
  7634. effect.onBind(effect);
  7635. }
  7636. };
  7637. Engine.prototype.setIntArray = function (uniform, array) {
  7638. if (!uniform)
  7639. return;
  7640. this._gl.uniform1iv(uniform, array);
  7641. };
  7642. Engine.prototype.setIntArray2 = function (uniform, array) {
  7643. if (!uniform || array.length % 2 !== 0)
  7644. return;
  7645. this._gl.uniform2iv(uniform, array);
  7646. };
  7647. Engine.prototype.setIntArray3 = function (uniform, array) {
  7648. if (!uniform || array.length % 3 !== 0)
  7649. return;
  7650. this._gl.uniform3iv(uniform, array);
  7651. };
  7652. Engine.prototype.setIntArray4 = function (uniform, array) {
  7653. if (!uniform || array.length % 4 !== 0)
  7654. return;
  7655. this._gl.uniform4iv(uniform, array);
  7656. };
  7657. Engine.prototype.setFloatArray = function (uniform, array) {
  7658. if (!uniform)
  7659. return;
  7660. this._gl.uniform1fv(uniform, array);
  7661. };
  7662. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7663. if (!uniform || array.length % 2 !== 0)
  7664. return;
  7665. this._gl.uniform2fv(uniform, array);
  7666. };
  7667. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7668. if (!uniform || array.length % 3 !== 0)
  7669. return;
  7670. this._gl.uniform3fv(uniform, array);
  7671. };
  7672. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7673. if (!uniform || array.length % 4 !== 0)
  7674. return;
  7675. this._gl.uniform4fv(uniform, array);
  7676. };
  7677. Engine.prototype.setArray = function (uniform, array) {
  7678. if (!uniform)
  7679. return;
  7680. this._gl.uniform1fv(uniform, array);
  7681. };
  7682. Engine.prototype.setArray2 = function (uniform, array) {
  7683. if (!uniform || array.length % 2 !== 0)
  7684. return;
  7685. this._gl.uniform2fv(uniform, array);
  7686. };
  7687. Engine.prototype.setArray3 = function (uniform, array) {
  7688. if (!uniform || array.length % 3 !== 0)
  7689. return;
  7690. this._gl.uniform3fv(uniform, array);
  7691. };
  7692. Engine.prototype.setArray4 = function (uniform, array) {
  7693. if (!uniform || array.length % 4 !== 0)
  7694. return;
  7695. this._gl.uniform4fv(uniform, array);
  7696. };
  7697. Engine.prototype.setMatrices = function (uniform, matrices) {
  7698. if (!uniform)
  7699. return;
  7700. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7701. };
  7702. Engine.prototype.setMatrix = function (uniform, matrix) {
  7703. if (!uniform)
  7704. return;
  7705. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7706. };
  7707. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7708. if (!uniform)
  7709. return;
  7710. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7711. };
  7712. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7713. if (!uniform)
  7714. return;
  7715. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7716. };
  7717. Engine.prototype.setFloat = function (uniform, value) {
  7718. if (!uniform)
  7719. return;
  7720. this._gl.uniform1f(uniform, value);
  7721. };
  7722. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7723. if (!uniform)
  7724. return;
  7725. this._gl.uniform2f(uniform, x, y);
  7726. };
  7727. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7728. if (!uniform)
  7729. return;
  7730. this._gl.uniform3f(uniform, x, y, z);
  7731. };
  7732. Engine.prototype.setBool = function (uniform, bool) {
  7733. if (!uniform)
  7734. return;
  7735. this._gl.uniform1i(uniform, bool);
  7736. };
  7737. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7738. if (!uniform)
  7739. return;
  7740. this._gl.uniform4f(uniform, x, y, z, w);
  7741. };
  7742. Engine.prototype.setColor3 = function (uniform, color3) {
  7743. if (!uniform)
  7744. return;
  7745. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7746. };
  7747. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7748. if (!uniform)
  7749. return;
  7750. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7751. };
  7752. // States
  7753. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7754. if (zOffset === void 0) { zOffset = 0; }
  7755. if (reverseSide === void 0) { reverseSide = false; }
  7756. // Culling
  7757. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7758. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7759. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7760. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7761. if (culling) {
  7762. this._depthCullingState.cullFace = cullFace;
  7763. this._depthCullingState.cull = true;
  7764. }
  7765. else {
  7766. this._depthCullingState.cull = false;
  7767. }
  7768. }
  7769. // Z offset
  7770. this._depthCullingState.zOffset = zOffset;
  7771. };
  7772. Engine.prototype.setDepthBuffer = function (enable) {
  7773. this._depthCullingState.depthTest = enable;
  7774. };
  7775. Engine.prototype.getDepthWrite = function () {
  7776. return this._depthCullingState.depthMask;
  7777. };
  7778. Engine.prototype.setDepthWrite = function (enable) {
  7779. this._depthCullingState.depthMask = enable;
  7780. };
  7781. Engine.prototype.setColorWrite = function (enable) {
  7782. this._gl.colorMask(enable, enable, enable, enable);
  7783. };
  7784. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7785. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7786. if (this._alphaMode === mode) {
  7787. return;
  7788. }
  7789. switch (mode) {
  7790. case Engine.ALPHA_DISABLE:
  7791. this._alphaState.alphaBlend = false;
  7792. break;
  7793. case Engine.ALPHA_COMBINE:
  7794. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7795. this._alphaState.alphaBlend = true;
  7796. break;
  7797. case Engine.ALPHA_ONEONE:
  7798. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7799. this._alphaState.alphaBlend = true;
  7800. break;
  7801. case Engine.ALPHA_ADD:
  7802. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7803. this._alphaState.alphaBlend = true;
  7804. break;
  7805. case Engine.ALPHA_SUBTRACT:
  7806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7807. this._alphaState.alphaBlend = true;
  7808. break;
  7809. case Engine.ALPHA_MULTIPLY:
  7810. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7811. this._alphaState.alphaBlend = true;
  7812. break;
  7813. case Engine.ALPHA_MAXIMIZED:
  7814. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7815. this._alphaState.alphaBlend = true;
  7816. break;
  7817. }
  7818. if (!noDepthWriteChange) {
  7819. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7820. }
  7821. this._alphaMode = mode;
  7822. };
  7823. Engine.prototype.getAlphaMode = function () {
  7824. return this._alphaMode;
  7825. };
  7826. Engine.prototype.setAlphaTesting = function (enable) {
  7827. this._alphaTest = enable;
  7828. };
  7829. Engine.prototype.getAlphaTesting = function () {
  7830. return this._alphaTest;
  7831. };
  7832. // Textures
  7833. Engine.prototype.wipeCaches = function () {
  7834. this.resetTextureCache();
  7835. this._currentEffect = null;
  7836. this._stencilState.reset();
  7837. this._depthCullingState.reset();
  7838. this.setDepthFunctionToLessOrEqual();
  7839. this._alphaState.reset();
  7840. this._cachedVertexBuffers = null;
  7841. this._cachedIndexBuffer = null;
  7842. this._cachedEffectForVertexBuffers = null;
  7843. };
  7844. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7845. var gl = this._gl;
  7846. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7847. var magFilter = gl.NEAREST;
  7848. var minFilter = gl.NEAREST;
  7849. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7850. magFilter = gl.LINEAR;
  7851. minFilter = gl.LINEAR;
  7852. }
  7853. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7854. magFilter = gl.LINEAR;
  7855. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7856. }
  7857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7859. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7860. texture.samplingMode = samplingMode;
  7861. };
  7862. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7863. var _this = this;
  7864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7865. if (onLoad === void 0) { onLoad = null; }
  7866. if (onError === void 0) { onError = null; }
  7867. if (buffer === void 0) { buffer = null; }
  7868. var texture = this._gl.createTexture();
  7869. var extension;
  7870. var fromData = false;
  7871. if (url.substr(0, 5) === "data:") {
  7872. fromData = true;
  7873. }
  7874. if (!fromData)
  7875. extension = url.substr(url.length - 4, 4).toLowerCase();
  7876. else {
  7877. var oldUrl = url;
  7878. fromData = oldUrl.split(':');
  7879. url = oldUrl;
  7880. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7881. }
  7882. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7883. var isTGA = (extension === ".tga");
  7884. scene._addPendingData(texture);
  7885. texture.url = url;
  7886. texture.noMipmap = noMipmap;
  7887. texture.references = 1;
  7888. texture.samplingMode = samplingMode;
  7889. texture.onLoadedCallbacks = [onLoad];
  7890. this._loadedTexturesCache.push(texture);
  7891. var onerror = function () {
  7892. scene._removePendingData(texture);
  7893. if (onError) {
  7894. onError();
  7895. }
  7896. };
  7897. var callback;
  7898. if (isTGA) {
  7899. callback = function (arrayBuffer) {
  7900. var data = new Uint8Array(arrayBuffer);
  7901. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7902. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7903. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7904. }, samplingMode);
  7905. };
  7906. if (!(fromData instanceof Array))
  7907. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7908. callback(arrayBuffer);
  7909. }, null, scene.database, true, onerror);
  7910. else
  7911. callback(buffer);
  7912. }
  7913. else if (isDDS) {
  7914. callback = function (data) {
  7915. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7916. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7917. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7918. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7919. }, samplingMode);
  7920. };
  7921. if (!(fromData instanceof Array))
  7922. BABYLON.Tools.LoadFile(url, function (data) {
  7923. callback(data);
  7924. }, null, scene.database, true, onerror);
  7925. else
  7926. callback(buffer);
  7927. }
  7928. else {
  7929. var onload = function (img) {
  7930. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7931. var isPot = (img.width === potWidth && img.height === potHeight);
  7932. if (!isPot) {
  7933. _this._prepareWorkingCanvas();
  7934. _this._workingCanvas.width = potWidth;
  7935. _this._workingCanvas.height = potHeight;
  7936. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7937. _this._workingContext.imageSmoothingEnabled = false;
  7938. _this._workingContext.mozImageSmoothingEnabled = false;
  7939. _this._workingContext.oImageSmoothingEnabled = false;
  7940. _this._workingContext.webkitImageSmoothingEnabled = false;
  7941. _this._workingContext.msImageSmoothingEnabled = false;
  7942. }
  7943. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7944. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7945. _this._workingContext.imageSmoothingEnabled = true;
  7946. _this._workingContext.mozImageSmoothingEnabled = true;
  7947. _this._workingContext.oImageSmoothingEnabled = true;
  7948. _this._workingContext.webkitImageSmoothingEnabled = true;
  7949. _this._workingContext.msImageSmoothingEnabled = true;
  7950. }
  7951. }
  7952. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7953. }, samplingMode);
  7954. };
  7955. if (!(fromData instanceof Array))
  7956. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7957. else
  7958. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7959. }
  7960. return texture;
  7961. };
  7962. Engine.prototype._getInternalFormat = function (format) {
  7963. var internalFormat = this._gl.RGBA;
  7964. switch (format) {
  7965. case Engine.TEXTUREFORMAT_ALPHA:
  7966. internalFormat = this._gl.ALPHA;
  7967. break;
  7968. case Engine.TEXTUREFORMAT_LUMINANCE:
  7969. internalFormat = this._gl.LUMINANCE;
  7970. break;
  7971. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7972. internalFormat = this._gl.LUMINANCE_ALPHA;
  7973. break;
  7974. case Engine.TEXTUREFORMAT_RGB:
  7975. internalFormat = this._gl.RGB;
  7976. break;
  7977. case Engine.TEXTUREFORMAT_RGBA:
  7978. internalFormat = this._gl.RGBA;
  7979. break;
  7980. }
  7981. return internalFormat;
  7982. };
  7983. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7984. if (compression === void 0) { compression = null; }
  7985. var internalFormat = this._getInternalFormat(format);
  7986. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7987. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7988. if (texture._width % 4 !== 0) {
  7989. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7990. }
  7991. if (compression) {
  7992. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7993. }
  7994. else {
  7995. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7996. }
  7997. if (texture.generateMipMaps) {
  7998. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7999. }
  8000. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8001. this.resetTextureCache();
  8002. texture.isReady = true;
  8003. };
  8004. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8005. if (compression === void 0) { compression = null; }
  8006. var texture = this._gl.createTexture();
  8007. texture._baseWidth = width;
  8008. texture._baseHeight = height;
  8009. texture._width = width;
  8010. texture._height = height;
  8011. texture.references = 1;
  8012. this.updateRawTexture(texture, data, format, invertY, compression);
  8013. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8014. // Filters
  8015. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8016. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8017. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8018. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8019. texture.samplingMode = samplingMode;
  8020. this._loadedTexturesCache.push(texture);
  8021. return texture;
  8022. };
  8023. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8024. var texture = this._gl.createTexture();
  8025. texture._baseWidth = width;
  8026. texture._baseHeight = height;
  8027. if (generateMipMaps) {
  8028. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8029. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8030. }
  8031. this.resetTextureCache();
  8032. texture._width = width;
  8033. texture._height = height;
  8034. texture.isReady = false;
  8035. texture.generateMipMaps = generateMipMaps;
  8036. texture.references = 1;
  8037. texture.samplingMode = samplingMode;
  8038. this.updateTextureSamplingMode(samplingMode, texture);
  8039. this._loadedTexturesCache.push(texture);
  8040. return texture;
  8041. };
  8042. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8043. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8044. if (texture.isCube) {
  8045. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8046. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8047. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8048. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8049. }
  8050. else {
  8051. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8052. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8053. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8054. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8055. }
  8056. };
  8057. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8058. if (premulAlpha === void 0) { premulAlpha = false; }
  8059. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8060. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8061. if (premulAlpha) {
  8062. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8063. }
  8064. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8065. if (texture.generateMipMaps) {
  8066. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8067. }
  8068. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8069. if (premulAlpha) {
  8070. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8071. }
  8072. this.resetTextureCache();
  8073. texture.isReady = true;
  8074. };
  8075. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8076. if (texture._isDisabled) {
  8077. return;
  8078. }
  8079. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8080. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8081. try {
  8082. // Testing video texture support
  8083. if (this._videoTextureSupported === undefined) {
  8084. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8085. if (this._gl.getError() !== 0) {
  8086. this._videoTextureSupported = false;
  8087. }
  8088. else {
  8089. this._videoTextureSupported = true;
  8090. }
  8091. }
  8092. // Copy video through the current working canvas if video texture is not supported
  8093. if (!this._videoTextureSupported) {
  8094. if (!texture._workingCanvas) {
  8095. texture._workingCanvas = document.createElement("canvas");
  8096. texture._workingContext = texture._workingCanvas.getContext("2d");
  8097. texture._workingCanvas.width = texture._width;
  8098. texture._workingCanvas.height = texture._height;
  8099. }
  8100. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8101. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8102. }
  8103. else {
  8104. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8105. }
  8106. if (texture.generateMipMaps) {
  8107. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8108. }
  8109. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8110. this.resetTextureCache();
  8111. texture.isReady = true;
  8112. }
  8113. catch (ex) {
  8114. // Something unexpected
  8115. // Let's disable the texture
  8116. texture._isDisabled = true;
  8117. }
  8118. };
  8119. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8120. // old version had a "generateMipMaps" arg instead of options.
  8121. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8122. // in the same way, generateDepthBuffer is defaulted to true
  8123. var generateMipMaps = false;
  8124. var generateDepthBuffer = true;
  8125. var generateStencilBuffer = false;
  8126. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8127. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8128. if (options !== undefined) {
  8129. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8130. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8131. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8132. type = options.type === undefined ? type : options.type;
  8133. if (options.samplingMode !== undefined) {
  8134. samplingMode = options.samplingMode;
  8135. }
  8136. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8137. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8138. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8139. }
  8140. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8141. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8142. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8143. }
  8144. }
  8145. var gl = this._gl;
  8146. var texture = gl.createTexture();
  8147. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8148. var width = size.width || size;
  8149. var height = size.height || size;
  8150. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8151. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8152. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8153. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8154. }
  8155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8159. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8160. var depthStencilBuffer;
  8161. // Create the depth/stencil buffer
  8162. if (generateStencilBuffer) {
  8163. depthStencilBuffer = gl.createRenderbuffer();
  8164. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8165. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8166. }
  8167. else if (generateDepthBuffer) {
  8168. depthStencilBuffer = gl.createRenderbuffer();
  8169. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8170. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8171. }
  8172. // Create the framebuffer
  8173. var framebuffer = gl.createFramebuffer();
  8174. this.bindUnboundFramebuffer(framebuffer);
  8175. // Manage attachments
  8176. if (generateStencilBuffer) {
  8177. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8178. }
  8179. else if (generateDepthBuffer) {
  8180. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8181. }
  8182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8183. if (generateMipMaps) {
  8184. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8185. }
  8186. // Unbind
  8187. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8188. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8189. this.bindUnboundFramebuffer(null);
  8190. texture._framebuffer = framebuffer;
  8191. if (generateDepthBuffer) {
  8192. texture._depthBuffer = depthStencilBuffer;
  8193. }
  8194. texture._baseWidth = width;
  8195. texture._baseHeight = height;
  8196. texture._width = width;
  8197. texture._height = height;
  8198. texture.isReady = true;
  8199. texture.generateMipMaps = generateMipMaps;
  8200. texture.references = 1;
  8201. texture.samplingMode = samplingMode;
  8202. texture.type = type;
  8203. this.resetTextureCache();
  8204. this._loadedTexturesCache.push(texture);
  8205. return texture;
  8206. };
  8207. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8208. var gl = this._gl;
  8209. var texture = gl.createTexture();
  8210. var generateMipMaps = true;
  8211. var generateDepthBuffer = true;
  8212. var generateStencilBuffer = false;
  8213. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8214. if (options !== undefined) {
  8215. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8216. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8217. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8218. if (options.samplingMode !== undefined) {
  8219. samplingMode = options.samplingMode;
  8220. }
  8221. }
  8222. texture.isCube = true;
  8223. texture.references = 1;
  8224. texture.generateMipMaps = generateMipMaps;
  8225. texture.references = 1;
  8226. texture.samplingMode = samplingMode;
  8227. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8228. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8229. for (var face = 0; face < 6; face++) {
  8230. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8231. }
  8232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8234. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8236. // Create the depth buffer
  8237. var depthStencilBuffer;
  8238. // Create the depth/stencil buffer
  8239. if (generateStencilBuffer) {
  8240. depthStencilBuffer = gl.createRenderbuffer();
  8241. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8242. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8243. }
  8244. else if (generateDepthBuffer) {
  8245. depthStencilBuffer = gl.createRenderbuffer();
  8246. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8247. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8248. }
  8249. // Create the framebuffer
  8250. var framebuffer = gl.createFramebuffer();
  8251. this.bindUnboundFramebuffer(framebuffer);
  8252. // Manage attachments
  8253. if (generateStencilBuffer) {
  8254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8255. }
  8256. else if (generateDepthBuffer) {
  8257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8258. }
  8259. // Mipmaps
  8260. if (texture.generateMipMaps) {
  8261. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8262. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8263. }
  8264. // Unbind
  8265. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8266. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8267. this.bindUnboundFramebuffer(null);
  8268. texture._framebuffer = framebuffer;
  8269. if (generateDepthBuffer) {
  8270. texture._depthBuffer = depthStencilBuffer;
  8271. }
  8272. texture._width = size;
  8273. texture._height = size;
  8274. texture.isReady = true;
  8275. this.resetTextureCache();
  8276. this._loadedTexturesCache.push(texture);
  8277. return texture;
  8278. };
  8279. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8280. var _this = this;
  8281. if (onLoad === void 0) { onLoad = null; }
  8282. if (onError === void 0) { onError = null; }
  8283. var gl = this._gl;
  8284. var texture = gl.createTexture();
  8285. texture.isCube = true;
  8286. texture.url = rootUrl;
  8287. texture.references = 1;
  8288. texture.onLoadedCallbacks = [];
  8289. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8290. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8291. if (isDDS) {
  8292. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8293. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8294. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8295. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8296. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8297. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8298. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8299. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8300. }
  8301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8302. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8303. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8305. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8306. _this.resetTextureCache();
  8307. texture._width = info.width;
  8308. texture._height = info.height;
  8309. texture.isReady = true;
  8310. }, null, null, true, onError);
  8311. }
  8312. else {
  8313. cascadeLoad(rootUrl, scene, function (imgs) {
  8314. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8315. var height = width;
  8316. _this._prepareWorkingCanvas();
  8317. _this._workingCanvas.width = width;
  8318. _this._workingCanvas.height = height;
  8319. var faces = [
  8320. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8321. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8322. ];
  8323. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8324. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8325. for (var index = 0; index < faces.length; index++) {
  8326. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8327. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8328. }
  8329. if (!noMipmap) {
  8330. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8331. }
  8332. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8336. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8337. _this.resetTextureCache();
  8338. texture._width = width;
  8339. texture._height = height;
  8340. texture.isReady = true;
  8341. texture.onLoadedCallbacks.forEach(function (callback) {
  8342. callback();
  8343. });
  8344. if (onLoad) {
  8345. onLoad();
  8346. }
  8347. }, files, onError);
  8348. }
  8349. this._loadedTexturesCache.push(texture);
  8350. return texture;
  8351. };
  8352. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8353. texture._width = width;
  8354. texture._height = height;
  8355. texture._size = width * height;
  8356. texture._baseWidth = width;
  8357. texture._baseHeight = height;
  8358. };
  8359. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8360. var _this = this;
  8361. var gl = this._gl;
  8362. var texture = gl.createTexture();
  8363. scene._addPendingData(texture);
  8364. texture.isCube = true;
  8365. texture.references = 1;
  8366. texture.url = url;
  8367. var internalFormat = this._getInternalFormat(format);
  8368. var textureType = gl.UNSIGNED_BYTE;
  8369. if (type === Engine.TEXTURETYPE_FLOAT) {
  8370. textureType = gl.FLOAT;
  8371. }
  8372. var width = size;
  8373. var height = width;
  8374. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8375. texture._width = width;
  8376. texture._height = height;
  8377. var onerror = function () {
  8378. scene._removePendingData(texture);
  8379. };
  8380. var internalCallback = function (data) {
  8381. var rgbeDataArrays = callback(data);
  8382. var facesIndex = [
  8383. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8384. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8385. ];
  8386. width = texture._width;
  8387. height = texture._height;
  8388. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8389. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8390. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8391. if (!noMipmap && isPot) {
  8392. if (mipmmapGenerator) {
  8393. var arrayTemp = [];
  8394. // Data are known to be in +X +Y +Z -X -Y -Z
  8395. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8396. arrayTemp.push(rgbeDataArrays[0]); // +X
  8397. arrayTemp.push(rgbeDataArrays[3]); // -X
  8398. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8399. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8400. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8401. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8402. var mipData = mipmmapGenerator(arrayTemp);
  8403. for (var level = 0; level < mipData.length; level++) {
  8404. var mipSize = width >> level;
  8405. // mipData is order in +X -X +Y -Y +Z -Z
  8406. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8407. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8408. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8409. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8410. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8411. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8412. }
  8413. }
  8414. else {
  8415. // Data are known to be in +X +Y +Z -X -Y -Z
  8416. for (var index = 0; index < facesIndex.length; index++) {
  8417. var faceData = rgbeDataArrays[index];
  8418. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8419. }
  8420. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8421. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8422. // By following the webgl standard changes from Revision 7, 2014/11/24
  8423. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8424. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8425. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8426. // Data are known to be in +X +Y +Z -X -Y -Z
  8427. for (var index = 0; index < facesIndex.length; index++) {
  8428. var faceData = rgbeDataArrays[index];
  8429. // Create a new RGBA Face.
  8430. var newFaceData = new Float32Array(width * height * 4);
  8431. for (var x = 0; x < width; x++) {
  8432. for (var y = 0; y < height; y++) {
  8433. var index_1 = (y * width + x) * 3;
  8434. var newIndex = (y * width + x) * 4;
  8435. // Map Old Value to new value.
  8436. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8437. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8438. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8439. // Add fully opaque alpha channel.
  8440. newFaceData[newIndex + 3] = 1;
  8441. }
  8442. }
  8443. // Reupload the face.
  8444. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8445. }
  8446. // Try to generate mipmap again.
  8447. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8448. }
  8449. }
  8450. }
  8451. else {
  8452. noMipmap = true;
  8453. }
  8454. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8457. }
  8458. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8461. }
  8462. else {
  8463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8465. }
  8466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8468. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8469. texture.isReady = true;
  8470. _this.resetTextureCache();
  8471. scene._removePendingData(texture);
  8472. };
  8473. BABYLON.Tools.LoadFile(url, function (data) {
  8474. internalCallback(data);
  8475. }, onerror, scene.database, true);
  8476. return texture;
  8477. };
  8478. ;
  8479. Engine.prototype._releaseTexture = function (texture) {
  8480. var gl = this._gl;
  8481. if (texture._framebuffer) {
  8482. gl.deleteFramebuffer(texture._framebuffer);
  8483. }
  8484. if (texture._depthBuffer) {
  8485. gl.deleteRenderbuffer(texture._depthBuffer);
  8486. }
  8487. gl.deleteTexture(texture);
  8488. // Unbind channels
  8489. this.unbindAllTextures();
  8490. var index = this._loadedTexturesCache.indexOf(texture);
  8491. if (index !== -1) {
  8492. this._loadedTexturesCache.splice(index, 1);
  8493. }
  8494. };
  8495. Engine.prototype.setProgram = function (program) {
  8496. if (this._currentProgram !== program) {
  8497. this._gl.useProgram(program);
  8498. this._currentProgram = program;
  8499. }
  8500. };
  8501. Engine.prototype.bindSamplers = function (effect) {
  8502. this.setProgram(effect.getProgram());
  8503. var samplers = effect.getSamplers();
  8504. for (var index = 0; index < samplers.length; index++) {
  8505. var uniform = effect.getUniform(samplers[index]);
  8506. this._gl.uniform1i(uniform, index);
  8507. }
  8508. this._currentEffect = null;
  8509. };
  8510. Engine.prototype.activateTexture = function (texture) {
  8511. if (this._activeTexture !== texture) {
  8512. this._gl.activeTexture(texture);
  8513. this._activeTexture = texture;
  8514. }
  8515. };
  8516. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8517. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8518. this._gl.bindTexture(target, texture);
  8519. this._activeTexturesCache[this._activeTexture] = texture;
  8520. }
  8521. };
  8522. Engine.prototype._bindTexture = function (channel, texture) {
  8523. if (channel < 0) {
  8524. return;
  8525. }
  8526. this.activateTexture(this._gl["TEXTURE" + channel]);
  8527. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8528. };
  8529. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8530. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8531. };
  8532. Engine.prototype.unbindAllTextures = function () {
  8533. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8534. this.activateTexture(this._gl["TEXTURE" + channel]);
  8535. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8536. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8537. }
  8538. };
  8539. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8540. if (channel < 0) {
  8541. return;
  8542. }
  8543. this._gl.uniform1i(uniform, channel);
  8544. this._setTexture(channel, texture);
  8545. };
  8546. Engine.prototype._setTexture = function (channel, texture) {
  8547. // Not ready?
  8548. if (!texture || !texture.isReady()) {
  8549. if (this._activeTexturesCache[channel] != null) {
  8550. this.activateTexture(this._gl["TEXTURE" + channel]);
  8551. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8553. }
  8554. return;
  8555. }
  8556. // Video
  8557. var alreadyActivated = false;
  8558. if (texture instanceof BABYLON.VideoTexture) {
  8559. this.activateTexture(this._gl["TEXTURE" + channel]);
  8560. alreadyActivated = true;
  8561. texture.update();
  8562. }
  8563. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8564. texture.delayLoad();
  8565. return;
  8566. }
  8567. var internalTexture = texture.getInternalTexture();
  8568. if (this._activeTexturesCache[channel] === internalTexture) {
  8569. return;
  8570. }
  8571. if (!alreadyActivated) {
  8572. this.activateTexture(this._gl["TEXTURE" + channel]);
  8573. }
  8574. if (internalTexture.isCube) {
  8575. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8576. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8577. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8578. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8579. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8580. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8581. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8582. }
  8583. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8584. }
  8585. else {
  8586. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8587. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8588. internalTexture._cachedWrapU = texture.wrapU;
  8589. switch (texture.wrapU) {
  8590. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8591. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8592. break;
  8593. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8595. break;
  8596. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8598. break;
  8599. }
  8600. }
  8601. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8602. internalTexture._cachedWrapV = texture.wrapV;
  8603. switch (texture.wrapV) {
  8604. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8605. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8606. break;
  8607. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8609. break;
  8610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8612. break;
  8613. }
  8614. }
  8615. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8616. }
  8617. };
  8618. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8619. if (channel < 0) {
  8620. return;
  8621. }
  8622. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8623. this._textureUnits = new Int32Array(textures.length);
  8624. }
  8625. for (var i = 0; i < textures.length; i++) {
  8626. this._textureUnits[i] = channel + i;
  8627. }
  8628. this._gl.uniform1iv(uniform, this._textureUnits);
  8629. for (var index = 0; index < textures.length; index++) {
  8630. this._setTexture(channel + index, textures[index]);
  8631. }
  8632. };
  8633. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8634. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8635. var value = texture.anisotropicFilteringLevel;
  8636. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8637. value = 1;
  8638. }
  8639. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8640. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8641. texture._cachedAnisotropicFilteringLevel = value;
  8642. }
  8643. };
  8644. Engine.prototype.readPixels = function (x, y, width, height) {
  8645. var data = new Uint8Array(height * width * 4);
  8646. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8647. return data;
  8648. };
  8649. /**
  8650. * Add an externaly attached data from its key.
  8651. * This method call will fail and return false, if such key already exists.
  8652. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8653. * @param key the unique key that identifies the data
  8654. * @param data the data object to associate to the key for this Engine instance
  8655. * @return true if no such key were already present and the data was added successfully, false otherwise
  8656. */
  8657. Engine.prototype.addExternalData = function (key, data) {
  8658. return this._externalData.add(key, data);
  8659. };
  8660. /**
  8661. * Get an externaly attached data from its key
  8662. * @param key the unique key that identifies the data
  8663. * @return the associated data, if present (can be null), or undefined if not present
  8664. */
  8665. Engine.prototype.getExternalData = function (key) {
  8666. return this._externalData.get(key);
  8667. };
  8668. /**
  8669. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8670. * @param key the unique key that identifies the data
  8671. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8672. * @return the associated data, can be null if the factory returned null.
  8673. */
  8674. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8675. return this._externalData.getOrAddWithFactory(key, factory);
  8676. };
  8677. /**
  8678. * Remove an externaly attached data from the Engine instance
  8679. * @param key the unique key that identifies the data
  8680. * @return true if the data was successfully removed, false if it doesn't exist
  8681. */
  8682. Engine.prototype.removeExternalData = function (key) {
  8683. return this._externalData.remove(key);
  8684. };
  8685. Engine.prototype.releaseInternalTexture = function (texture) {
  8686. if (!texture) {
  8687. return;
  8688. }
  8689. texture.references--;
  8690. // Final reference ?
  8691. if (texture.references === 0) {
  8692. var texturesCache = this.getLoadedTexturesCache();
  8693. var index = texturesCache.indexOf(texture);
  8694. if (index > -1) {
  8695. texturesCache.splice(index, 1);
  8696. }
  8697. this._releaseTexture(texture);
  8698. }
  8699. };
  8700. Engine.prototype.unbindAllAttributes = function () {
  8701. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8702. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8703. continue;
  8704. }
  8705. this._gl.disableVertexAttribArray(i);
  8706. this._vertexAttribArraysEnabled[i] = false;
  8707. }
  8708. };
  8709. // Dispose
  8710. Engine.prototype.dispose = function () {
  8711. this.hideLoadingUI();
  8712. this.stopRenderLoop();
  8713. // Release scenes
  8714. while (this.scenes.length) {
  8715. this.scenes[0].dispose();
  8716. }
  8717. // Release audio engine
  8718. Engine.audioEngine.dispose();
  8719. // Release effects
  8720. for (var name in this._compiledEffects) {
  8721. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8722. }
  8723. // Unbind
  8724. this.unbindAllAttributes();
  8725. this._gl = null;
  8726. //WebVR
  8727. this.disableVR();
  8728. // Events
  8729. window.removeEventListener("blur", this._onBlur);
  8730. window.removeEventListener("focus", this._onFocus);
  8731. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8732. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8733. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8734. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8735. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8736. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8737. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8738. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8739. };
  8740. // Loading screen
  8741. Engine.prototype.displayLoadingUI = function () {
  8742. this._loadingScreen.displayLoadingUI();
  8743. };
  8744. Engine.prototype.hideLoadingUI = function () {
  8745. this._loadingScreen.hideLoadingUI();
  8746. };
  8747. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8748. get: function () {
  8749. return this._loadingScreen;
  8750. },
  8751. set: function (loadingScreen) {
  8752. this._loadingScreen = loadingScreen;
  8753. },
  8754. enumerable: true,
  8755. configurable: true
  8756. });
  8757. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8758. set: function (text) {
  8759. this._loadingScreen.loadingUIText = text;
  8760. },
  8761. enumerable: true,
  8762. configurable: true
  8763. });
  8764. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8765. set: function (color) {
  8766. this._loadingScreen.loadingUIBackgroundColor = color;
  8767. },
  8768. enumerable: true,
  8769. configurable: true
  8770. });
  8771. Engine.prototype.attachContextLostEvent = function (callback) {
  8772. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8773. };
  8774. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8775. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8776. };
  8777. // FPS
  8778. Engine.prototype.getFps = function () {
  8779. return this.fps;
  8780. };
  8781. Engine.prototype.getDeltaTime = function () {
  8782. return this.deltaTime;
  8783. };
  8784. Engine.prototype._measureFps = function () {
  8785. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8786. var length = this.previousFramesDuration.length;
  8787. if (length >= 2) {
  8788. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8789. }
  8790. if (length >= this.fpsRange) {
  8791. if (length > this.fpsRange) {
  8792. this.previousFramesDuration.splice(0, 1);
  8793. length = this.previousFramesDuration.length;
  8794. }
  8795. var sum = 0;
  8796. for (var id = 0; id < length - 1; id++) {
  8797. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8798. }
  8799. this.fps = 1000.0 / (sum / (length - 1));
  8800. }
  8801. };
  8802. Engine.prototype._canRenderToFloatTexture = function () {
  8803. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8804. };
  8805. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8806. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8807. };
  8808. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8809. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8810. var tempcanvas = document.createElement("canvas");
  8811. tempcanvas.height = 16;
  8812. tempcanvas.width = 16;
  8813. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8814. // extension.
  8815. var ext = gl.getExtension(extension);
  8816. if (!ext) {
  8817. return false;
  8818. }
  8819. // setup GLSL program
  8820. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8821. 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 }";
  8822. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8823. gl.useProgram(program);
  8824. // look up where the vertex data needs to go.
  8825. var positionLocation = gl.getAttribLocation(program, "a_position");
  8826. var colorLoc = gl.getUniformLocation(program, "u_color");
  8827. // provide texture coordinates for the rectangle.
  8828. var positionBuffer = gl.createBuffer();
  8829. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8830. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8831. -1.0, -1.0,
  8832. 1.0, -1.0,
  8833. -1.0, 1.0,
  8834. -1.0, 1.0,
  8835. 1.0, -1.0,
  8836. 1.0, 1.0]), gl.STATIC_DRAW);
  8837. gl.enableVertexAttribArray(positionLocation);
  8838. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8839. var whiteTex = gl.createTexture();
  8840. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8841. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8842. var tex = gl.createTexture();
  8843. gl.bindTexture(gl.TEXTURE_2D, tex);
  8844. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8846. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8847. var fb = gl.createFramebuffer();
  8848. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8849. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8850. var cleanup = function () {
  8851. gl.deleteProgram(program);
  8852. gl.disableVertexAttribArray(positionLocation);
  8853. gl.deleteBuffer(positionBuffer);
  8854. gl.deleteFramebuffer(fb);
  8855. gl.deleteTexture(whiteTex);
  8856. gl.deleteTexture(tex);
  8857. };
  8858. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8859. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8860. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8861. cleanup();
  8862. return false;
  8863. }
  8864. // Draw the rectangle.
  8865. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8866. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8867. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8868. gl.bindTexture(gl.TEXTURE_2D, tex);
  8869. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8870. gl.clearColor(1, 0, 0, 1);
  8871. gl.clear(gl.COLOR_BUFFER_BIT);
  8872. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8873. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8874. var pixel = new Uint8Array(4);
  8875. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8876. if (pixel[0] !== 0 ||
  8877. pixel[1] < 248 ||
  8878. pixel[2] < 248 ||
  8879. pixel[3] < 254) {
  8880. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8881. cleanup();
  8882. return false;
  8883. }
  8884. // Succesfully rendered to "format" texture.
  8885. cleanup();
  8886. return true;
  8887. };
  8888. // Statics
  8889. Engine.isSupported = function () {
  8890. try {
  8891. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8892. if (navigator.isCocoonJS) {
  8893. return true;
  8894. }
  8895. var tempcanvas = document.createElement("canvas");
  8896. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8897. return gl != null && !!window.WebGLRenderingContext;
  8898. }
  8899. catch (e) {
  8900. return false;
  8901. }
  8902. };
  8903. // Const statics
  8904. Engine._ALPHA_DISABLE = 0;
  8905. Engine._ALPHA_ADD = 1;
  8906. Engine._ALPHA_COMBINE = 2;
  8907. Engine._ALPHA_SUBTRACT = 3;
  8908. Engine._ALPHA_MULTIPLY = 4;
  8909. Engine._ALPHA_MAXIMIZED = 5;
  8910. Engine._ALPHA_ONEONE = 6;
  8911. Engine._DELAYLOADSTATE_NONE = 0;
  8912. Engine._DELAYLOADSTATE_LOADED = 1;
  8913. Engine._DELAYLOADSTATE_LOADING = 2;
  8914. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8915. Engine._TEXTUREFORMAT_ALPHA = 0;
  8916. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8917. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8918. Engine._TEXTUREFORMAT_RGB = 4;
  8919. Engine._TEXTUREFORMAT_RGBA = 5;
  8920. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8921. Engine._TEXTURETYPE_FLOAT = 1;
  8922. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8923. // Depht or Stencil test Constants.
  8924. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8925. 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.
  8926. 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.
  8927. 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.
  8928. 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.
  8929. 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.
  8930. 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.
  8931. 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.
  8932. // Stencil Actions Constants.
  8933. Engine._KEEP = 0x1E00;
  8934. Engine._REPLACE = 0x1E01;
  8935. Engine._INCR = 0x1E02;
  8936. Engine._DECR = 0x1E03;
  8937. Engine._INVERT = 0x150A;
  8938. Engine._INCR_WRAP = 0x8507;
  8939. Engine._DECR_WRAP = 0x8508;
  8940. // Updatable statics so stick with vars here
  8941. Engine.CollisionsEpsilon = 0.001;
  8942. Engine.CodeRepository = "src/";
  8943. Engine.ShadersRepository = "src/Shaders/";
  8944. return Engine;
  8945. }());
  8946. BABYLON.Engine = Engine;
  8947. })(BABYLON || (BABYLON = {}));
  8948. var BABYLON;
  8949. (function (BABYLON) {
  8950. /**
  8951. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8952. */
  8953. var Node = (function () {
  8954. /**
  8955. * @constructor
  8956. * @param {string} name - the name and id to be given to this node
  8957. * @param {BABYLON.Scene} the scene this node will be added to
  8958. */
  8959. function Node(name, scene) {
  8960. this.state = "";
  8961. this.metadata = null;
  8962. this.animations = new Array();
  8963. this._ranges = {};
  8964. this._childrenFlag = -1;
  8965. this._isEnabled = true;
  8966. this._isReady = true;
  8967. this._currentRenderId = -1;
  8968. this._parentRenderId = -1;
  8969. this.name = name;
  8970. this.id = name;
  8971. this._scene = scene;
  8972. this._initCache();
  8973. }
  8974. Object.defineProperty(Node.prototype, "parent", {
  8975. get: function () {
  8976. return this._parentNode;
  8977. },
  8978. set: function (parent) {
  8979. if (this._parentNode === parent) {
  8980. return;
  8981. }
  8982. if (this._parentNode) {
  8983. var index = this._parentNode._children.indexOf(this);
  8984. if (index !== -1) {
  8985. this._parentNode._children.splice(index, 1);
  8986. }
  8987. }
  8988. this._parentNode = parent;
  8989. if (this._parentNode) {
  8990. if (!this._parentNode._children) {
  8991. this._parentNode._children = new Array();
  8992. }
  8993. this._parentNode._children.push(this);
  8994. }
  8995. },
  8996. enumerable: true,
  8997. configurable: true
  8998. });
  8999. Node.prototype.getScene = function () {
  9000. return this._scene;
  9001. };
  9002. Node.prototype.getEngine = function () {
  9003. return this._scene.getEngine();
  9004. };
  9005. // override it in derived class
  9006. Node.prototype.getWorldMatrix = function () {
  9007. return BABYLON.Matrix.Identity();
  9008. };
  9009. // override it in derived class if you add new variables to the cache
  9010. // and call the parent class method
  9011. Node.prototype._initCache = function () {
  9012. this._cache = {};
  9013. this._cache.parent = undefined;
  9014. };
  9015. Node.prototype.updateCache = function (force) {
  9016. if (!force && this.isSynchronized())
  9017. return;
  9018. this._cache.parent = this.parent;
  9019. this._updateCache();
  9020. };
  9021. // override it in derived class if you add new variables to the cache
  9022. // and call the parent class method if !ignoreParentClass
  9023. Node.prototype._updateCache = function (ignoreParentClass) {
  9024. };
  9025. // override it in derived class if you add new variables to the cache
  9026. Node.prototype._isSynchronized = function () {
  9027. return true;
  9028. };
  9029. Node.prototype._markSyncedWithParent = function () {
  9030. this._parentRenderId = this.parent._currentRenderId;
  9031. };
  9032. Node.prototype.isSynchronizedWithParent = function () {
  9033. if (!this.parent) {
  9034. return true;
  9035. }
  9036. if (this._parentRenderId !== this.parent._currentRenderId) {
  9037. return false;
  9038. }
  9039. return this.parent.isSynchronized();
  9040. };
  9041. Node.prototype.isSynchronized = function (updateCache) {
  9042. var check = this.hasNewParent();
  9043. check = check || !this.isSynchronizedWithParent();
  9044. check = check || !this._isSynchronized();
  9045. if (updateCache)
  9046. this.updateCache(true);
  9047. return !check;
  9048. };
  9049. Node.prototype.hasNewParent = function (update) {
  9050. if (this._cache.parent === this.parent)
  9051. return false;
  9052. if (update)
  9053. this._cache.parent = this.parent;
  9054. return true;
  9055. };
  9056. /**
  9057. * Is this node ready to be used/rendered
  9058. * @return {boolean} is it ready
  9059. */
  9060. Node.prototype.isReady = function () {
  9061. return this._isReady;
  9062. };
  9063. /**
  9064. * Is this node enabled.
  9065. * If the node has a parent and is enabled, the parent will be inspected as well.
  9066. * @return {boolean} whether this node (and its parent) is enabled.
  9067. * @see setEnabled
  9068. */
  9069. Node.prototype.isEnabled = function () {
  9070. if (!this._isEnabled) {
  9071. return false;
  9072. }
  9073. if (this.parent) {
  9074. return this.parent.isEnabled();
  9075. }
  9076. return true;
  9077. };
  9078. /**
  9079. * Set the enabled state of this node.
  9080. * @param {boolean} value - the new enabled state
  9081. * @see isEnabled
  9082. */
  9083. Node.prototype.setEnabled = function (value) {
  9084. this._isEnabled = value;
  9085. };
  9086. /**
  9087. * Is this node a descendant of the given node.
  9088. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9089. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9090. * @see parent
  9091. */
  9092. Node.prototype.isDescendantOf = function (ancestor) {
  9093. if (this.parent) {
  9094. if (this.parent === ancestor) {
  9095. return true;
  9096. }
  9097. return this.parent.isDescendantOf(ancestor);
  9098. }
  9099. return false;
  9100. };
  9101. /**
  9102. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9103. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9104. * @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.
  9105. * @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.
  9106. */
  9107. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9108. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9109. if (!this._children) {
  9110. return;
  9111. }
  9112. for (var index = 0; index < this._children.length; index++) {
  9113. var item = this._children[index];
  9114. if (!predicate || predicate(item)) {
  9115. results.push(item);
  9116. }
  9117. if (!directDescendantsOnly) {
  9118. item._getDescendants(results, false, predicate);
  9119. }
  9120. }
  9121. };
  9122. /**
  9123. * Will return all nodes that have this node as ascendant.
  9124. * @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.
  9125. * @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.
  9126. * @return {BABYLON.Node[]} all children nodes of all types.
  9127. */
  9128. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9129. var results = [];
  9130. this._getDescendants(results, directDescendantsOnly, predicate);
  9131. return results;
  9132. };
  9133. /**
  9134. * @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.
  9135. * @Deprecated, legacy support.
  9136. * use getDecendants instead.
  9137. */
  9138. Node.prototype.getChildren = function (predicate) {
  9139. return this.getDescendants(true, predicate);
  9140. };
  9141. /**
  9142. * Get all child-meshes of this node.
  9143. */
  9144. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9145. var results = [];
  9146. this._getDescendants(results, directDecendantsOnly, function (node) {
  9147. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9148. });
  9149. return results;
  9150. };
  9151. Node.prototype._setReady = function (state) {
  9152. if (state === this._isReady) {
  9153. return;
  9154. }
  9155. if (!state) {
  9156. this._isReady = false;
  9157. return;
  9158. }
  9159. this._isReady = true;
  9160. if (this.onReady) {
  9161. this.onReady(this);
  9162. }
  9163. };
  9164. Node.prototype.getAnimationByName = function (name) {
  9165. for (var i = 0; i < this.animations.length; i++) {
  9166. var animation = this.animations[i];
  9167. if (animation.name === name) {
  9168. return animation;
  9169. }
  9170. }
  9171. return null;
  9172. };
  9173. Node.prototype.createAnimationRange = function (name, from, to) {
  9174. // check name not already in use
  9175. if (!this._ranges[name]) {
  9176. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9177. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9178. if (this.animations[i]) {
  9179. this.animations[i].createRange(name, from, to);
  9180. }
  9181. }
  9182. }
  9183. };
  9184. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9185. if (deleteFrames === void 0) { deleteFrames = true; }
  9186. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9187. if (this.animations[i]) {
  9188. this.animations[i].deleteRange(name, deleteFrames);
  9189. }
  9190. }
  9191. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9192. };
  9193. Node.prototype.getAnimationRange = function (name) {
  9194. return this._ranges[name];
  9195. };
  9196. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9197. var range = this.getAnimationRange(name);
  9198. if (!range) {
  9199. return null;
  9200. }
  9201. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9202. };
  9203. Node.prototype.serializeAnimationRanges = function () {
  9204. var serializationRanges = [];
  9205. for (var name in this._ranges) {
  9206. var range = {};
  9207. range.name = name;
  9208. range.from = this._ranges[name].from;
  9209. range.to = this._ranges[name].to;
  9210. serializationRanges.push(range);
  9211. }
  9212. return serializationRanges;
  9213. };
  9214. Node.prototype.dispose = function () {
  9215. this.parent = null;
  9216. };
  9217. Node.prototype.getDirection = function (localAxis) {
  9218. var result = BABYLON.Vector3.Zero();
  9219. this.getDirectionToRef(localAxis, result);
  9220. return result;
  9221. };
  9222. Node.prototype.getDirectionToRef = function (localAxis, result) {
  9223. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  9224. };
  9225. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9226. if (parsedNode.ranges) {
  9227. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9228. var data = parsedNode.ranges[index];
  9229. node.createAnimationRange(data.name, data.from, data.to);
  9230. }
  9231. }
  9232. };
  9233. __decorate([
  9234. BABYLON.serialize()
  9235. ], Node.prototype, "name", void 0);
  9236. __decorate([
  9237. BABYLON.serialize()
  9238. ], Node.prototype, "id", void 0);
  9239. __decorate([
  9240. BABYLON.serialize()
  9241. ], Node.prototype, "uniqueId", void 0);
  9242. __decorate([
  9243. BABYLON.serialize()
  9244. ], Node.prototype, "state", void 0);
  9245. __decorate([
  9246. BABYLON.serialize()
  9247. ], Node.prototype, "metadata", void 0);
  9248. return Node;
  9249. }());
  9250. BABYLON.Node = Node;
  9251. })(BABYLON || (BABYLON = {}));
  9252. var BABYLON;
  9253. (function (BABYLON) {
  9254. var FilesInput = (function () {
  9255. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9256. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9257. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9258. this._engine = p_engine;
  9259. this._canvas = p_canvas;
  9260. this._currentScene = p_scene;
  9261. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9262. this._progressCallback = p_progressCallback;
  9263. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9264. this._textureLoadingCallback = p_textureLoadingCallback;
  9265. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9266. }
  9267. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9268. var _this = this;
  9269. if (p_elementToMonitor) {
  9270. this._elementToMonitor = p_elementToMonitor;
  9271. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9272. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9273. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9274. }
  9275. };
  9276. FilesInput.prototype.renderFunction = function () {
  9277. if (this._additionnalRenderLoopLogicCallback) {
  9278. this._additionnalRenderLoopLogicCallback();
  9279. }
  9280. if (this._currentScene) {
  9281. if (this._textureLoadingCallback) {
  9282. var remaining = this._currentScene.getWaitingItemsCount();
  9283. if (remaining > 0) {
  9284. this._textureLoadingCallback(remaining);
  9285. }
  9286. }
  9287. this._currentScene.render();
  9288. }
  9289. };
  9290. FilesInput.prototype.drag = function (e) {
  9291. e.stopPropagation();
  9292. e.preventDefault();
  9293. };
  9294. FilesInput.prototype.drop = function (eventDrop) {
  9295. eventDrop.stopPropagation();
  9296. eventDrop.preventDefault();
  9297. this.loadFiles(eventDrop);
  9298. };
  9299. FilesInput.prototype.loadFiles = function (event) {
  9300. if (this._startingProcessingFilesCallback)
  9301. this._startingProcessingFilesCallback();
  9302. // Handling data transfer via drag'n'drop
  9303. if (event && event.dataTransfer && event.dataTransfer.files) {
  9304. this._filesToLoad = event.dataTransfer.files;
  9305. }
  9306. // Handling files from input files
  9307. if (event && event.target && event.target.files) {
  9308. this._filesToLoad = event.target.files;
  9309. }
  9310. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9311. for (var i = 0; i < this._filesToLoad.length; i++) {
  9312. switch (this._filesToLoad[i].type) {
  9313. case "image/jpeg":
  9314. case "image/png":
  9315. case "image/bmp":
  9316. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9317. break;
  9318. case "image/targa":
  9319. case "image/vnd.ms-dds":
  9320. case "audio/wav":
  9321. case "audio/x-wav":
  9322. case "audio/mp3":
  9323. case "audio/mpeg":
  9324. case "audio/mpeg3":
  9325. case "audio/x-mpeg-3":
  9326. case "audio/ogg":
  9327. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9328. break;
  9329. default:
  9330. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9331. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9332. }
  9333. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9334. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9335. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9336. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9337. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9338. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9339. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9340. this._sceneFileToLoad = this._filesToLoad[i];
  9341. }
  9342. break;
  9343. }
  9344. }
  9345. this.reload();
  9346. }
  9347. };
  9348. FilesInput.prototype.reload = function () {
  9349. var _this = this;
  9350. var that = this;
  9351. // If a ".babylon" file has been provided
  9352. if (this._sceneFileToLoad) {
  9353. if (this._currentScene) {
  9354. if (BABYLON.Tools.errorsCount > 0) {
  9355. BABYLON.Tools.ClearLogCache();
  9356. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9357. }
  9358. this._engine.stopRenderLoop();
  9359. this._currentScene.dispose();
  9360. }
  9361. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9362. that._currentScene = newScene;
  9363. // Wait for textures and shaders to be ready
  9364. that._currentScene.executeWhenReady(function () {
  9365. // Attach camera to canvas inputs
  9366. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9367. that._currentScene.createDefaultCameraOrLight();
  9368. }
  9369. that._currentScene.activeCamera.attachControl(that._canvas);
  9370. if (that._sceneLoadedCallback) {
  9371. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9372. }
  9373. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9374. });
  9375. }, function (progress) {
  9376. if (_this._progressCallback) {
  9377. _this._progressCallback(progress);
  9378. }
  9379. });
  9380. }
  9381. else {
  9382. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9383. }
  9384. };
  9385. FilesInput.FilesTextures = new Array();
  9386. FilesInput.FilesToLoad = new Array();
  9387. return FilesInput;
  9388. }());
  9389. BABYLON.FilesInput = FilesInput;
  9390. })(BABYLON || (BABYLON = {}));
  9391. var BABYLON;
  9392. (function (BABYLON) {
  9393. var IntersectionInfo = (function () {
  9394. function IntersectionInfo(bu, bv, distance) {
  9395. this.bu = bu;
  9396. this.bv = bv;
  9397. this.distance = distance;
  9398. this.faceId = 0;
  9399. this.subMeshId = 0;
  9400. }
  9401. return IntersectionInfo;
  9402. }());
  9403. BABYLON.IntersectionInfo = IntersectionInfo;
  9404. var PickingInfo = (function () {
  9405. function PickingInfo() {
  9406. this.hit = false;
  9407. this.distance = 0;
  9408. this.pickedPoint = null;
  9409. this.pickedMesh = null;
  9410. this.bu = 0;
  9411. this.bv = 0;
  9412. this.faceId = -1;
  9413. this.subMeshId = 0;
  9414. this.pickedSprite = null;
  9415. }
  9416. // Methods
  9417. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9418. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9419. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9420. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9421. return null;
  9422. }
  9423. var indices = this.pickedMesh.getIndices();
  9424. var result;
  9425. if (useVerticesNormals) {
  9426. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9427. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9428. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9429. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9430. normal0 = normal0.scale(this.bu);
  9431. normal1 = normal1.scale(this.bv);
  9432. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9433. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9434. }
  9435. else {
  9436. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9437. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9438. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9439. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9440. var p1p2 = vertex1.subtract(vertex2);
  9441. var p3p2 = vertex3.subtract(vertex2);
  9442. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9443. }
  9444. if (useWorldCoordinates) {
  9445. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9446. }
  9447. return BABYLON.Vector3.Normalize(result);
  9448. };
  9449. PickingInfo.prototype.getTextureCoordinates = function () {
  9450. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9451. return null;
  9452. }
  9453. var indices = this.pickedMesh.getIndices();
  9454. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9455. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9456. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9457. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9458. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9459. uv1 = uv1.scale(this.bu);
  9460. uv2 = uv2.scale(this.bv);
  9461. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9462. };
  9463. return PickingInfo;
  9464. }());
  9465. BABYLON.PickingInfo = PickingInfo;
  9466. })(BABYLON || (BABYLON = {}));
  9467. var BABYLON;
  9468. (function (BABYLON) {
  9469. var BoundingSphere = (function () {
  9470. function BoundingSphere(minimum, maximum) {
  9471. this.minimum = minimum;
  9472. this.maximum = maximum;
  9473. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9474. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9475. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9476. this.radius = distance * 0.5;
  9477. this.centerWorld = BABYLON.Vector3.Zero();
  9478. this._update(BABYLON.Matrix.Identity());
  9479. }
  9480. // Methods
  9481. BoundingSphere.prototype._update = function (world) {
  9482. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9483. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9484. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9485. };
  9486. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9487. for (var i = 0; i < 6; i++) {
  9488. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9489. return false;
  9490. }
  9491. return true;
  9492. };
  9493. BoundingSphere.prototype.intersectsPoint = function (point) {
  9494. var x = this.centerWorld.x - point.x;
  9495. var y = this.centerWorld.y - point.y;
  9496. var z = this.centerWorld.z - point.z;
  9497. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9498. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9499. return false;
  9500. return true;
  9501. };
  9502. // Statics
  9503. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9504. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9505. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9506. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9507. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9508. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9509. return false;
  9510. return true;
  9511. };
  9512. return BoundingSphere;
  9513. }());
  9514. BABYLON.BoundingSphere = BoundingSphere;
  9515. })(BABYLON || (BABYLON = {}));
  9516. var BABYLON;
  9517. (function (BABYLON) {
  9518. var BoundingBox = (function () {
  9519. function BoundingBox(minimum, maximum) {
  9520. this.minimum = minimum;
  9521. this.maximum = maximum;
  9522. this.vectors = new Array();
  9523. this.vectorsWorld = new Array();
  9524. // Bounding vectors
  9525. this.vectors.push(this.minimum.clone());
  9526. this.vectors.push(this.maximum.clone());
  9527. this.vectors.push(this.minimum.clone());
  9528. this.vectors[2].x = this.maximum.x;
  9529. this.vectors.push(this.minimum.clone());
  9530. this.vectors[3].y = this.maximum.y;
  9531. this.vectors.push(this.minimum.clone());
  9532. this.vectors[4].z = this.maximum.z;
  9533. this.vectors.push(this.maximum.clone());
  9534. this.vectors[5].z = this.minimum.z;
  9535. this.vectors.push(this.maximum.clone());
  9536. this.vectors[6].x = this.minimum.x;
  9537. this.vectors.push(this.maximum.clone());
  9538. this.vectors[7].y = this.minimum.y;
  9539. // OBB
  9540. this.center = this.maximum.add(this.minimum).scale(0.5);
  9541. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9542. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9543. // World
  9544. for (var index = 0; index < this.vectors.length; index++) {
  9545. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9546. }
  9547. this.minimumWorld = BABYLON.Vector3.Zero();
  9548. this.maximumWorld = BABYLON.Vector3.Zero();
  9549. this._update(BABYLON.Matrix.Identity());
  9550. }
  9551. // Methods
  9552. BoundingBox.prototype.getWorldMatrix = function () {
  9553. return this._worldMatrix;
  9554. };
  9555. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9556. this._worldMatrix.copyFrom(matrix);
  9557. return this;
  9558. };
  9559. BoundingBox.prototype._update = function (world) {
  9560. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9561. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9562. for (var index = 0; index < this.vectors.length; index++) {
  9563. var v = this.vectorsWorld[index];
  9564. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9565. if (v.x < this.minimumWorld.x)
  9566. this.minimumWorld.x = v.x;
  9567. if (v.y < this.minimumWorld.y)
  9568. this.minimumWorld.y = v.y;
  9569. if (v.z < this.minimumWorld.z)
  9570. this.minimumWorld.z = v.z;
  9571. if (v.x > this.maximumWorld.x)
  9572. this.maximumWorld.x = v.x;
  9573. if (v.y > this.maximumWorld.y)
  9574. this.maximumWorld.y = v.y;
  9575. if (v.z > this.maximumWorld.z)
  9576. this.maximumWorld.z = v.z;
  9577. }
  9578. // OBB
  9579. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9580. this.center.scaleInPlace(0.5);
  9581. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9582. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9583. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9584. this._worldMatrix = world;
  9585. };
  9586. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9587. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9588. };
  9589. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9590. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9591. };
  9592. BoundingBox.prototype.intersectsPoint = function (point) {
  9593. var delta = -BABYLON.Epsilon;
  9594. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9595. return false;
  9596. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9597. return false;
  9598. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9599. return false;
  9600. return true;
  9601. };
  9602. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9603. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9604. };
  9605. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9606. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9607. return false;
  9608. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9609. return false;
  9610. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9611. return false;
  9612. return true;
  9613. };
  9614. // Statics
  9615. BoundingBox.Intersects = function (box0, box1) {
  9616. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9617. return false;
  9618. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9619. return false;
  9620. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9621. return false;
  9622. return true;
  9623. };
  9624. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9625. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9626. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9627. return (num <= (sphereRadius * sphereRadius));
  9628. };
  9629. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9630. for (var p = 0; p < 6; p++) {
  9631. for (var i = 0; i < 8; i++) {
  9632. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9633. return false;
  9634. }
  9635. }
  9636. }
  9637. return true;
  9638. };
  9639. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9640. for (var p = 0; p < 6; p++) {
  9641. var inCount = 8;
  9642. for (var i = 0; i < 8; i++) {
  9643. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9644. --inCount;
  9645. }
  9646. else {
  9647. break;
  9648. }
  9649. }
  9650. if (inCount === 0)
  9651. return false;
  9652. }
  9653. return true;
  9654. };
  9655. return BoundingBox;
  9656. }());
  9657. BABYLON.BoundingBox = BoundingBox;
  9658. })(BABYLON || (BABYLON = {}));
  9659. var BABYLON;
  9660. (function (BABYLON) {
  9661. var computeBoxExtents = function (axis, box) {
  9662. var p = BABYLON.Vector3.Dot(box.center, axis);
  9663. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9664. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9665. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9666. var r = r0 + r1 + r2;
  9667. return {
  9668. min: p - r,
  9669. max: p + r
  9670. };
  9671. };
  9672. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9673. var axisOverlap = function (axis, box0, box1) {
  9674. var result0 = computeBoxExtents(axis, box0);
  9675. var result1 = computeBoxExtents(axis, box1);
  9676. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9677. };
  9678. var BoundingInfo = (function () {
  9679. function BoundingInfo(minimum, maximum) {
  9680. this.minimum = minimum;
  9681. this.maximum = maximum;
  9682. this._isLocked = false;
  9683. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9684. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9685. }
  9686. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9687. get: function () {
  9688. return this._isLocked;
  9689. },
  9690. set: function (value) {
  9691. this._isLocked = value;
  9692. },
  9693. enumerable: true,
  9694. configurable: true
  9695. });
  9696. // Methods
  9697. BoundingInfo.prototype.update = function (world) {
  9698. if (this._isLocked) {
  9699. return;
  9700. }
  9701. this.boundingBox._update(world);
  9702. this.boundingSphere._update(world);
  9703. };
  9704. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9705. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9706. return false;
  9707. return this.boundingBox.isInFrustum(frustumPlanes);
  9708. };
  9709. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9710. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9711. };
  9712. BoundingInfo.prototype._checkCollision = function (collider) {
  9713. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9714. };
  9715. BoundingInfo.prototype.intersectsPoint = function (point) {
  9716. if (!this.boundingSphere.centerWorld) {
  9717. return false;
  9718. }
  9719. if (!this.boundingSphere.intersectsPoint(point)) {
  9720. return false;
  9721. }
  9722. if (!this.boundingBox.intersectsPoint(point)) {
  9723. return false;
  9724. }
  9725. return true;
  9726. };
  9727. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9728. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9729. return false;
  9730. }
  9731. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9732. return false;
  9733. }
  9734. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9735. return false;
  9736. }
  9737. if (!precise) {
  9738. return true;
  9739. }
  9740. var box0 = this.boundingBox;
  9741. var box1 = boundingInfo.boundingBox;
  9742. if (!axisOverlap(box0.directions[0], box0, box1))
  9743. return false;
  9744. if (!axisOverlap(box0.directions[1], box0, box1))
  9745. return false;
  9746. if (!axisOverlap(box0.directions[2], box0, box1))
  9747. return false;
  9748. if (!axisOverlap(box1.directions[0], box0, box1))
  9749. return false;
  9750. if (!axisOverlap(box1.directions[1], box0, box1))
  9751. return false;
  9752. if (!axisOverlap(box1.directions[2], box0, box1))
  9753. return false;
  9754. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9755. return false;
  9756. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9757. return false;
  9758. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9759. return false;
  9760. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9761. return false;
  9762. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9763. return false;
  9764. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9765. return false;
  9766. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9767. return false;
  9768. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9769. return false;
  9770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9771. return false;
  9772. return true;
  9773. };
  9774. return BoundingInfo;
  9775. }());
  9776. BABYLON.BoundingInfo = BoundingInfo;
  9777. })(BABYLON || (BABYLON = {}));
  9778. var BABYLON;
  9779. (function (BABYLON) {
  9780. var Ray = (function () {
  9781. function Ray(origin, direction, length) {
  9782. if (length === void 0) { length = Number.MAX_VALUE; }
  9783. this.origin = origin;
  9784. this.direction = direction;
  9785. this.length = length;
  9786. }
  9787. // Methods
  9788. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9789. var d = 0.0;
  9790. var maxValue = Number.MAX_VALUE;
  9791. var inv;
  9792. var min;
  9793. var max;
  9794. var temp;
  9795. if (Math.abs(this.direction.x) < 0.0000001) {
  9796. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9797. return false;
  9798. }
  9799. }
  9800. else {
  9801. inv = 1.0 / this.direction.x;
  9802. min = (minimum.x - this.origin.x) * inv;
  9803. max = (maximum.x - this.origin.x) * inv;
  9804. if (max === -Infinity) {
  9805. max = Infinity;
  9806. }
  9807. if (min > max) {
  9808. temp = min;
  9809. min = max;
  9810. max = temp;
  9811. }
  9812. d = Math.max(min, d);
  9813. maxValue = Math.min(max, maxValue);
  9814. if (d > maxValue) {
  9815. return false;
  9816. }
  9817. }
  9818. if (Math.abs(this.direction.y) < 0.0000001) {
  9819. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9820. return false;
  9821. }
  9822. }
  9823. else {
  9824. inv = 1.0 / this.direction.y;
  9825. min = (minimum.y - this.origin.y) * inv;
  9826. max = (maximum.y - this.origin.y) * inv;
  9827. if (max === -Infinity) {
  9828. max = Infinity;
  9829. }
  9830. if (min > max) {
  9831. temp = min;
  9832. min = max;
  9833. max = temp;
  9834. }
  9835. d = Math.max(min, d);
  9836. maxValue = Math.min(max, maxValue);
  9837. if (d > maxValue) {
  9838. return false;
  9839. }
  9840. }
  9841. if (Math.abs(this.direction.z) < 0.0000001) {
  9842. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9843. return false;
  9844. }
  9845. }
  9846. else {
  9847. inv = 1.0 / this.direction.z;
  9848. min = (minimum.z - this.origin.z) * inv;
  9849. max = (maximum.z - this.origin.z) * inv;
  9850. if (max === -Infinity) {
  9851. max = Infinity;
  9852. }
  9853. if (min > max) {
  9854. temp = min;
  9855. min = max;
  9856. max = temp;
  9857. }
  9858. d = Math.max(min, d);
  9859. maxValue = Math.min(max, maxValue);
  9860. if (d > maxValue) {
  9861. return false;
  9862. }
  9863. }
  9864. return true;
  9865. };
  9866. Ray.prototype.intersectsBox = function (box) {
  9867. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9868. };
  9869. Ray.prototype.intersectsSphere = function (sphere) {
  9870. var x = sphere.center.x - this.origin.x;
  9871. var y = sphere.center.y - this.origin.y;
  9872. var z = sphere.center.z - this.origin.z;
  9873. var pyth = (x * x) + (y * y) + (z * z);
  9874. var rr = sphere.radius * sphere.radius;
  9875. if (pyth <= rr) {
  9876. return true;
  9877. }
  9878. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9879. if (dot < 0.0) {
  9880. return false;
  9881. }
  9882. var temp = pyth - (dot * dot);
  9883. return temp <= rr;
  9884. };
  9885. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9886. if (!this._edge1) {
  9887. this._edge1 = BABYLON.Vector3.Zero();
  9888. this._edge2 = BABYLON.Vector3.Zero();
  9889. this._pvec = BABYLON.Vector3.Zero();
  9890. this._tvec = BABYLON.Vector3.Zero();
  9891. this._qvec = BABYLON.Vector3.Zero();
  9892. }
  9893. vertex1.subtractToRef(vertex0, this._edge1);
  9894. vertex2.subtractToRef(vertex0, this._edge2);
  9895. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9896. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9897. if (det === 0) {
  9898. return null;
  9899. }
  9900. var invdet = 1 / det;
  9901. this.origin.subtractToRef(vertex0, this._tvec);
  9902. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9903. if (bu < 0 || bu > 1.0) {
  9904. return null;
  9905. }
  9906. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9907. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9908. if (bv < 0 || bu + bv > 1.0) {
  9909. return null;
  9910. }
  9911. //check if the distance is longer than the predefined length.
  9912. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9913. if (distance > this.length) {
  9914. return null;
  9915. }
  9916. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9917. };
  9918. Ray.prototype.intersectsPlane = function (plane) {
  9919. var distance;
  9920. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9921. if (Math.abs(result1) < 9.99999997475243E-07) {
  9922. return null;
  9923. }
  9924. else {
  9925. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9926. distance = (-plane.d - result2) / result1;
  9927. if (distance < 0.0) {
  9928. if (distance < -9.99999997475243E-07) {
  9929. return null;
  9930. }
  9931. else {
  9932. return 0;
  9933. }
  9934. }
  9935. return distance;
  9936. }
  9937. };
  9938. /**
  9939. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9940. * @param sega the first point of the segment to test the intersection against
  9941. * @param segb the second point of the segment to test the intersection against
  9942. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9943. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9944. */
  9945. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9946. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9947. var u = segb.subtract(sega);
  9948. var v = rsegb.subtract(this.origin);
  9949. var w = sega.subtract(this.origin);
  9950. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9951. var b = BABYLON.Vector3.Dot(u, v);
  9952. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9953. var d = BABYLON.Vector3.Dot(u, w);
  9954. var e = BABYLON.Vector3.Dot(v, w);
  9955. var D = a * c - b * b; // always >= 0
  9956. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9957. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9958. // compute the line parameters of the two closest points
  9959. if (D < Ray.smallnum) {
  9960. sN = 0.0; // force using point P0 on segment S1
  9961. sD = 1.0; // to prevent possible division by 0.0 later
  9962. tN = e;
  9963. tD = c;
  9964. }
  9965. else {
  9966. sN = (b * e - c * d);
  9967. tN = (a * e - b * d);
  9968. if (sN < 0.0) {
  9969. sN = 0.0;
  9970. tN = e;
  9971. tD = c;
  9972. }
  9973. else if (sN > sD) {
  9974. sN = sD;
  9975. tN = e + b;
  9976. tD = c;
  9977. }
  9978. }
  9979. if (tN < 0.0) {
  9980. tN = 0.0;
  9981. // recompute sc for this edge
  9982. if (-d < 0.0) {
  9983. sN = 0.0;
  9984. }
  9985. else if (-d > a)
  9986. sN = sD;
  9987. else {
  9988. sN = -d;
  9989. sD = a;
  9990. }
  9991. }
  9992. else if (tN > tD) {
  9993. tN = tD;
  9994. // recompute sc for this edge
  9995. if ((-d + b) < 0.0) {
  9996. sN = 0;
  9997. }
  9998. else if ((-d + b) > a) {
  9999. sN = sD;
  10000. }
  10001. else {
  10002. sN = (-d + b);
  10003. sD = a;
  10004. }
  10005. }
  10006. // finally do the division to get sc and tc
  10007. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10008. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10009. // get the difference of the two closest points
  10010. var qtc = v.multiplyByFloats(tc, tc, tc);
  10011. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10012. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10013. if (isIntersected) {
  10014. return qtc.length();
  10015. }
  10016. return -1;
  10017. };
  10018. // Statics
  10019. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10020. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10021. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10022. var direction = end.subtract(start);
  10023. direction.normalize();
  10024. return new Ray(start, direction);
  10025. };
  10026. /**
  10027. * 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
  10028. * transformed to the given world matrix.
  10029. * @param origin The origin point
  10030. * @param end The end point
  10031. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10032. */
  10033. Ray.CreateNewFromTo = function (origin, end, world) {
  10034. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10035. var direction = end.subtract(origin);
  10036. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10037. direction.normalize();
  10038. return Ray.Transform(new Ray(origin, direction, length), world);
  10039. };
  10040. Ray.Transform = function (ray, matrix) {
  10041. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10042. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10043. newDirection.normalize();
  10044. return new Ray(newOrigin, newDirection, ray.length);
  10045. };
  10046. Ray.smallnum = 0.00000001;
  10047. Ray.rayl = 10e8;
  10048. return Ray;
  10049. }());
  10050. BABYLON.Ray = Ray;
  10051. })(BABYLON || (BABYLON = {}));
  10052. var BABYLON;
  10053. (function (BABYLON) {
  10054. var AbstractMesh = (function (_super) {
  10055. __extends(AbstractMesh, _super);
  10056. // Constructor
  10057. function AbstractMesh(name, scene) {
  10058. var _this = this;
  10059. _super.call(this, name, scene);
  10060. // Events
  10061. /**
  10062. * An event triggered when the mesh is disposed.
  10063. * @type {BABYLON.Observable}
  10064. */
  10065. this.onDisposeObservable = new BABYLON.Observable();
  10066. /**
  10067. * An event triggered when this mesh collides with another one
  10068. * @type {BABYLON.Observable}
  10069. */
  10070. this.onCollideObservable = new BABYLON.Observable();
  10071. /**
  10072. * An event triggered when the collision's position changes
  10073. * @type {BABYLON.Observable}
  10074. */
  10075. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10076. /**
  10077. * An event triggered after the world matrix is updated
  10078. * @type {BABYLON.Observable}
  10079. */
  10080. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10081. // Properties
  10082. this.definedFacingForward = true; // orientation for POV movement & rotation
  10083. this.position = new BABYLON.Vector3(0, 0, 0);
  10084. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10085. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10086. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10087. this.visibility = 1.0;
  10088. this.alphaIndex = Number.MAX_VALUE;
  10089. this.infiniteDistance = false;
  10090. this.isVisible = true;
  10091. this.isPickable = true;
  10092. this.showBoundingBox = false;
  10093. this.showSubMeshesBoundingBox = false;
  10094. this.isBlocker = false;
  10095. this.renderingGroupId = 0;
  10096. this.receiveShadows = false;
  10097. this.renderOutline = false;
  10098. this.outlineColor = BABYLON.Color3.Red();
  10099. this.outlineWidth = 0.02;
  10100. this.renderOverlay = false;
  10101. this.overlayColor = BABYLON.Color3.Red();
  10102. this.overlayAlpha = 0.5;
  10103. this.hasVertexAlpha = false;
  10104. this.useVertexColors = true;
  10105. this.applyFog = true;
  10106. this.computeBonesUsingShaders = true;
  10107. this.scalingDeterminant = 1;
  10108. this.numBoneInfluencers = 4;
  10109. this.useOctreeForRenderingSelection = true;
  10110. this.useOctreeForPicking = true;
  10111. this.useOctreeForCollisions = true;
  10112. this.layerMask = 0x0FFFFFFF;
  10113. this.alwaysSelectAsActiveMesh = false;
  10114. // Collisions
  10115. this._checkCollisions = false;
  10116. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10117. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10118. this._collider = new BABYLON.Collider();
  10119. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10120. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10121. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10122. // Edges
  10123. this.edgesWidth = 1;
  10124. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10125. // Cache
  10126. this._localWorld = BABYLON.Matrix.Zero();
  10127. this._worldMatrix = BABYLON.Matrix.Zero();
  10128. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10129. this._absolutePosition = BABYLON.Vector3.Zero();
  10130. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10131. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10132. this._isDirty = false;
  10133. this._pivotMatrix = BABYLON.Matrix.Identity();
  10134. this._isDisposed = false;
  10135. this._renderId = 0;
  10136. this._intersectionsInProgress = new Array();
  10137. this._isWorldMatrixFrozen = false;
  10138. this._unIndexed = false;
  10139. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10140. if (collidedMesh === void 0) { collidedMesh = null; }
  10141. //TODO move this to the collision coordinator!
  10142. if (_this.getScene().workerCollisions)
  10143. newPosition.multiplyInPlace(_this._collider.radius);
  10144. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10145. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10146. _this.position.addInPlace(_this._diffPositionForCollisions);
  10147. }
  10148. if (collidedMesh) {
  10149. _this.onCollideObservable.notifyObservers(collidedMesh);
  10150. }
  10151. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10152. };
  10153. scene.addMesh(this);
  10154. }
  10155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10156. get: function () {
  10157. return AbstractMesh._BILLBOARDMODE_NONE;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10163. get: function () {
  10164. return AbstractMesh._BILLBOARDMODE_X;
  10165. },
  10166. enumerable: true,
  10167. configurable: true
  10168. });
  10169. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10170. get: function () {
  10171. return AbstractMesh._BILLBOARDMODE_Y;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10177. get: function () {
  10178. return AbstractMesh._BILLBOARDMODE_Z;
  10179. },
  10180. enumerable: true,
  10181. configurable: true
  10182. });
  10183. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10184. get: function () {
  10185. return AbstractMesh._BILLBOARDMODE_ALL;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10191. set: function (callback) {
  10192. if (this._onDisposeObserver) {
  10193. this.onDisposeObservable.remove(this._onDisposeObserver);
  10194. }
  10195. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10196. },
  10197. enumerable: true,
  10198. configurable: true
  10199. });
  10200. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10201. set: function (callback) {
  10202. if (this._onCollideObserver) {
  10203. this.onCollideObservable.remove(this._onCollideObserver);
  10204. }
  10205. this._onCollideObserver = this.onCollideObservable.add(callback);
  10206. },
  10207. enumerable: true,
  10208. configurable: true
  10209. });
  10210. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10211. set: function (callback) {
  10212. if (this._onCollisionPositionChangeObserver) {
  10213. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10214. }
  10215. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10221. get: function () {
  10222. return this._skeleton;
  10223. },
  10224. set: function (value) {
  10225. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10226. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10227. }
  10228. if (value && value.needInitialSkinMatrix) {
  10229. value._registerMeshWithPoseMatrix(this);
  10230. }
  10231. this._skeleton = value;
  10232. if (!this._skeleton) {
  10233. this._bonesTransformMatrices = null;
  10234. }
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. /**
  10240. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10241. */
  10242. AbstractMesh.prototype.toString = function (fullDetails) {
  10243. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10244. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10245. if (this._skeleton) {
  10246. ret += ", skeleton: " + this._skeleton.name;
  10247. }
  10248. if (fullDetails) {
  10249. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10250. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10251. }
  10252. return ret;
  10253. };
  10254. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10255. /**
  10256. * Getting the rotation object.
  10257. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10258. */
  10259. get: function () {
  10260. return this._rotation;
  10261. },
  10262. set: function (newRotation) {
  10263. this._rotation = newRotation;
  10264. },
  10265. enumerable: true,
  10266. configurable: true
  10267. });
  10268. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10269. get: function () {
  10270. return this._scaling;
  10271. },
  10272. set: function (newScaling) {
  10273. this._scaling = newScaling;
  10274. if (this.physicsImpostor) {
  10275. this.physicsImpostor.forceUpdate();
  10276. }
  10277. },
  10278. enumerable: true,
  10279. configurable: true
  10280. });
  10281. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10282. get: function () {
  10283. return this._rotationQuaternion;
  10284. },
  10285. set: function (quaternion) {
  10286. this._rotationQuaternion = quaternion;
  10287. //reset the rotation vector.
  10288. if (quaternion && this.rotation.length()) {
  10289. this.rotation.copyFromFloats(0, 0, 0);
  10290. }
  10291. },
  10292. enumerable: true,
  10293. configurable: true
  10294. });
  10295. // Methods
  10296. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10297. this._poseMatrix.copyFrom(matrix);
  10298. };
  10299. AbstractMesh.prototype.getPoseMatrix = function () {
  10300. return this._poseMatrix;
  10301. };
  10302. AbstractMesh.prototype.disableEdgesRendering = function () {
  10303. if (this._edgesRenderer !== undefined) {
  10304. this._edgesRenderer.dispose();
  10305. this._edgesRenderer = undefined;
  10306. }
  10307. };
  10308. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10309. if (epsilon === void 0) { epsilon = 0.95; }
  10310. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10311. this.disableEdgesRendering();
  10312. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10313. };
  10314. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10315. get: function () {
  10316. return false;
  10317. },
  10318. enumerable: true,
  10319. configurable: true
  10320. });
  10321. AbstractMesh.prototype.getLOD = function (camera) {
  10322. return this;
  10323. };
  10324. AbstractMesh.prototype.getTotalVertices = function () {
  10325. return 0;
  10326. };
  10327. AbstractMesh.prototype.getIndices = function () {
  10328. return null;
  10329. };
  10330. AbstractMesh.prototype.getVerticesData = function (kind) {
  10331. return null;
  10332. };
  10333. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10334. return false;
  10335. };
  10336. AbstractMesh.prototype.getBoundingInfo = function () {
  10337. if (this._masterMesh) {
  10338. return this._masterMesh.getBoundingInfo();
  10339. }
  10340. if (!this._boundingInfo) {
  10341. this._updateBoundingInfo();
  10342. }
  10343. return this._boundingInfo;
  10344. };
  10345. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10346. this._boundingInfo = boundingInfo;
  10347. };
  10348. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10349. get: function () {
  10350. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10351. },
  10352. enumerable: true,
  10353. configurable: true
  10354. });
  10355. AbstractMesh.prototype._preActivate = function () {
  10356. };
  10357. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10358. };
  10359. AbstractMesh.prototype._activate = function (renderId) {
  10360. this._renderId = renderId;
  10361. };
  10362. AbstractMesh.prototype.getWorldMatrix = function () {
  10363. if (this._masterMesh) {
  10364. return this._masterMesh.getWorldMatrix();
  10365. }
  10366. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10367. this.computeWorldMatrix();
  10368. }
  10369. return this._worldMatrix;
  10370. };
  10371. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10372. get: function () {
  10373. return this._worldMatrix;
  10374. },
  10375. enumerable: true,
  10376. configurable: true
  10377. });
  10378. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10379. get: function () {
  10380. return this._absolutePosition;
  10381. },
  10382. enumerable: true,
  10383. configurable: true
  10384. });
  10385. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10386. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10387. this.computeWorldMatrix(true);
  10388. this._isWorldMatrixFrozen = true;
  10389. };
  10390. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10391. this._isWorldMatrixFrozen = false;
  10392. this.computeWorldMatrix(true);
  10393. };
  10394. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10395. get: function () {
  10396. return this._isWorldMatrixFrozen;
  10397. },
  10398. enumerable: true,
  10399. configurable: true
  10400. });
  10401. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10402. axis.normalize();
  10403. if (!this.rotationQuaternion) {
  10404. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10405. this.rotation = BABYLON.Vector3.Zero();
  10406. }
  10407. var rotationQuaternion;
  10408. if (!space || space === BABYLON.Space.LOCAL) {
  10409. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10410. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10411. }
  10412. else {
  10413. if (this.parent) {
  10414. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10415. invertParentWorldMatrix.invert();
  10416. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10417. }
  10418. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10419. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10420. }
  10421. };
  10422. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10423. var displacementVector = axis.scale(distance);
  10424. if (!space || space === BABYLON.Space.LOCAL) {
  10425. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10426. this.setPositionWithLocalVector(tempV3);
  10427. }
  10428. else {
  10429. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10430. }
  10431. };
  10432. AbstractMesh.prototype.getAbsolutePosition = function () {
  10433. this.computeWorldMatrix();
  10434. return this._absolutePosition;
  10435. };
  10436. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10437. if (!absolutePosition) {
  10438. return;
  10439. }
  10440. var absolutePositionX;
  10441. var absolutePositionY;
  10442. var absolutePositionZ;
  10443. if (absolutePosition.x === undefined) {
  10444. if (arguments.length < 3) {
  10445. return;
  10446. }
  10447. absolutePositionX = arguments[0];
  10448. absolutePositionY = arguments[1];
  10449. absolutePositionZ = arguments[2];
  10450. }
  10451. else {
  10452. absolutePositionX = absolutePosition.x;
  10453. absolutePositionY = absolutePosition.y;
  10454. absolutePositionZ = absolutePosition.z;
  10455. }
  10456. if (this.parent) {
  10457. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10458. invertParentWorldMatrix.invert();
  10459. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10460. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10461. }
  10462. else {
  10463. this.position.x = absolutePositionX;
  10464. this.position.y = absolutePositionY;
  10465. this.position.z = absolutePositionZ;
  10466. }
  10467. };
  10468. // ================================== Point of View Movement =================================
  10469. /**
  10470. * Perform relative position change from the point of view of behind the front of the mesh.
  10471. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10472. * Supports definition of mesh facing forward or backward.
  10473. * @param {number} amountRight
  10474. * @param {number} amountUp
  10475. * @param {number} amountForward
  10476. */
  10477. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10478. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10479. };
  10480. /**
  10481. * Calculate relative position change from the point of view of behind the front of the mesh.
  10482. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10483. * Supports definition of mesh facing forward or backward.
  10484. * @param {number} amountRight
  10485. * @param {number} amountUp
  10486. * @param {number} amountForward
  10487. */
  10488. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10489. var rotMatrix = new BABYLON.Matrix();
  10490. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10491. rotQuaternion.toRotationMatrix(rotMatrix);
  10492. var translationDelta = BABYLON.Vector3.Zero();
  10493. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10495. return translationDelta;
  10496. };
  10497. // ================================== Point of View Rotation =================================
  10498. /**
  10499. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10500. * Supports definition of mesh facing forward or backward.
  10501. * @param {number} flipBack
  10502. * @param {number} twirlClockwise
  10503. * @param {number} tiltRight
  10504. */
  10505. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10506. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10507. };
  10508. /**
  10509. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10510. * Supports definition of mesh facing forward or backward.
  10511. * @param {number} flipBack
  10512. * @param {number} twirlClockwise
  10513. * @param {number} tiltRight
  10514. */
  10515. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10516. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10517. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10518. };
  10519. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10520. this._pivotMatrix = matrix;
  10521. this._cache.pivotMatrixUpdated = true;
  10522. };
  10523. AbstractMesh.prototype.getPivotMatrix = function () {
  10524. return this._pivotMatrix;
  10525. };
  10526. AbstractMesh.prototype._isSynchronized = function () {
  10527. if (this._isDirty) {
  10528. return false;
  10529. }
  10530. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10531. return false;
  10532. if (this._cache.pivotMatrixUpdated) {
  10533. return false;
  10534. }
  10535. if (this.infiniteDistance) {
  10536. return false;
  10537. }
  10538. if (!this._cache.position.equals(this.position))
  10539. return false;
  10540. if (this.rotationQuaternion) {
  10541. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10542. return false;
  10543. }
  10544. if (!this._cache.rotation.equals(this.rotation))
  10545. return false;
  10546. if (!this._cache.scaling.equals(this.scaling))
  10547. return false;
  10548. return true;
  10549. };
  10550. AbstractMesh.prototype._initCache = function () {
  10551. _super.prototype._initCache.call(this);
  10552. this._cache.localMatrixUpdated = false;
  10553. this._cache.position = BABYLON.Vector3.Zero();
  10554. this._cache.scaling = BABYLON.Vector3.Zero();
  10555. this._cache.rotation = BABYLON.Vector3.Zero();
  10556. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10557. this._cache.billboardMode = -1;
  10558. };
  10559. AbstractMesh.prototype.markAsDirty = function (property) {
  10560. if (property === "rotation") {
  10561. this.rotationQuaternion = null;
  10562. }
  10563. this._currentRenderId = Number.MAX_VALUE;
  10564. this._isDirty = true;
  10565. };
  10566. AbstractMesh.prototype._updateBoundingInfo = function () {
  10567. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10568. this._boundingInfo.update(this.worldMatrixFromCache);
  10569. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10570. };
  10571. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10572. if (!this.subMeshes) {
  10573. return;
  10574. }
  10575. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10576. var subMesh = this.subMeshes[subIndex];
  10577. if (!subMesh.IsGlobal) {
  10578. subMesh.updateBoundingInfo(matrix);
  10579. }
  10580. }
  10581. };
  10582. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10583. if (this._isWorldMatrixFrozen) {
  10584. return this._worldMatrix;
  10585. }
  10586. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10587. this._currentRenderId = this.getScene().getRenderId();
  10588. return this._worldMatrix;
  10589. }
  10590. this._cache.position.copyFrom(this.position);
  10591. this._cache.scaling.copyFrom(this.scaling);
  10592. this._cache.pivotMatrixUpdated = false;
  10593. this._cache.billboardMode = this.billboardMode;
  10594. this._currentRenderId = this.getScene().getRenderId();
  10595. this._isDirty = false;
  10596. // Scaling
  10597. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10598. // Rotation
  10599. //rotate, if quaternion is set and rotation was used
  10600. if (this.rotationQuaternion) {
  10601. var len = this.rotation.length();
  10602. if (len) {
  10603. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10604. this.rotation.copyFromFloats(0, 0, 0);
  10605. }
  10606. }
  10607. if (this.rotationQuaternion) {
  10608. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10609. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10610. }
  10611. else {
  10612. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10613. this._cache.rotation.copyFrom(this.rotation);
  10614. }
  10615. // Translation
  10616. if (this.infiniteDistance && !this.parent) {
  10617. var camera = this.getScene().activeCamera;
  10618. if (camera) {
  10619. var cameraWorldMatrix = camera.getWorldMatrix();
  10620. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10621. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10622. }
  10623. }
  10624. else {
  10625. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10626. }
  10627. // Composing transformations
  10628. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10629. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10630. // Billboarding
  10631. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10632. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10633. var localPosition = BABYLON.Tmp.Vector3[0];
  10634. if (this.parent && this.parent.getWorldMatrix) {
  10635. this._markSyncedWithParent();
  10636. var parentMatrix;
  10637. if (this._meshToBoneReferal) {
  10638. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10639. parentMatrix = BABYLON.Tmp.Matrix[6];
  10640. }
  10641. else {
  10642. parentMatrix = this.parent.getWorldMatrix();
  10643. }
  10644. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10645. localPosition = BABYLON.Tmp.Vector3[1];
  10646. }
  10647. var zero = this.getScene().activeCamera.globalPosition.clone();
  10648. if (this.parent && this.parent.position) {
  10649. localPosition.addInPlace(this.parent.position);
  10650. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10651. }
  10652. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10653. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10654. zero.x = localPosition.x + BABYLON.Epsilon;
  10655. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10656. zero.y = localPosition.y + BABYLON.Epsilon;
  10657. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10658. zero.z = localPosition.z + BABYLON.Epsilon;
  10659. }
  10660. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10661. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10662. BABYLON.Tmp.Matrix[3].invert();
  10663. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10664. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10665. }
  10666. // Local world
  10667. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10668. // Parent
  10669. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10670. this._markSyncedWithParent();
  10671. if (this._meshToBoneReferal) {
  10672. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10673. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10674. }
  10675. else {
  10676. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10677. }
  10678. }
  10679. else {
  10680. this._worldMatrix.copyFrom(this._localWorld);
  10681. }
  10682. // Bounding info
  10683. this._updateBoundingInfo();
  10684. // Absolute position
  10685. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10686. // Callbacks
  10687. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10688. if (!this._poseMatrix) {
  10689. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10690. }
  10691. return this._worldMatrix;
  10692. };
  10693. /**
  10694. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10695. * @param func: callback function to add
  10696. */
  10697. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10698. this.onAfterWorldMatrixUpdateObservable.add(func);
  10699. };
  10700. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10701. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10702. };
  10703. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10704. this.computeWorldMatrix();
  10705. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10706. };
  10707. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10708. this.computeWorldMatrix();
  10709. var invLocalWorldMatrix = this._localWorld.clone();
  10710. invLocalWorldMatrix.invert();
  10711. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10712. };
  10713. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10714. this.computeWorldMatrix(true);
  10715. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10716. };
  10717. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10718. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10719. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10720. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10721. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10722. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10723. /// <returns>Mesh oriented towards targetMesh</returns>
  10724. if (yawCor === void 0) { yawCor = 0; }
  10725. if (pitchCor === void 0) { pitchCor = 0; }
  10726. if (rollCor === void 0) { rollCor = 0; }
  10727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10728. var dv = AbstractMesh._lookAtVectorCache;
  10729. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10730. targetPoint.subtractToRef(pos, dv);
  10731. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10732. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10733. var pitch = Math.atan2(dv.y, len);
  10734. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10735. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10736. };
  10737. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10738. this._meshToBoneReferal = affectedMesh;
  10739. this.parent = bone;
  10740. if (bone.getWorldMatrix().determinant() < 0) {
  10741. this.scalingDeterminant *= -1;
  10742. }
  10743. };
  10744. AbstractMesh.prototype.detachFromBone = function () {
  10745. if (this.parent.getWorldMatrix().determinant() < 0) {
  10746. this.scalingDeterminant *= -1;
  10747. }
  10748. this._meshToBoneReferal = null;
  10749. this.parent = null;
  10750. };
  10751. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10752. return this._boundingInfo.isInFrustum(frustumPlanes);
  10753. };
  10754. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10755. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10756. ;
  10757. };
  10758. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10759. if (!this._boundingInfo || !mesh._boundingInfo) {
  10760. return false;
  10761. }
  10762. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10763. };
  10764. AbstractMesh.prototype.intersectsPoint = function (point) {
  10765. if (!this._boundingInfo) {
  10766. return false;
  10767. }
  10768. return this._boundingInfo.intersectsPoint(point);
  10769. };
  10770. // Physics
  10771. /**
  10772. * @Deprecated. Use new PhysicsImpostor instead.
  10773. * */
  10774. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10775. //legacy support
  10776. if (impostor.impostor) {
  10777. options = impostor;
  10778. impostor = impostor.impostor;
  10779. }
  10780. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10781. return this.physicsImpostor.physicsBody;
  10782. };
  10783. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10784. return this.physicsImpostor;
  10785. };
  10786. /**
  10787. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10788. */
  10789. AbstractMesh.prototype.getPhysicsMass = function () {
  10790. return this.physicsImpostor.getParam("mass");
  10791. };
  10792. /**
  10793. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10794. */
  10795. AbstractMesh.prototype.getPhysicsFriction = function () {
  10796. return this.physicsImpostor.getParam("friction");
  10797. };
  10798. /**
  10799. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10800. */
  10801. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10802. return this.physicsImpostor.getParam("restitution");
  10803. };
  10804. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10805. if (!camera) {
  10806. camera = this.getScene().activeCamera;
  10807. }
  10808. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10809. };
  10810. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10811. if (!camera) {
  10812. camera = this.getScene().activeCamera;
  10813. }
  10814. return this.absolutePosition.subtract(camera.position).length();
  10815. };
  10816. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10817. if (!this.physicsImpostor) {
  10818. return;
  10819. }
  10820. this.physicsImpostor.applyImpulse(force, contactPoint);
  10821. };
  10822. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10823. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10824. return;
  10825. }
  10826. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10827. mainPivot: pivot1,
  10828. connectedPivot: pivot2,
  10829. nativeParams: options
  10830. });
  10831. };
  10832. /**
  10833. * @Deprecated
  10834. */
  10835. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10836. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10837. this.updatePhysicsBody();
  10838. };
  10839. /**
  10840. * @Deprecated
  10841. * Calling this function is not needed anymore.
  10842. * The physics engine takes care of transofmration automatically.
  10843. */
  10844. AbstractMesh.prototype.updatePhysicsBody = function () {
  10845. //Unneeded
  10846. };
  10847. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10848. // Collisions
  10849. get: function () {
  10850. return this._checkCollisions;
  10851. },
  10852. set: function (collisionEnabled) {
  10853. this._checkCollisions = collisionEnabled;
  10854. if (this.getScene().workerCollisions) {
  10855. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10856. }
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10862. var globalPosition = this.getAbsolutePosition();
  10863. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10864. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10865. this._collider.radius = this.ellipsoid;
  10866. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10867. };
  10868. // Submeshes octree
  10869. /**
  10870. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10871. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10872. */
  10873. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10874. if (maxCapacity === void 0) { maxCapacity = 64; }
  10875. if (maxDepth === void 0) { maxDepth = 2; }
  10876. if (!this._submeshesOctree) {
  10877. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10878. }
  10879. this.computeWorldMatrix(true);
  10880. // Update octree
  10881. var bbox = this.getBoundingInfo().boundingBox;
  10882. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10883. return this._submeshesOctree;
  10884. };
  10885. // Collisions
  10886. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10887. this._generatePointsArray();
  10888. // Transformation
  10889. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10890. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10891. subMesh._lastColliderWorldVertices = [];
  10892. subMesh._trianglePlanes = [];
  10893. var start = subMesh.verticesStart;
  10894. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10895. for (var i = start; i < end; i++) {
  10896. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10897. }
  10898. }
  10899. // Collide
  10900. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10901. if (collider.collisionFound) {
  10902. collider.collidedMesh = this;
  10903. }
  10904. };
  10905. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10906. var subMeshes;
  10907. var len;
  10908. // Octrees
  10909. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10910. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10911. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10912. len = intersections.length;
  10913. subMeshes = intersections.data;
  10914. }
  10915. else {
  10916. subMeshes = this.subMeshes;
  10917. len = subMeshes.length;
  10918. }
  10919. for (var index = 0; index < len; index++) {
  10920. var subMesh = subMeshes[index];
  10921. // Bounding test
  10922. if (len > 1 && !subMesh._checkCollision(collider))
  10923. continue;
  10924. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10925. }
  10926. };
  10927. AbstractMesh.prototype._checkCollision = function (collider) {
  10928. // Bounding box test
  10929. if (!this._boundingInfo._checkCollision(collider))
  10930. return;
  10931. // Transformation matrix
  10932. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10933. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10934. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10935. };
  10936. // Picking
  10937. AbstractMesh.prototype._generatePointsArray = function () {
  10938. return false;
  10939. };
  10940. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10941. var pickingInfo = new BABYLON.PickingInfo();
  10942. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10943. return pickingInfo;
  10944. }
  10945. if (!this._generatePointsArray()) {
  10946. return pickingInfo;
  10947. }
  10948. var intersectInfo = null;
  10949. // Octrees
  10950. var subMeshes;
  10951. var len;
  10952. if (this._submeshesOctree && this.useOctreeForPicking) {
  10953. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10954. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10955. len = intersections.length;
  10956. subMeshes = intersections.data;
  10957. }
  10958. else {
  10959. subMeshes = this.subMeshes;
  10960. len = subMeshes.length;
  10961. }
  10962. for (var index = 0; index < len; index++) {
  10963. var subMesh = subMeshes[index];
  10964. // Bounding test
  10965. if (len > 1 && !subMesh.canIntersects(ray))
  10966. continue;
  10967. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10968. if (currentIntersectInfo) {
  10969. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10970. intersectInfo = currentIntersectInfo;
  10971. intersectInfo.subMeshId = index;
  10972. if (fastCheck) {
  10973. break;
  10974. }
  10975. }
  10976. }
  10977. }
  10978. if (intersectInfo) {
  10979. // Get picked point
  10980. var world = this.getWorldMatrix();
  10981. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10982. var direction = ray.direction.clone();
  10983. direction = direction.scale(intersectInfo.distance);
  10984. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10985. var pickedPoint = worldOrigin.add(worldDirection);
  10986. // Return result
  10987. pickingInfo.hit = true;
  10988. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10989. pickingInfo.pickedPoint = pickedPoint;
  10990. pickingInfo.pickedMesh = this;
  10991. pickingInfo.bu = intersectInfo.bu;
  10992. pickingInfo.bv = intersectInfo.bv;
  10993. pickingInfo.faceId = intersectInfo.faceId;
  10994. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10995. return pickingInfo;
  10996. }
  10997. return pickingInfo;
  10998. };
  10999. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11000. return null;
  11001. };
  11002. AbstractMesh.prototype.releaseSubMeshes = function () {
  11003. if (this.subMeshes) {
  11004. while (this.subMeshes.length) {
  11005. this.subMeshes[0].dispose();
  11006. }
  11007. }
  11008. else {
  11009. this.subMeshes = new Array();
  11010. }
  11011. };
  11012. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11013. var _this = this;
  11014. var index;
  11015. // Action manager
  11016. if (this.actionManager) {
  11017. this.actionManager.dispose();
  11018. this.actionManager = null;
  11019. }
  11020. // Skeleton
  11021. this.skeleton = null;
  11022. // Animations
  11023. this.getScene().stopAnimation(this);
  11024. // Physics
  11025. if (this.physicsImpostor) {
  11026. this.physicsImpostor.dispose();
  11027. }
  11028. // Intersections in progress
  11029. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11030. var other = this._intersectionsInProgress[index];
  11031. var pos = other._intersectionsInProgress.indexOf(this);
  11032. other._intersectionsInProgress.splice(pos, 1);
  11033. }
  11034. this._intersectionsInProgress = [];
  11035. // Lights
  11036. var lights = this.getScene().lights;
  11037. lights.forEach(function (light) {
  11038. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11039. if (meshIndex !== -1) {
  11040. light.includedOnlyMeshes.splice(meshIndex, 1);
  11041. }
  11042. meshIndex = light.excludedMeshes.indexOf(_this);
  11043. if (meshIndex !== -1) {
  11044. light.excludedMeshes.splice(meshIndex, 1);
  11045. }
  11046. // Shadow generators
  11047. var generator = light.getShadowGenerator();
  11048. if (generator) {
  11049. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11050. if (meshIndex !== -1) {
  11051. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11052. }
  11053. }
  11054. });
  11055. // Edges
  11056. if (this._edgesRenderer) {
  11057. this._edgesRenderer.dispose();
  11058. this._edgesRenderer = null;
  11059. }
  11060. // SubMeshes
  11061. this.releaseSubMeshes();
  11062. // Engine
  11063. this.getScene().getEngine().unbindAllAttributes();
  11064. // Remove from scene
  11065. this.getScene().removeMesh(this);
  11066. if (!doNotRecurse) {
  11067. // Particles
  11068. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11069. if (this.getScene().particleSystems[index].emitter === this) {
  11070. this.getScene().particleSystems[index].dispose();
  11071. index--;
  11072. }
  11073. }
  11074. // Children
  11075. var objects = this.getDescendants(true);
  11076. for (index = 0; index < objects.length; index++) {
  11077. objects[index].dispose();
  11078. }
  11079. }
  11080. else {
  11081. var childMeshes = this.getChildMeshes(true);
  11082. for (index = 0; index < childMeshes.length; index++) {
  11083. var child = childMeshes[index];
  11084. child.parent = null;
  11085. child.computeWorldMatrix(true);
  11086. }
  11087. }
  11088. _super.prototype.dispose.call(this);
  11089. this.onAfterWorldMatrixUpdateObservable.clear();
  11090. this.onCollideObservable.clear();
  11091. this.onCollisionPositionChangeObservable.clear();
  11092. this._isDisposed = true;
  11093. // Callback
  11094. this.onDisposeObservable.notifyObservers(this);
  11095. this.onDisposeObservable.clear();
  11096. };
  11097. // Statics
  11098. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11099. AbstractMesh._BILLBOARDMODE_X = 1;
  11100. AbstractMesh._BILLBOARDMODE_Y = 2;
  11101. AbstractMesh._BILLBOARDMODE_Z = 4;
  11102. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11103. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11104. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11105. return AbstractMesh;
  11106. }(BABYLON.Node));
  11107. BABYLON.AbstractMesh = AbstractMesh;
  11108. })(BABYLON || (BABYLON = {}));
  11109. var BABYLON;
  11110. (function (BABYLON) {
  11111. var Light = (function (_super) {
  11112. __extends(Light, _super);
  11113. function Light(name, scene) {
  11114. _super.call(this, name, scene);
  11115. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11116. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11117. this.intensity = 1.0;
  11118. this.range = Number.MAX_VALUE;
  11119. this.includeOnlyWithLayerMask = 0;
  11120. this.includedOnlyMeshes = new Array();
  11121. this.excludedMeshes = new Array();
  11122. this.excludeWithLayerMask = 0;
  11123. this.lightmapMode = 0;
  11124. // PBR Properties.
  11125. this.radius = 0.00001;
  11126. this._excludedMeshesIds = new Array();
  11127. this._includedOnlyMeshesIds = new Array();
  11128. scene.addLight(this);
  11129. }
  11130. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11131. /**
  11132. * If every light affecting the material is in this lightmapMode,
  11133. * material.lightmapTexture adds or multiplies
  11134. * (depends on material.useLightmapAsShadowmap)
  11135. * after every other light calculations.
  11136. */
  11137. get: function () {
  11138. return Light._LIGHTMAP_DEFAULT;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11144. /**
  11145. * material.lightmapTexture as only diffuse lighting from this light
  11146. * adds pnly specular lighting from this light
  11147. * adds dynamic shadows
  11148. */
  11149. get: function () {
  11150. return Light._LIGHTMAP_SPECULAR;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11156. /**
  11157. * material.lightmapTexture as only lighting
  11158. * no light calculation from this light
  11159. * only adds dynamic shadows from this light
  11160. */
  11161. get: function () {
  11162. return Light._LIGHTMAP_SHADOWSONLY;
  11163. },
  11164. enumerable: true,
  11165. configurable: true
  11166. });
  11167. /**
  11168. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11169. */
  11170. Light.prototype.toString = function (fullDetails) {
  11171. var ret = "Name: " + this.name;
  11172. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11173. if (this.animations) {
  11174. for (var i = 0; i < this.animations.length; i++) {
  11175. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11176. }
  11177. }
  11178. if (fullDetails) {
  11179. }
  11180. return ret;
  11181. };
  11182. Light.prototype.getShadowGenerator = function () {
  11183. return this._shadowGenerator;
  11184. };
  11185. Light.prototype.getAbsolutePosition = function () {
  11186. return BABYLON.Vector3.Zero();
  11187. };
  11188. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11189. };
  11190. Light.prototype._getWorldMatrix = function () {
  11191. return BABYLON.Matrix.Identity();
  11192. };
  11193. Light.prototype.canAffectMesh = function (mesh) {
  11194. if (!mesh) {
  11195. return true;
  11196. }
  11197. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11198. return false;
  11199. }
  11200. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11201. return false;
  11202. }
  11203. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11204. return false;
  11205. }
  11206. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11207. return false;
  11208. }
  11209. return true;
  11210. };
  11211. Light.prototype.getWorldMatrix = function () {
  11212. this._currentRenderId = this.getScene().getRenderId();
  11213. var worldMatrix = this._getWorldMatrix();
  11214. if (this.parent && this.parent.getWorldMatrix) {
  11215. if (!this._parentedWorldMatrix) {
  11216. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11217. }
  11218. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11219. this._markSyncedWithParent();
  11220. return this._parentedWorldMatrix;
  11221. }
  11222. return worldMatrix;
  11223. };
  11224. Light.prototype.dispose = function () {
  11225. if (this._shadowGenerator) {
  11226. this._shadowGenerator.dispose();
  11227. this._shadowGenerator = null;
  11228. }
  11229. // Animations
  11230. this.getScene().stopAnimation(this);
  11231. // Remove from scene
  11232. this.getScene().removeLight(this);
  11233. _super.prototype.dispose.call(this);
  11234. };
  11235. Light.prototype.getTypeID = function () {
  11236. return 0;
  11237. };
  11238. Light.prototype.clone = function (name) {
  11239. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11240. };
  11241. Light.prototype.serialize = function () {
  11242. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11243. // Type
  11244. serializationObject.type = this.getTypeID();
  11245. // Parent
  11246. if (this.parent) {
  11247. serializationObject.parentId = this.parent.id;
  11248. }
  11249. // Inclusion / exclusions
  11250. if (this.excludedMeshes.length > 0) {
  11251. serializationObject.excludedMeshesIds = [];
  11252. this.excludedMeshes.forEach(function (mesh) {
  11253. serializationObject.excludedMeshesIds.push(mesh.id);
  11254. });
  11255. }
  11256. if (this.includedOnlyMeshes.length > 0) {
  11257. serializationObject.includedOnlyMeshesIds = [];
  11258. this.includedOnlyMeshes.forEach(function (mesh) {
  11259. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11260. });
  11261. }
  11262. // Animations
  11263. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11264. serializationObject.ranges = this.serializeAnimationRanges();
  11265. return serializationObject;
  11266. };
  11267. Light.GetConstructorFromName = function (type, name, scene) {
  11268. switch (type) {
  11269. case 0:
  11270. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11271. case 1:
  11272. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11273. case 2:
  11274. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11275. case 3:
  11276. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11277. }
  11278. };
  11279. Light.Parse = function (parsedLight, scene) {
  11280. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11281. // Inclusion / exclusions
  11282. if (parsedLight.excludedMeshesIds) {
  11283. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11284. }
  11285. if (parsedLight.includedOnlyMeshesIds) {
  11286. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11287. }
  11288. // Parent
  11289. if (parsedLight.parentId) {
  11290. light._waitingParentId = parsedLight.parentId;
  11291. }
  11292. // Animations
  11293. if (parsedLight.animations) {
  11294. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11295. var parsedAnimation = parsedLight.animations[animationIndex];
  11296. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11297. }
  11298. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11299. }
  11300. if (parsedLight.autoAnimate) {
  11301. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11302. }
  11303. return light;
  11304. };
  11305. //lightmapMode Consts
  11306. Light._LIGHTMAP_DEFAULT = 0;
  11307. Light._LIGHTMAP_SPECULAR = 1;
  11308. Light._LIGHTMAP_SHADOWSONLY = 2;
  11309. __decorate([
  11310. BABYLON.serializeAsColor3()
  11311. ], Light.prototype, "diffuse", void 0);
  11312. __decorate([
  11313. BABYLON.serializeAsColor3()
  11314. ], Light.prototype, "specular", void 0);
  11315. __decorate([
  11316. BABYLON.serialize()
  11317. ], Light.prototype, "intensity", void 0);
  11318. __decorate([
  11319. BABYLON.serialize()
  11320. ], Light.prototype, "range", void 0);
  11321. __decorate([
  11322. BABYLON.serialize()
  11323. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11324. __decorate([
  11325. BABYLON.serialize()
  11326. ], Light.prototype, "excludeWithLayerMask", void 0);
  11327. __decorate([
  11328. BABYLON.serialize()
  11329. ], Light.prototype, "lightmapMode", void 0);
  11330. __decorate([
  11331. BABYLON.serialize()
  11332. ], Light.prototype, "radius", void 0);
  11333. return Light;
  11334. }(BABYLON.Node));
  11335. BABYLON.Light = Light;
  11336. })(BABYLON || (BABYLON = {}));
  11337. var BABYLON;
  11338. (function (BABYLON) {
  11339. var PointLight = (function (_super) {
  11340. __extends(PointLight, _super);
  11341. function PointLight(name, position, scene) {
  11342. _super.call(this, name, scene);
  11343. this.position = position;
  11344. }
  11345. PointLight.prototype.getAbsolutePosition = function () {
  11346. return this.transformedPosition ? this.transformedPosition : this.position;
  11347. };
  11348. PointLight.prototype.computeTransformedPosition = function () {
  11349. if (this.parent && this.parent.getWorldMatrix) {
  11350. if (!this.transformedPosition) {
  11351. this.transformedPosition = BABYLON.Vector3.Zero();
  11352. }
  11353. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11354. return true;
  11355. }
  11356. return false;
  11357. };
  11358. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11359. if (this.parent && this.parent.getWorldMatrix) {
  11360. this.computeTransformedPosition();
  11361. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11362. return;
  11363. }
  11364. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11365. };
  11366. PointLight.prototype.needCube = function () {
  11367. return true;
  11368. };
  11369. PointLight.prototype.supportsVSM = function () {
  11370. return false;
  11371. };
  11372. PointLight.prototype.needRefreshPerFrame = function () {
  11373. return false;
  11374. };
  11375. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11376. switch (faceIndex) {
  11377. case 0:
  11378. return new BABYLON.Vector3(1, 0, 0);
  11379. case 1:
  11380. return new BABYLON.Vector3(-1, 0, 0);
  11381. case 2:
  11382. return new BABYLON.Vector3(0, -1, 0);
  11383. case 3:
  11384. return new BABYLON.Vector3(0, 1, 0);
  11385. case 4:
  11386. return new BABYLON.Vector3(0, 0, 1);
  11387. case 5:
  11388. return new BABYLON.Vector3(0, 0, -1);
  11389. }
  11390. return BABYLON.Vector3.Zero();
  11391. };
  11392. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11393. var activeCamera = this.getScene().activeCamera;
  11394. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11395. };
  11396. PointLight.prototype._getWorldMatrix = function () {
  11397. if (!this._worldMatrix) {
  11398. this._worldMatrix = BABYLON.Matrix.Identity();
  11399. }
  11400. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11401. return this._worldMatrix;
  11402. };
  11403. PointLight.prototype.getTypeID = function () {
  11404. return 0;
  11405. };
  11406. __decorate([
  11407. BABYLON.serializeAsVector3()
  11408. ], PointLight.prototype, "position", void 0);
  11409. return PointLight;
  11410. }(BABYLON.Light));
  11411. BABYLON.PointLight = PointLight;
  11412. })(BABYLON || (BABYLON = {}));
  11413. var BABYLON;
  11414. (function (BABYLON) {
  11415. var SpotLight = (function (_super) {
  11416. __extends(SpotLight, _super);
  11417. function SpotLight(name, position, direction, angle, exponent, scene) {
  11418. _super.call(this, name, scene);
  11419. this.position = position;
  11420. this.direction = direction;
  11421. this.angle = angle;
  11422. this.exponent = exponent;
  11423. }
  11424. SpotLight.prototype.getAbsolutePosition = function () {
  11425. return this.transformedPosition ? this.transformedPosition : this.position;
  11426. };
  11427. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11428. var activeCamera = this.getScene().activeCamera;
  11429. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11430. };
  11431. SpotLight.prototype.needCube = function () {
  11432. return false;
  11433. };
  11434. SpotLight.prototype.supportsVSM = function () {
  11435. return true;
  11436. };
  11437. SpotLight.prototype.needRefreshPerFrame = function () {
  11438. return false;
  11439. };
  11440. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11441. return this.direction;
  11442. };
  11443. SpotLight.prototype.setDirectionToTarget = function (target) {
  11444. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11445. return this.direction;
  11446. };
  11447. SpotLight.prototype.computeTransformedPosition = function () {
  11448. if (this.parent && this.parent.getWorldMatrix) {
  11449. if (!this.transformedPosition) {
  11450. this.transformedPosition = BABYLON.Vector3.Zero();
  11451. }
  11452. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11453. return true;
  11454. }
  11455. return false;
  11456. };
  11457. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11458. var normalizeDirection;
  11459. if (this.parent && this.parent.getWorldMatrix) {
  11460. if (!this._transformedDirection) {
  11461. this._transformedDirection = BABYLON.Vector3.Zero();
  11462. }
  11463. this.computeTransformedPosition();
  11464. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11465. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11466. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11467. }
  11468. else {
  11469. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11470. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11471. }
  11472. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11473. };
  11474. SpotLight.prototype._getWorldMatrix = function () {
  11475. if (!this._worldMatrix) {
  11476. this._worldMatrix = BABYLON.Matrix.Identity();
  11477. }
  11478. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11479. return this._worldMatrix;
  11480. };
  11481. SpotLight.prototype.getTypeID = function () {
  11482. return 2;
  11483. };
  11484. __decorate([
  11485. BABYLON.serializeAsVector3()
  11486. ], SpotLight.prototype, "position", void 0);
  11487. __decorate([
  11488. BABYLON.serializeAsVector3()
  11489. ], SpotLight.prototype, "direction", void 0);
  11490. __decorate([
  11491. BABYLON.serialize()
  11492. ], SpotLight.prototype, "angle", void 0);
  11493. __decorate([
  11494. BABYLON.serialize()
  11495. ], SpotLight.prototype, "exponent", void 0);
  11496. return SpotLight;
  11497. }(BABYLON.Light));
  11498. BABYLON.SpotLight = SpotLight;
  11499. })(BABYLON || (BABYLON = {}));
  11500. var BABYLON;
  11501. (function (BABYLON) {
  11502. var HemisphericLight = (function (_super) {
  11503. __extends(HemisphericLight, _super);
  11504. function HemisphericLight(name, direction, scene) {
  11505. _super.call(this, name, scene);
  11506. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11507. this.direction = direction;
  11508. }
  11509. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11510. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11511. return this.direction;
  11512. };
  11513. HemisphericLight.prototype.getShadowGenerator = function () {
  11514. return null;
  11515. };
  11516. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11517. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11518. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11519. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11520. };
  11521. HemisphericLight.prototype._getWorldMatrix = function () {
  11522. if (!this._worldMatrix) {
  11523. this._worldMatrix = BABYLON.Matrix.Identity();
  11524. }
  11525. return this._worldMatrix;
  11526. };
  11527. HemisphericLight.prototype.getTypeID = function () {
  11528. return 3;
  11529. };
  11530. __decorate([
  11531. BABYLON.serializeAsColor3()
  11532. ], HemisphericLight.prototype, "groundColor", void 0);
  11533. __decorate([
  11534. BABYLON.serializeAsVector3()
  11535. ], HemisphericLight.prototype, "direction", void 0);
  11536. return HemisphericLight;
  11537. }(BABYLON.Light));
  11538. BABYLON.HemisphericLight = HemisphericLight;
  11539. })(BABYLON || (BABYLON = {}));
  11540. var BABYLON;
  11541. (function (BABYLON) {
  11542. var DirectionalLight = (function (_super) {
  11543. __extends(DirectionalLight, _super);
  11544. function DirectionalLight(name, direction, scene) {
  11545. _super.call(this, name, scene);
  11546. this.shadowOrthoScale = 0.5;
  11547. this.autoUpdateExtends = true;
  11548. // Cache
  11549. this._orthoLeft = Number.MAX_VALUE;
  11550. this._orthoRight = Number.MIN_VALUE;
  11551. this._orthoTop = Number.MIN_VALUE;
  11552. this._orthoBottom = Number.MAX_VALUE;
  11553. this.position = direction.scale(-1);
  11554. this.direction = direction;
  11555. }
  11556. DirectionalLight.prototype.getAbsolutePosition = function () {
  11557. return this.transformedPosition ? this.transformedPosition : this.position;
  11558. };
  11559. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11560. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11561. return this.direction;
  11562. };
  11563. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11564. var activeCamera = this.getScene().activeCamera;
  11565. // Check extends
  11566. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11567. var tempVector3 = BABYLON.Vector3.Zero();
  11568. this._orthoLeft = Number.MAX_VALUE;
  11569. this._orthoRight = Number.MIN_VALUE;
  11570. this._orthoTop = Number.MIN_VALUE;
  11571. this._orthoBottom = Number.MAX_VALUE;
  11572. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11573. var mesh = renderList[meshIndex];
  11574. if (!mesh) {
  11575. continue;
  11576. }
  11577. var boundingInfo = mesh.getBoundingInfo();
  11578. if (!boundingInfo) {
  11579. continue;
  11580. }
  11581. var boundingBox = boundingInfo.boundingBox;
  11582. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11583. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11584. if (tempVector3.x < this._orthoLeft)
  11585. this._orthoLeft = tempVector3.x;
  11586. if (tempVector3.y < this._orthoBottom)
  11587. this._orthoBottom = tempVector3.y;
  11588. if (tempVector3.x > this._orthoRight)
  11589. this._orthoRight = tempVector3.x;
  11590. if (tempVector3.y > this._orthoTop)
  11591. this._orthoTop = tempVector3.y;
  11592. }
  11593. }
  11594. }
  11595. var xOffset = this._orthoRight - this._orthoLeft;
  11596. var yOffset = this._orthoTop - this._orthoBottom;
  11597. 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);
  11598. };
  11599. DirectionalLight.prototype.supportsVSM = function () {
  11600. return true;
  11601. };
  11602. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11603. return true;
  11604. };
  11605. DirectionalLight.prototype.needCube = function () {
  11606. return false;
  11607. };
  11608. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11609. return this.direction;
  11610. };
  11611. DirectionalLight.prototype.computeTransformedPosition = function () {
  11612. if (this.parent && this.parent.getWorldMatrix) {
  11613. if (!this.transformedPosition) {
  11614. this.transformedPosition = BABYLON.Vector3.Zero();
  11615. }
  11616. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11617. return true;
  11618. }
  11619. return false;
  11620. };
  11621. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11622. if (this.parent && this.parent.getWorldMatrix) {
  11623. if (!this._transformedDirection) {
  11624. this._transformedDirection = BABYLON.Vector3.Zero();
  11625. }
  11626. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11627. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11628. return;
  11629. }
  11630. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11631. };
  11632. DirectionalLight.prototype._getWorldMatrix = function () {
  11633. if (!this._worldMatrix) {
  11634. this._worldMatrix = BABYLON.Matrix.Identity();
  11635. }
  11636. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11637. return this._worldMatrix;
  11638. };
  11639. DirectionalLight.prototype.getTypeID = function () {
  11640. return 1;
  11641. };
  11642. __decorate([
  11643. BABYLON.serializeAsVector3()
  11644. ], DirectionalLight.prototype, "position", void 0);
  11645. __decorate([
  11646. BABYLON.serializeAsVector3()
  11647. ], DirectionalLight.prototype, "direction", void 0);
  11648. __decorate([
  11649. BABYLON.serialize()
  11650. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11651. __decorate([
  11652. BABYLON.serialize()
  11653. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11654. return DirectionalLight;
  11655. }(BABYLON.Light));
  11656. BABYLON.DirectionalLight = DirectionalLight;
  11657. })(BABYLON || (BABYLON = {}));
  11658. var BABYLON;
  11659. (function (BABYLON) {
  11660. var ShadowGenerator = (function () {
  11661. function ShadowGenerator(mapSize, light) {
  11662. var _this = this;
  11663. // Members
  11664. this._filter = ShadowGenerator.FILTER_NONE;
  11665. this.blurScale = 2;
  11666. this._blurBoxOffset = 0;
  11667. this._bias = 0.00005;
  11668. this._lightDirection = BABYLON.Vector3.Zero();
  11669. this.forceBackFacesOnly = false;
  11670. this._darkness = 0;
  11671. this._transparencyShadow = false;
  11672. this._viewMatrix = BABYLON.Matrix.Zero();
  11673. this._projectionMatrix = BABYLON.Matrix.Zero();
  11674. this._transformMatrix = BABYLON.Matrix.Zero();
  11675. this._worldViewProjection = BABYLON.Matrix.Zero();
  11676. this._currentFaceIndex = 0;
  11677. this._currentFaceIndexCache = 0;
  11678. this._useFullFloat = true;
  11679. this._light = light;
  11680. this._scene = light.getScene();
  11681. this._mapSize = mapSize;
  11682. light._shadowGenerator = this;
  11683. // Texture type fallback from float to int if not supported.
  11684. var textureType;
  11685. var caps = this._scene.getEngine().getCaps();
  11686. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11687. this._useFullFloat = true;
  11688. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11689. }
  11690. else {
  11691. this._useFullFloat = false;
  11692. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11693. }
  11694. // Render target
  11695. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11696. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11697. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11698. this._shadowMap.anisotropicFilteringLevel = 1;
  11699. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11700. this._shadowMap.renderParticles = false;
  11701. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11702. _this._currentFaceIndex = faceIndex;
  11703. });
  11704. this._shadowMap.onAfterUnbindObservable.add(function () {
  11705. if (!_this.useBlurVarianceShadowMap) {
  11706. return;
  11707. }
  11708. if (!_this._shadowMap2) {
  11709. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11710. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11711. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11712. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11713. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11714. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11715. effect.setTexture("textureSampler", _this._shadowMap);
  11716. });
  11717. _this.blurBoxOffset = 1;
  11718. }
  11719. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11720. });
  11721. // Custom render function
  11722. var renderSubMesh = function (subMesh) {
  11723. var mesh = subMesh.getRenderingMesh();
  11724. var scene = _this._scene;
  11725. var engine = scene.getEngine();
  11726. // Culling
  11727. engine.setState(subMesh.getMaterial().backFaceCulling);
  11728. // Managing instances
  11729. var batch = mesh._getInstancesRenderList(subMesh._id);
  11730. if (batch.mustReturn) {
  11731. return;
  11732. }
  11733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11734. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11735. engine.enableEffect(_this._effect);
  11736. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11737. var material = subMesh.getMaterial();
  11738. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11739. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11740. if (_this.getLight().needCube()) {
  11741. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11742. }
  11743. // Alpha test
  11744. if (material && material.needAlphaTesting()) {
  11745. var alphaTexture = material.getAlphaTestTexture();
  11746. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11747. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11748. }
  11749. // Bones
  11750. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11751. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11752. }
  11753. if (_this.forceBackFacesOnly) {
  11754. engine.setState(true, 0, false, true);
  11755. }
  11756. // Draw
  11757. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11758. if (_this.forceBackFacesOnly) {
  11759. engine.setState(true, 0, false, false);
  11760. }
  11761. }
  11762. else {
  11763. // Need to reset refresh rate of the shadowMap
  11764. _this._shadowMap.resetRefreshCounter();
  11765. }
  11766. };
  11767. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11768. var index;
  11769. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11770. renderSubMesh(opaqueSubMeshes.data[index]);
  11771. }
  11772. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11773. renderSubMesh(alphaTestSubMeshes.data[index]);
  11774. }
  11775. if (_this._transparencyShadow) {
  11776. for (index = 0; index < transparentSubMeshes.length; index++) {
  11777. renderSubMesh(transparentSubMeshes.data[index]);
  11778. }
  11779. }
  11780. };
  11781. this._shadowMap.onClearObservable.add(function (engine) {
  11782. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11783. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11784. }
  11785. else {
  11786. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11787. }
  11788. });
  11789. }
  11790. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11791. // Static
  11792. get: function () {
  11793. return ShadowGenerator._FILTER_NONE;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11799. get: function () {
  11800. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11806. get: function () {
  11807. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11813. get: function () {
  11814. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11820. get: function () {
  11821. return this._bias;
  11822. },
  11823. set: function (bias) {
  11824. this._bias = bias;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11830. get: function () {
  11831. return this._blurBoxOffset;
  11832. },
  11833. set: function (value) {
  11834. var _this = this;
  11835. if (this._blurBoxOffset === value) {
  11836. return;
  11837. }
  11838. this._blurBoxOffset = value;
  11839. if (this._boxBlurPostprocess) {
  11840. this._boxBlurPostprocess.dispose();
  11841. }
  11842. 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);
  11843. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11844. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11845. });
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11851. get: function () {
  11852. return this._filter;
  11853. },
  11854. set: function (value) {
  11855. if (this._filter === value) {
  11856. return;
  11857. }
  11858. this._filter = value;
  11859. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11860. this._shadowMap.anisotropicFilteringLevel = 16;
  11861. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11862. }
  11863. else {
  11864. this._shadowMap.anisotropicFilteringLevel = 1;
  11865. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11866. }
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11872. get: function () {
  11873. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11874. },
  11875. set: function (value) {
  11876. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11882. get: function () {
  11883. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11884. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11885. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11886. },
  11887. set: function (value) {
  11888. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11894. get: function () {
  11895. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11896. },
  11897. set: function (value) {
  11898. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11904. var defines = [];
  11905. if (this._useFullFloat) {
  11906. defines.push("#define FULLFLOAT");
  11907. }
  11908. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11909. defines.push("#define VSM");
  11910. }
  11911. if (this.getLight().needCube()) {
  11912. defines.push("#define CUBEMAP");
  11913. }
  11914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11915. var mesh = subMesh.getMesh();
  11916. var material = subMesh.getMaterial();
  11917. // Alpha test
  11918. if (material && material.needAlphaTesting()) {
  11919. defines.push("#define ALPHATEST");
  11920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11921. attribs.push(BABYLON.VertexBuffer.UVKind);
  11922. defines.push("#define UV1");
  11923. }
  11924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11925. var alphaTexture = material.getAlphaTestTexture();
  11926. if (alphaTexture.coordinatesIndex === 1) {
  11927. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11928. defines.push("#define UV2");
  11929. }
  11930. }
  11931. }
  11932. // Bones
  11933. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11936. if (mesh.numBoneInfluencers > 4) {
  11937. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11938. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11939. }
  11940. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11941. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11942. }
  11943. else {
  11944. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11945. }
  11946. // Instances
  11947. if (useInstances) {
  11948. defines.push("#define INSTANCES");
  11949. attribs.push("world0");
  11950. attribs.push("world1");
  11951. attribs.push("world2");
  11952. attribs.push("world3");
  11953. }
  11954. // Get correct effect
  11955. var join = defines.join("\n");
  11956. if (this._cachedDefines !== join) {
  11957. this._cachedDefines = join;
  11958. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11959. }
  11960. return this._effect.isReady();
  11961. };
  11962. ShadowGenerator.prototype.getShadowMap = function () {
  11963. return this._shadowMap;
  11964. };
  11965. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11966. if (this._shadowMap2) {
  11967. return this._shadowMap2;
  11968. }
  11969. return this._shadowMap;
  11970. };
  11971. ShadowGenerator.prototype.getLight = function () {
  11972. return this._light;
  11973. };
  11974. // Methods
  11975. ShadowGenerator.prototype.getTransformMatrix = function () {
  11976. var scene = this._scene;
  11977. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11978. return this._transformMatrix;
  11979. }
  11980. this._currentRenderID = scene.getRenderId();
  11981. this._currentFaceIndexCache = this._currentFaceIndex;
  11982. var lightPosition = this._light.position;
  11983. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11984. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11985. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11986. }
  11987. if (this._light.computeTransformedPosition()) {
  11988. lightPosition = this._light.transformedPosition;
  11989. }
  11990. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11991. this._cachedPosition = lightPosition.clone();
  11992. this._cachedDirection = this._lightDirection.clone();
  11993. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11994. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11995. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11996. }
  11997. return this._transformMatrix;
  11998. };
  11999. ShadowGenerator.prototype.getDarkness = function () {
  12000. return this._darkness;
  12001. };
  12002. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12003. if (darkness >= 1.0)
  12004. this._darkness = 1.0;
  12005. else if (darkness <= 0.0)
  12006. this._darkness = 0.0;
  12007. else
  12008. this._darkness = darkness;
  12009. };
  12010. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12011. this._transparencyShadow = hasShadow;
  12012. };
  12013. ShadowGenerator.prototype._packHalf = function (depth) {
  12014. var scale = depth * 255.0;
  12015. var fract = scale - Math.floor(scale);
  12016. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12017. };
  12018. ShadowGenerator.prototype.dispose = function () {
  12019. this._shadowMap.dispose();
  12020. if (this._shadowMap2) {
  12021. this._shadowMap2.dispose();
  12022. }
  12023. if (this._downSamplePostprocess) {
  12024. this._downSamplePostprocess.dispose();
  12025. }
  12026. if (this._boxBlurPostprocess) {
  12027. this._boxBlurPostprocess.dispose();
  12028. }
  12029. };
  12030. ShadowGenerator.prototype.serialize = function () {
  12031. var serializationObject = {};
  12032. serializationObject.lightId = this._light.id;
  12033. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12034. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12035. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12036. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12037. serializationObject.renderList = [];
  12038. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12039. var mesh = this.getShadowMap().renderList[meshIndex];
  12040. serializationObject.renderList.push(mesh.id);
  12041. }
  12042. return serializationObject;
  12043. };
  12044. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12045. //casting to point light, as light is missing the position attr and typescript complains.
  12046. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12047. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12048. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12049. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12050. meshes.forEach(function (mesh) {
  12051. shadowGenerator.getShadowMap().renderList.push(mesh);
  12052. });
  12053. }
  12054. if (parsedShadowGenerator.usePoissonSampling) {
  12055. shadowGenerator.usePoissonSampling = true;
  12056. }
  12057. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12058. shadowGenerator.useVarianceShadowMap = true;
  12059. }
  12060. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12061. shadowGenerator.useBlurVarianceShadowMap = true;
  12062. if (parsedShadowGenerator.blurScale) {
  12063. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12064. }
  12065. if (parsedShadowGenerator.blurBoxOffset) {
  12066. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12067. }
  12068. }
  12069. if (parsedShadowGenerator.bias !== undefined) {
  12070. shadowGenerator.bias = parsedShadowGenerator.bias;
  12071. }
  12072. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12073. return shadowGenerator;
  12074. };
  12075. ShadowGenerator._FILTER_NONE = 0;
  12076. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12077. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12078. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12079. return ShadowGenerator;
  12080. }());
  12081. BABYLON.ShadowGenerator = ShadowGenerator;
  12082. })(BABYLON || (BABYLON = {}));
  12083. var BABYLON;
  12084. (function (BABYLON) {
  12085. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12086. if (boxMin.x > sphereCenter.x + sphereRadius)
  12087. return false;
  12088. if (sphereCenter.x - sphereRadius > boxMax.x)
  12089. return false;
  12090. if (boxMin.y > sphereCenter.y + sphereRadius)
  12091. return false;
  12092. if (sphereCenter.y - sphereRadius > boxMax.y)
  12093. return false;
  12094. if (boxMin.z > sphereCenter.z + sphereRadius)
  12095. return false;
  12096. if (sphereCenter.z - sphereRadius > boxMax.z)
  12097. return false;
  12098. return true;
  12099. };
  12100. var getLowestRoot = (function () {
  12101. var result = { root: 0, found: false };
  12102. return function (a, b, c, maxR) {
  12103. result.root = 0;
  12104. result.found = false;
  12105. var determinant = b * b - 4.0 * a * c;
  12106. if (determinant < 0)
  12107. return result;
  12108. var sqrtD = Math.sqrt(determinant);
  12109. var r1 = (-b - sqrtD) / (2.0 * a);
  12110. var r2 = (-b + sqrtD) / (2.0 * a);
  12111. if (r1 > r2) {
  12112. var temp = r2;
  12113. r2 = r1;
  12114. r1 = temp;
  12115. }
  12116. if (r1 > 0 && r1 < maxR) {
  12117. result.root = r1;
  12118. result.found = true;
  12119. return result;
  12120. }
  12121. if (r2 > 0 && r2 < maxR) {
  12122. result.root = r2;
  12123. result.found = true;
  12124. return result;
  12125. }
  12126. return result;
  12127. };
  12128. })();
  12129. var Collider = (function () {
  12130. function Collider() {
  12131. this.radius = new BABYLON.Vector3(1, 1, 1);
  12132. this.retry = 0;
  12133. this.basePointWorld = BABYLON.Vector3.Zero();
  12134. this.velocityWorld = BABYLON.Vector3.Zero();
  12135. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12136. this._collisionPoint = BABYLON.Vector3.Zero();
  12137. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12138. this._tempVector = BABYLON.Vector3.Zero();
  12139. this._tempVector2 = BABYLON.Vector3.Zero();
  12140. this._tempVector3 = BABYLON.Vector3.Zero();
  12141. this._tempVector4 = BABYLON.Vector3.Zero();
  12142. this._edge = BABYLON.Vector3.Zero();
  12143. this._baseToVertex = BABYLON.Vector3.Zero();
  12144. this._destinationPoint = BABYLON.Vector3.Zero();
  12145. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12146. this._displacementVector = BABYLON.Vector3.Zero();
  12147. }
  12148. // Methods
  12149. Collider.prototype._initialize = function (source, dir, e) {
  12150. this.velocity = dir;
  12151. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12152. this.basePoint = source;
  12153. source.multiplyToRef(this.radius, this.basePointWorld);
  12154. dir.multiplyToRef(this.radius, this.velocityWorld);
  12155. this.velocityWorldLength = this.velocityWorld.length();
  12156. this.epsilon = e;
  12157. this.collisionFound = false;
  12158. };
  12159. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12160. pa.subtractToRef(point, this._tempVector);
  12161. pb.subtractToRef(point, this._tempVector2);
  12162. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12163. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12164. if (d < 0)
  12165. return false;
  12166. pc.subtractToRef(point, this._tempVector3);
  12167. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12168. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12169. if (d < 0)
  12170. return false;
  12171. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12172. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12173. return d >= 0;
  12174. };
  12175. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12176. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12177. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12178. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12179. return false;
  12180. }
  12181. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12182. return false;
  12183. return true;
  12184. };
  12185. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12186. var t0;
  12187. var embeddedInPlane = false;
  12188. //defensive programming, actually not needed.
  12189. if (!trianglePlaneArray) {
  12190. trianglePlaneArray = [];
  12191. }
  12192. if (!trianglePlaneArray[faceIndex]) {
  12193. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12194. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12195. }
  12196. var trianglePlane = trianglePlaneArray[faceIndex];
  12197. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12198. return;
  12199. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12200. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12201. if (normalDotVelocity == 0) {
  12202. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12203. return;
  12204. embeddedInPlane = true;
  12205. t0 = 0;
  12206. }
  12207. else {
  12208. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12209. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12210. if (t0 > t1) {
  12211. var temp = t1;
  12212. t1 = t0;
  12213. t0 = temp;
  12214. }
  12215. if (t0 > 1.0 || t1 < 0.0)
  12216. return;
  12217. if (t0 < 0)
  12218. t0 = 0;
  12219. if (t0 > 1.0)
  12220. t0 = 1.0;
  12221. }
  12222. this._collisionPoint.copyFromFloats(0, 0, 0);
  12223. var found = false;
  12224. var t = 1.0;
  12225. if (!embeddedInPlane) {
  12226. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12227. this.velocity.scaleToRef(t0, this._tempVector);
  12228. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12229. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12230. found = true;
  12231. t = t0;
  12232. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12233. }
  12234. }
  12235. if (!found) {
  12236. var velocitySquaredLength = this.velocity.lengthSquared();
  12237. var a = velocitySquaredLength;
  12238. this.basePoint.subtractToRef(p1, this._tempVector);
  12239. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12240. var c = this._tempVector.lengthSquared() - 1.0;
  12241. var lowestRoot = getLowestRoot(a, b, c, t);
  12242. if (lowestRoot.found) {
  12243. t = lowestRoot.root;
  12244. found = true;
  12245. this._collisionPoint.copyFrom(p1);
  12246. }
  12247. this.basePoint.subtractToRef(p2, this._tempVector);
  12248. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12249. c = this._tempVector.lengthSquared() - 1.0;
  12250. lowestRoot = getLowestRoot(a, b, c, t);
  12251. if (lowestRoot.found) {
  12252. t = lowestRoot.root;
  12253. found = true;
  12254. this._collisionPoint.copyFrom(p2);
  12255. }
  12256. this.basePoint.subtractToRef(p3, this._tempVector);
  12257. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12258. c = this._tempVector.lengthSquared() - 1.0;
  12259. lowestRoot = getLowestRoot(a, b, c, t);
  12260. if (lowestRoot.found) {
  12261. t = lowestRoot.root;
  12262. found = true;
  12263. this._collisionPoint.copyFrom(p3);
  12264. }
  12265. p2.subtractToRef(p1, this._edge);
  12266. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12267. var edgeSquaredLength = this._edge.lengthSquared();
  12268. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12269. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12270. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12271. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12272. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12273. lowestRoot = getLowestRoot(a, b, c, t);
  12274. if (lowestRoot.found) {
  12275. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12276. if (f >= 0.0 && f <= 1.0) {
  12277. t = lowestRoot.root;
  12278. found = true;
  12279. this._edge.scaleInPlace(f);
  12280. p1.addToRef(this._edge, this._collisionPoint);
  12281. }
  12282. }
  12283. p3.subtractToRef(p2, this._edge);
  12284. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12285. edgeSquaredLength = this._edge.lengthSquared();
  12286. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12287. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12288. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12289. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12290. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12291. lowestRoot = getLowestRoot(a, b, c, t);
  12292. if (lowestRoot.found) {
  12293. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12294. if (f >= 0.0 && f <= 1.0) {
  12295. t = lowestRoot.root;
  12296. found = true;
  12297. this._edge.scaleInPlace(f);
  12298. p2.addToRef(this._edge, this._collisionPoint);
  12299. }
  12300. }
  12301. p1.subtractToRef(p3, this._edge);
  12302. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12303. edgeSquaredLength = this._edge.lengthSquared();
  12304. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12305. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12306. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12307. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12308. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12309. lowestRoot = getLowestRoot(a, b, c, t);
  12310. if (lowestRoot.found) {
  12311. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12312. if (f >= 0.0 && f <= 1.0) {
  12313. t = lowestRoot.root;
  12314. found = true;
  12315. this._edge.scaleInPlace(f);
  12316. p3.addToRef(this._edge, this._collisionPoint);
  12317. }
  12318. }
  12319. }
  12320. if (found) {
  12321. var distToCollision = t * this.velocity.length();
  12322. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12323. if (!this.intersectionPoint) {
  12324. this.intersectionPoint = this._collisionPoint.clone();
  12325. }
  12326. else {
  12327. this.intersectionPoint.copyFrom(this._collisionPoint);
  12328. }
  12329. this.nearestDistance = distToCollision;
  12330. this.collisionFound = true;
  12331. }
  12332. }
  12333. };
  12334. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12335. for (var i = indexStart; i < indexEnd; i += 3) {
  12336. var p1 = pts[indices[i] - decal];
  12337. var p2 = pts[indices[i + 1] - decal];
  12338. var p3 = pts[indices[i + 2] - decal];
  12339. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12340. }
  12341. };
  12342. Collider.prototype._getResponse = function (pos, vel) {
  12343. pos.addToRef(vel, this._destinationPoint);
  12344. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12345. this.basePoint.addToRef(vel, pos);
  12346. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12347. this._slidePlaneNormal.normalize();
  12348. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12349. pos.addInPlace(this._displacementVector);
  12350. this.intersectionPoint.addInPlace(this._displacementVector);
  12351. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12352. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12353. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12354. };
  12355. return Collider;
  12356. }());
  12357. BABYLON.Collider = Collider;
  12358. })(BABYLON || (BABYLON = {}));
  12359. var BABYLON;
  12360. (function (BABYLON) {
  12361. //WebWorker code will be inserted to this variable.
  12362. BABYLON.CollisionWorker = "";
  12363. (function (WorkerTaskType) {
  12364. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12365. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12366. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12367. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12368. var WorkerTaskType = BABYLON.WorkerTaskType;
  12369. (function (WorkerReplyType) {
  12370. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12371. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12372. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12373. var WorkerReplyType = BABYLON.WorkerReplyType;
  12374. var CollisionCoordinatorWorker = (function () {
  12375. function CollisionCoordinatorWorker() {
  12376. var _this = this;
  12377. this._scaledPosition = BABYLON.Vector3.Zero();
  12378. this._scaledVelocity = BABYLON.Vector3.Zero();
  12379. this.onMeshUpdated = function (mesh) {
  12380. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12381. };
  12382. this.onGeometryUpdated = function (geometry) {
  12383. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12384. };
  12385. this._afterRender = function () {
  12386. if (!_this._init)
  12387. return;
  12388. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12389. return;
  12390. }
  12391. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12392. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12393. if (_this._runningUpdated > 4) {
  12394. return;
  12395. }
  12396. ++_this._runningUpdated;
  12397. var payload = {
  12398. updatedMeshes: _this._addUpdateMeshesList,
  12399. updatedGeometries: _this._addUpdateGeometriesList,
  12400. removedGeometries: _this._toRemoveGeometryArray,
  12401. removedMeshes: _this._toRemoveMeshesArray
  12402. };
  12403. var message = {
  12404. payload: payload,
  12405. taskType: WorkerTaskType.UPDATE
  12406. };
  12407. var serializable = [];
  12408. for (var id in payload.updatedGeometries) {
  12409. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12410. //prepare transferables
  12411. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12412. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12413. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12414. }
  12415. }
  12416. _this._worker.postMessage(message, serializable);
  12417. _this._addUpdateMeshesList = {};
  12418. _this._addUpdateGeometriesList = {};
  12419. _this._toRemoveGeometryArray = [];
  12420. _this._toRemoveMeshesArray = [];
  12421. };
  12422. this._onMessageFromWorker = function (e) {
  12423. var returnData = e.data;
  12424. if (returnData.error != WorkerReplyType.SUCCESS) {
  12425. //TODO what errors can be returned from the worker?
  12426. BABYLON.Tools.Warn("error returned from worker!");
  12427. return;
  12428. }
  12429. switch (returnData.taskType) {
  12430. case WorkerTaskType.INIT:
  12431. _this._init = true;
  12432. //Update the worked with ALL of the scene's current state
  12433. _this._scene.meshes.forEach(function (mesh) {
  12434. _this.onMeshAdded(mesh);
  12435. });
  12436. _this._scene.getGeometries().forEach(function (geometry) {
  12437. _this.onGeometryAdded(geometry);
  12438. });
  12439. break;
  12440. case WorkerTaskType.UPDATE:
  12441. _this._runningUpdated--;
  12442. break;
  12443. case WorkerTaskType.COLLIDE:
  12444. _this._runningCollisionTask = false;
  12445. var returnPayload = returnData.payload;
  12446. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12447. return;
  12448. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12449. //cleanup
  12450. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12451. break;
  12452. }
  12453. };
  12454. this._collisionsCallbackArray = [];
  12455. this._init = false;
  12456. this._runningUpdated = 0;
  12457. this._runningCollisionTask = false;
  12458. this._addUpdateMeshesList = {};
  12459. this._addUpdateGeometriesList = {};
  12460. this._toRemoveGeometryArray = [];
  12461. this._toRemoveMeshesArray = [];
  12462. }
  12463. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12464. if (!this._init)
  12465. return;
  12466. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12467. return;
  12468. position.divideToRef(collider.radius, this._scaledPosition);
  12469. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12470. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12471. var payload = {
  12472. collider: {
  12473. position: this._scaledPosition.asArray(),
  12474. velocity: this._scaledVelocity.asArray(),
  12475. radius: collider.radius.asArray()
  12476. },
  12477. collisionId: collisionIndex,
  12478. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12479. maximumRetry: maximumRetry
  12480. };
  12481. var message = {
  12482. payload: payload,
  12483. taskType: WorkerTaskType.COLLIDE
  12484. };
  12485. this._worker.postMessage(message);
  12486. };
  12487. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12488. this._scene = scene;
  12489. this._scene.registerAfterRender(this._afterRender);
  12490. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12491. this._worker = new Worker(workerUrl);
  12492. this._worker.onmessage = this._onMessageFromWorker;
  12493. var message = {
  12494. payload: {},
  12495. taskType: WorkerTaskType.INIT
  12496. };
  12497. this._worker.postMessage(message);
  12498. };
  12499. CollisionCoordinatorWorker.prototype.destroy = function () {
  12500. this._scene.unregisterAfterRender(this._afterRender);
  12501. this._worker.terminate();
  12502. };
  12503. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12504. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12505. this.onMeshUpdated(mesh);
  12506. };
  12507. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12508. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12509. };
  12510. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12511. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12512. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12513. this.onGeometryUpdated(geometry);
  12514. };
  12515. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12516. this._toRemoveGeometryArray.push(geometry.id);
  12517. };
  12518. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12519. var submeshes = [];
  12520. if (mesh.subMeshes) {
  12521. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12522. return {
  12523. position: idx,
  12524. verticesStart: sm.verticesStart,
  12525. verticesCount: sm.verticesCount,
  12526. indexStart: sm.indexStart,
  12527. indexCount: sm.indexCount,
  12528. hasMaterial: !!sm.getMaterial(),
  12529. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12530. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12531. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12532. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12533. };
  12534. });
  12535. }
  12536. var geometryId = null;
  12537. if (mesh instanceof BABYLON.Mesh) {
  12538. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12539. }
  12540. else if (mesh instanceof BABYLON.InstancedMesh) {
  12541. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12542. }
  12543. return {
  12544. uniqueId: mesh.uniqueId,
  12545. id: mesh.id,
  12546. name: mesh.name,
  12547. geometryId: geometryId,
  12548. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12549. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12550. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12551. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12552. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12553. subMeshes: submeshes,
  12554. checkCollisions: mesh.checkCollisions
  12555. };
  12556. };
  12557. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12558. return {
  12559. id: geometry.id,
  12560. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12561. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12562. indices: new Int32Array(geometry.getIndices() || []),
  12563. };
  12564. };
  12565. return CollisionCoordinatorWorker;
  12566. }());
  12567. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12568. var CollisionCoordinatorLegacy = (function () {
  12569. function CollisionCoordinatorLegacy() {
  12570. this._scaledPosition = BABYLON.Vector3.Zero();
  12571. this._scaledVelocity = BABYLON.Vector3.Zero();
  12572. this._finalPosition = BABYLON.Vector3.Zero();
  12573. }
  12574. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12575. position.divideToRef(collider.radius, this._scaledPosition);
  12576. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12577. collider.collidedMesh = null;
  12578. collider.retry = 0;
  12579. collider.initialVelocity = this._scaledVelocity;
  12580. collider.initialPosition = this._scaledPosition;
  12581. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12582. this._finalPosition.multiplyInPlace(collider.radius);
  12583. //run the callback
  12584. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12585. };
  12586. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12587. this._scene = scene;
  12588. };
  12589. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12590. //Legacy need no destruction method.
  12591. };
  12592. //No update in legacy mode
  12593. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12594. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12595. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12596. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12597. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12598. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12599. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12600. if (excludedMesh === void 0) { excludedMesh = null; }
  12601. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12602. if (collider.retry >= maximumRetry) {
  12603. finalPosition.copyFrom(position);
  12604. return;
  12605. }
  12606. collider._initialize(position, velocity, closeDistance);
  12607. // Check all meshes
  12608. for (var index = 0; index < this._scene.meshes.length; index++) {
  12609. var mesh = this._scene.meshes[index];
  12610. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12611. mesh._checkCollision(collider);
  12612. }
  12613. }
  12614. if (!collider.collisionFound) {
  12615. position.addToRef(velocity, finalPosition);
  12616. return;
  12617. }
  12618. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12619. collider._getResponse(position, velocity);
  12620. }
  12621. if (velocity.length() <= closeDistance) {
  12622. finalPosition.copyFrom(position);
  12623. return;
  12624. }
  12625. collider.retry++;
  12626. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12627. };
  12628. return CollisionCoordinatorLegacy;
  12629. }());
  12630. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12631. })(BABYLON || (BABYLON = {}));
  12632. var BABYLON;
  12633. (function (BABYLON) {
  12634. var Camera = (function (_super) {
  12635. __extends(Camera, _super);
  12636. function Camera(name, position, scene) {
  12637. _super.call(this, name, scene);
  12638. this.upVector = BABYLON.Vector3.Up();
  12639. this.orthoLeft = null;
  12640. this.orthoRight = null;
  12641. this.orthoBottom = null;
  12642. this.orthoTop = null;
  12643. this.fov = 0.8;
  12644. this.minZ = 1.0;
  12645. this.maxZ = 10000.0;
  12646. this.inertia = 0.9;
  12647. this.mode = Camera.PERSPECTIVE_CAMERA;
  12648. this.isIntermediate = false;
  12649. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12650. this.layerMask = 0x0FFFFFFF;
  12651. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12652. // Camera rig members
  12653. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12654. this._rigCameras = new Array();
  12655. // Cache
  12656. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12657. this._projectionMatrix = new BABYLON.Matrix();
  12658. this._doNotComputeProjectionMatrix = false;
  12659. this._postProcesses = new Array();
  12660. this._transformMatrix = BABYLON.Matrix.Zero();
  12661. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12662. this._activeMeshes = new BABYLON.SmartArray(256);
  12663. this._globalPosition = BABYLON.Vector3.Zero();
  12664. this._refreshFrustumPlanes = true;
  12665. scene.addCamera(this);
  12666. if (!scene.activeCamera) {
  12667. scene.activeCamera = this;
  12668. }
  12669. this.position = position;
  12670. }
  12671. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12672. get: function () {
  12673. return Camera._PERSPECTIVE_CAMERA;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12679. get: function () {
  12680. return Camera._ORTHOGRAPHIC_CAMERA;
  12681. },
  12682. enumerable: true,
  12683. configurable: true
  12684. });
  12685. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12686. get: function () {
  12687. return Camera._FOVMODE_VERTICAL_FIXED;
  12688. },
  12689. enumerable: true,
  12690. configurable: true
  12691. });
  12692. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12693. get: function () {
  12694. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12695. },
  12696. enumerable: true,
  12697. configurable: true
  12698. });
  12699. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12700. get: function () {
  12701. return Camera._RIG_MODE_NONE;
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12707. get: function () {
  12708. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12709. },
  12710. enumerable: true,
  12711. configurable: true
  12712. });
  12713. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12714. get: function () {
  12715. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12721. get: function () {
  12722. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12728. get: function () {
  12729. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12730. },
  12731. enumerable: true,
  12732. configurable: true
  12733. });
  12734. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12735. get: function () {
  12736. return Camera._RIG_MODE_VR;
  12737. },
  12738. enumerable: true,
  12739. configurable: true
  12740. });
  12741. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12742. get: function () {
  12743. return Camera._RIG_MODE_WEBVR;
  12744. },
  12745. enumerable: true,
  12746. configurable: true
  12747. });
  12748. /**
  12749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12750. */
  12751. Camera.prototype.toString = function (fullDetails) {
  12752. var ret = "Name: " + this.name;
  12753. ret += ", type: " + this.getTypeName();
  12754. if (this.animations) {
  12755. for (var i = 0; i < this.animations.length; i++) {
  12756. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12757. }
  12758. }
  12759. if (fullDetails) {
  12760. }
  12761. return ret;
  12762. };
  12763. Object.defineProperty(Camera.prototype, "globalPosition", {
  12764. get: function () {
  12765. return this._globalPosition;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Camera.prototype.getActiveMeshes = function () {
  12771. return this._activeMeshes;
  12772. };
  12773. Camera.prototype.isActiveMesh = function (mesh) {
  12774. return (this._activeMeshes.indexOf(mesh) !== -1);
  12775. };
  12776. //Cache
  12777. Camera.prototype._initCache = function () {
  12778. _super.prototype._initCache.call(this);
  12779. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12780. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12781. this._cache.mode = undefined;
  12782. this._cache.minZ = undefined;
  12783. this._cache.maxZ = undefined;
  12784. this._cache.fov = undefined;
  12785. this._cache.fovMode = undefined;
  12786. this._cache.aspectRatio = undefined;
  12787. this._cache.orthoLeft = undefined;
  12788. this._cache.orthoRight = undefined;
  12789. this._cache.orthoBottom = undefined;
  12790. this._cache.orthoTop = undefined;
  12791. this._cache.renderWidth = undefined;
  12792. this._cache.renderHeight = undefined;
  12793. };
  12794. Camera.prototype._updateCache = function (ignoreParentClass) {
  12795. if (!ignoreParentClass) {
  12796. _super.prototype._updateCache.call(this);
  12797. }
  12798. var engine = this.getEngine();
  12799. this._cache.position.copyFrom(this.position);
  12800. this._cache.upVector.copyFrom(this.upVector);
  12801. this._cache.mode = this.mode;
  12802. this._cache.minZ = this.minZ;
  12803. this._cache.maxZ = this.maxZ;
  12804. this._cache.fov = this.fov;
  12805. this._cache.fovMode = this.fovMode;
  12806. this._cache.aspectRatio = engine.getAspectRatio(this);
  12807. this._cache.orthoLeft = this.orthoLeft;
  12808. this._cache.orthoRight = this.orthoRight;
  12809. this._cache.orthoBottom = this.orthoBottom;
  12810. this._cache.orthoTop = this.orthoTop;
  12811. this._cache.renderWidth = engine.getRenderWidth();
  12812. this._cache.renderHeight = engine.getRenderHeight();
  12813. };
  12814. Camera.prototype._updateFromScene = function () {
  12815. this.updateCache();
  12816. this.update();
  12817. };
  12818. // Synchronized
  12819. Camera.prototype._isSynchronized = function () {
  12820. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12821. };
  12822. Camera.prototype._isSynchronizedViewMatrix = function () {
  12823. if (!_super.prototype._isSynchronized.call(this))
  12824. return false;
  12825. return this._cache.position.equals(this.position)
  12826. && this._cache.upVector.equals(this.upVector)
  12827. && this.isSynchronizedWithParent();
  12828. };
  12829. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12830. var check = this._cache.mode === this.mode
  12831. && this._cache.minZ === this.minZ
  12832. && this._cache.maxZ === this.maxZ;
  12833. if (!check) {
  12834. return false;
  12835. }
  12836. var engine = this.getEngine();
  12837. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12838. check = this._cache.fov === this.fov
  12839. && this._cache.fovMode === this.fovMode
  12840. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12841. }
  12842. else {
  12843. check = this._cache.orthoLeft === this.orthoLeft
  12844. && this._cache.orthoRight === this.orthoRight
  12845. && this._cache.orthoBottom === this.orthoBottom
  12846. && this._cache.orthoTop === this.orthoTop
  12847. && this._cache.renderWidth === engine.getRenderWidth()
  12848. && this._cache.renderHeight === engine.getRenderHeight();
  12849. }
  12850. return check;
  12851. };
  12852. // Controls
  12853. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12854. };
  12855. Camera.prototype.detachControl = function (element) {
  12856. };
  12857. Camera.prototype.update = function () {
  12858. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12859. this._updateRigCameras();
  12860. }
  12861. this._checkInputs();
  12862. };
  12863. Camera.prototype._checkInputs = function () {
  12864. };
  12865. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12866. // invalidate framebuffer
  12867. if (this._postProcesses.length > 0) {
  12868. this._postProcesses[0].markTextureDirty();
  12869. }
  12870. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12871. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12872. var cam = this._rigCameras[i];
  12873. var rigPostProcess = cam._rigPostProcess;
  12874. // for VR rig, there does not have to be a post process
  12875. if (rigPostProcess) {
  12876. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12877. if (isPass) {
  12878. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12879. cam.isIntermediate = this._postProcesses.length === 0;
  12880. }
  12881. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12882. rigPostProcess.markTextureDirty();
  12883. }
  12884. else {
  12885. cam._postProcesses = this._postProcesses.slice(0);
  12886. }
  12887. }
  12888. };
  12889. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12890. if (insertAt === void 0) { insertAt = null; }
  12891. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12892. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12893. return 0;
  12894. }
  12895. if (insertAt == null || insertAt < 0) {
  12896. this._postProcesses.push(postProcess);
  12897. }
  12898. else {
  12899. this._postProcesses.splice(insertAt, 0, postProcess);
  12900. }
  12901. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12902. return this._postProcesses.indexOf(postProcess);
  12903. };
  12904. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12905. if (atIndices === void 0) { atIndices = null; }
  12906. var result = [];
  12907. var i;
  12908. var index;
  12909. if (!atIndices) {
  12910. var idx = this._postProcesses.indexOf(postProcess);
  12911. if (idx !== -1) {
  12912. this._postProcesses.splice(idx, 1);
  12913. }
  12914. }
  12915. else {
  12916. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12917. // iterate descending, so can just splice as we go
  12918. for (i = atIndices.length - 1; i >= 0; i--) {
  12919. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12920. result.push(i);
  12921. continue;
  12922. }
  12923. this._postProcesses.splice(index, 1);
  12924. }
  12925. }
  12926. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12927. return result;
  12928. };
  12929. Camera.prototype.getWorldMatrix = function () {
  12930. if (!this._worldMatrix) {
  12931. this._worldMatrix = BABYLON.Matrix.Identity();
  12932. }
  12933. var viewMatrix = this.getViewMatrix();
  12934. viewMatrix.invertToRef(this._worldMatrix);
  12935. return this._worldMatrix;
  12936. };
  12937. Camera.prototype._getViewMatrix = function () {
  12938. return BABYLON.Matrix.Identity();
  12939. };
  12940. Camera.prototype.getViewMatrix = function (force) {
  12941. this._computedViewMatrix = this._computeViewMatrix(force);
  12942. if (!force && this._isSynchronizedViewMatrix()) {
  12943. return this._computedViewMatrix;
  12944. }
  12945. this._refreshFrustumPlanes = true;
  12946. if (!this.parent || !this.parent.getWorldMatrix) {
  12947. this._globalPosition.copyFrom(this.position);
  12948. }
  12949. else {
  12950. if (!this._worldMatrix) {
  12951. this._worldMatrix = BABYLON.Matrix.Identity();
  12952. }
  12953. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12954. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12955. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12956. this._computedViewMatrix.invert();
  12957. this._markSyncedWithParent();
  12958. }
  12959. this._currentRenderId = this.getScene().getRenderId();
  12960. return this._computedViewMatrix;
  12961. };
  12962. Camera.prototype._computeViewMatrix = function (force) {
  12963. if (!force && this._isSynchronizedViewMatrix()) {
  12964. return this._computedViewMatrix;
  12965. }
  12966. this._computedViewMatrix = this._getViewMatrix();
  12967. this._currentRenderId = this.getScene().getRenderId();
  12968. return this._computedViewMatrix;
  12969. };
  12970. Camera.prototype.freezeProjectionMatrix = function (projection) {
  12971. this._doNotComputeProjectionMatrix = true;
  12972. if (projection !== undefined) {
  12973. this._projectionMatrix = projection;
  12974. }
  12975. };
  12976. ;
  12977. Camera.prototype.unfreezeProjectionMatrix = function () {
  12978. this._doNotComputeProjectionMatrix = false;
  12979. };
  12980. ;
  12981. Camera.prototype.getProjectionMatrix = function (force) {
  12982. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  12983. return this._projectionMatrix;
  12984. }
  12985. this._refreshFrustumPlanes = true;
  12986. var engine = this.getEngine();
  12987. var scene = this.getScene();
  12988. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12989. if (this.minZ <= 0) {
  12990. this.minZ = 0.1;
  12991. }
  12992. if (scene.useRightHandedSystem) {
  12993. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12994. }
  12995. else {
  12996. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12997. }
  12998. return this._projectionMatrix;
  12999. }
  13000. var halfWidth = engine.getRenderWidth() / 2.0;
  13001. var halfHeight = engine.getRenderHeight() / 2.0;
  13002. if (scene.useRightHandedSystem) {
  13003. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13004. }
  13005. else {
  13006. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13007. }
  13008. return this._projectionMatrix;
  13009. };
  13010. Camera.prototype.getTranformationMatrix = function () {
  13011. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13012. return this._transformMatrix;
  13013. };
  13014. Camera.prototype.updateFrustumPlanes = function () {
  13015. if (!this._refreshFrustumPlanes) {
  13016. return;
  13017. }
  13018. this.getTranformationMatrix();
  13019. if (!this._frustumPlanes) {
  13020. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13021. }
  13022. else {
  13023. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13024. }
  13025. this._refreshFrustumPlanes = false;
  13026. };
  13027. Camera.prototype.isInFrustum = function (target) {
  13028. this.updateFrustumPlanes();
  13029. return target.isInFrustum(this._frustumPlanes);
  13030. };
  13031. Camera.prototype.isCompletelyInFrustum = function (target) {
  13032. this.updateFrustumPlanes();
  13033. return target.isCompletelyInFrustum(this._frustumPlanes);
  13034. };
  13035. Camera.prototype.dispose = function () {
  13036. // Animations
  13037. this.getScene().stopAnimation(this);
  13038. // Remove from scene
  13039. this.getScene().removeCamera(this);
  13040. while (this._rigCameras.length > 0) {
  13041. this._rigCameras.pop().dispose();
  13042. }
  13043. // Postprocesses
  13044. for (var i = 0; i < this._postProcesses.length; ++i) {
  13045. this._postProcesses[i].dispose(this);
  13046. }
  13047. _super.prototype.dispose.call(this);
  13048. };
  13049. // ---- Camera rigs section ----
  13050. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13051. while (this._rigCameras.length > 0) {
  13052. this._rigCameras.pop().dispose();
  13053. }
  13054. this.cameraRigMode = mode;
  13055. this._cameraRigParams = {};
  13056. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13057. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13058. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13059. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13060. // create the rig cameras, unless none
  13061. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13062. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13063. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13064. }
  13065. switch (this.cameraRigMode) {
  13066. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13067. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13068. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13069. break;
  13070. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13071. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13072. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13073. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13074. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13075. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13076. break;
  13077. case Camera.RIG_MODE_VR:
  13078. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13079. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13080. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13081. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13082. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13083. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13084. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13085. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13086. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13087. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13088. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13089. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13090. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13091. if (metrics.compensateDistortion) {
  13092. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13093. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13094. }
  13095. break;
  13096. case Camera.RIG_MODE_WEBVR:
  13097. if (rigParams.vrDisplay) {
  13098. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13099. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13100. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13101. this._rigCameras[0].setCameraRigParameter("left", true);
  13102. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13103. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13104. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13105. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13106. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13107. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13108. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13109. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13110. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13111. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13112. }
  13113. break;
  13114. }
  13115. this._cascadePostProcessesToRigCams();
  13116. this.
  13117. update();
  13118. };
  13119. Camera.prototype._getVRProjectionMatrix = function () {
  13120. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13121. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13122. return this._projectionMatrix;
  13123. };
  13124. Camera.prototype._getWebVRProjectionMatrix = function () {
  13125. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13126. //babylon compatible matrix
  13127. [8, 9, 10, 11].forEach(function (num) {
  13128. projectionArray[num] *= -1;
  13129. });
  13130. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13131. return this._projectionMatrix;
  13132. };
  13133. //Can be used, but we'll use the free camera's view matrix calculation
  13134. Camera.prototype._getWebVRViewMatrix = function () {
  13135. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13136. //babylon compatible matrix
  13137. [8, 9, 10, 11].forEach(function (num) {
  13138. projectionArray[num] *= -1;
  13139. });
  13140. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13141. return this._webvrViewMatrix;
  13142. };
  13143. Camera.prototype.setCameraRigParameter = function (name, value) {
  13144. if (!this._cameraRigParams) {
  13145. this._cameraRigParams = {};
  13146. }
  13147. this._cameraRigParams[name] = value;
  13148. //provisionnally:
  13149. if (name === "interaxialDistance") {
  13150. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13151. }
  13152. };
  13153. /**
  13154. * needs to be overridden by children so sub has required properties to be copied
  13155. */
  13156. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13157. return null;
  13158. };
  13159. /**
  13160. * May need to be overridden by children
  13161. */
  13162. Camera.prototype._updateRigCameras = function () {
  13163. for (var i = 0; i < this._rigCameras.length; i++) {
  13164. this._rigCameras[i].minZ = this.minZ;
  13165. this._rigCameras[i].maxZ = this.maxZ;
  13166. this._rigCameras[i].fov = this.fov;
  13167. }
  13168. // only update viewport when ANAGLYPH
  13169. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13170. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13171. }
  13172. };
  13173. Camera.prototype._setupInputs = function () {
  13174. };
  13175. Camera.prototype.serialize = function () {
  13176. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13177. // Type
  13178. serializationObject.type = this.getTypeName();
  13179. // Parent
  13180. if (this.parent) {
  13181. serializationObject.parentId = this.parent.id;
  13182. }
  13183. if (this.inputs) {
  13184. this.inputs.serialize(serializationObject);
  13185. }
  13186. // Animations
  13187. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13188. serializationObject.ranges = this.serializeAnimationRanges();
  13189. return serializationObject;
  13190. };
  13191. Camera.prototype.getTypeName = function () {
  13192. return "Camera";
  13193. };
  13194. Camera.prototype.clone = function (name) {
  13195. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13196. };
  13197. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13198. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13199. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13200. switch (type) {
  13201. case "ArcRotateCamera":
  13202. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13203. case "DeviceOrientationCamera":
  13204. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13205. case "FollowCamera":
  13206. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13207. case "ArcFollowCamera":
  13208. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13209. case "GamepadCamera":
  13210. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13211. case "TouchCamera":
  13212. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13213. case "VirtualJoysticksCamera":
  13214. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13215. case "WebVRFreeCamera":
  13216. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13217. case "VRDeviceOrientationFreeCamera":
  13218. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13219. case "AnaglyphArcRotateCamera":
  13220. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13221. case "AnaglyphFreeCamera":
  13222. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13223. case "AnaglyphGamepadCamera":
  13224. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13225. case "AnaglyphUniversalCamera":
  13226. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13227. case "StereoscopicArcRotateCamera":
  13228. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13229. case "StereoscopicFreeCamera":
  13230. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13231. case "StereoscopicGamepadCamera":
  13232. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13233. case "StereoscopicUniversalCamera":
  13234. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13235. case "FreeCamera":
  13236. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13237. default:
  13238. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13239. }
  13240. };
  13241. Camera.Parse = function (parsedCamera, scene) {
  13242. var type = parsedCamera.type;
  13243. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13244. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13245. // Parent
  13246. if (parsedCamera.parentId) {
  13247. camera._waitingParentId = parsedCamera.parentId;
  13248. }
  13249. //If camera has an input manager, let it parse inputs settings
  13250. if (camera.inputs) {
  13251. camera.inputs.parse(parsedCamera);
  13252. camera._setupInputs();
  13253. }
  13254. // Target
  13255. if (parsedCamera.target) {
  13256. if (camera.setTarget) {
  13257. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13258. }
  13259. }
  13260. // Apply 3d rig, when found
  13261. if (parsedCamera.cameraRigMode) {
  13262. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13263. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13264. }
  13265. // Animations
  13266. if (parsedCamera.animations) {
  13267. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13268. var parsedAnimation = parsedCamera.animations[animationIndex];
  13269. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13270. }
  13271. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13272. }
  13273. if (parsedCamera.autoAnimate) {
  13274. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13275. }
  13276. return camera;
  13277. };
  13278. // Statics
  13279. Camera._PERSPECTIVE_CAMERA = 0;
  13280. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13281. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13282. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13283. Camera._RIG_MODE_NONE = 0;
  13284. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13285. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13286. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13287. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13288. Camera._RIG_MODE_VR = 20;
  13289. Camera._RIG_MODE_WEBVR = 21;
  13290. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13291. __decorate([
  13292. BABYLON.serializeAsVector3()
  13293. ], Camera.prototype, "position", void 0);
  13294. __decorate([
  13295. BABYLON.serializeAsVector3()
  13296. ], Camera.prototype, "upVector", void 0);
  13297. __decorate([
  13298. BABYLON.serialize()
  13299. ], Camera.prototype, "orthoLeft", void 0);
  13300. __decorate([
  13301. BABYLON.serialize()
  13302. ], Camera.prototype, "orthoRight", void 0);
  13303. __decorate([
  13304. BABYLON.serialize()
  13305. ], Camera.prototype, "orthoBottom", void 0);
  13306. __decorate([
  13307. BABYLON.serialize()
  13308. ], Camera.prototype, "orthoTop", void 0);
  13309. __decorate([
  13310. BABYLON.serialize()
  13311. ], Camera.prototype, "fov", void 0);
  13312. __decorate([
  13313. BABYLON.serialize()
  13314. ], Camera.prototype, "minZ", void 0);
  13315. __decorate([
  13316. BABYLON.serialize()
  13317. ], Camera.prototype, "maxZ", void 0);
  13318. __decorate([
  13319. BABYLON.serialize()
  13320. ], Camera.prototype, "inertia", void 0);
  13321. __decorate([
  13322. BABYLON.serialize()
  13323. ], Camera.prototype, "mode", void 0);
  13324. __decorate([
  13325. BABYLON.serialize()
  13326. ], Camera.prototype, "layerMask", void 0);
  13327. __decorate([
  13328. BABYLON.serialize()
  13329. ], Camera.prototype, "fovMode", void 0);
  13330. __decorate([
  13331. BABYLON.serialize()
  13332. ], Camera.prototype, "cameraRigMode", void 0);
  13333. __decorate([
  13334. BABYLON.serialize()
  13335. ], Camera.prototype, "interaxialDistance", void 0);
  13336. __decorate([
  13337. BABYLON.serialize()
  13338. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13339. return Camera;
  13340. }(BABYLON.Node));
  13341. BABYLON.Camera = Camera;
  13342. })(BABYLON || (BABYLON = {}));
  13343. var BABYLON;
  13344. (function (BABYLON) {
  13345. BABYLON.CameraInputTypes = {};
  13346. var CameraInputsManager = (function () {
  13347. function CameraInputsManager(camera) {
  13348. this.attached = {};
  13349. this.camera = camera;
  13350. this.checkInputs = function () { };
  13351. }
  13352. CameraInputsManager.prototype.add = function (input) {
  13353. var type = input.getSimpleName();
  13354. if (this.attached[type]) {
  13355. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13356. return;
  13357. }
  13358. this.attached[type] = input;
  13359. input.camera = this.camera;
  13360. //for checkInputs, we are dynamically creating a function
  13361. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13362. if (input.checkInputs) {
  13363. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13364. }
  13365. if (this.attachedElement) {
  13366. input.attachControl(this.attachedElement);
  13367. }
  13368. };
  13369. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13370. for (var cam in this.attached) {
  13371. var input = this.attached[cam];
  13372. if (input === inputToRemove) {
  13373. input.detachControl(this.attachedElement);
  13374. delete this.attached[cam];
  13375. this.rebuildInputCheck();
  13376. }
  13377. }
  13378. };
  13379. CameraInputsManager.prototype.removeByType = function (inputType) {
  13380. for (var cam in this.attached) {
  13381. var input = this.attached[cam];
  13382. if (input.getTypeName() === inputType) {
  13383. input.detachControl(this.attachedElement);
  13384. delete this.attached[cam];
  13385. this.rebuildInputCheck();
  13386. }
  13387. }
  13388. };
  13389. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13390. var current = this.checkInputs;
  13391. return function () {
  13392. current();
  13393. fn();
  13394. };
  13395. };
  13396. CameraInputsManager.prototype.attachInput = function (input) {
  13397. input.attachControl(this.attachedElement, this.noPreventDefault);
  13398. };
  13399. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13400. if (this.attachedElement) {
  13401. return;
  13402. }
  13403. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13404. this.attachedElement = element;
  13405. this.noPreventDefault = noPreventDefault;
  13406. for (var cam in this.attached) {
  13407. var input = this.attached[cam];
  13408. this.attached[cam].attachControl(element, noPreventDefault);
  13409. }
  13410. };
  13411. CameraInputsManager.prototype.detachElement = function (element) {
  13412. if (this.attachedElement !== element) {
  13413. return;
  13414. }
  13415. for (var cam in this.attached) {
  13416. var input = this.attached[cam];
  13417. this.attached[cam].detachControl(element);
  13418. }
  13419. this.attachedElement = null;
  13420. };
  13421. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13422. this.checkInputs = function () { };
  13423. for (var cam in this.attached) {
  13424. var input = this.attached[cam];
  13425. if (input.checkInputs) {
  13426. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13427. }
  13428. }
  13429. };
  13430. CameraInputsManager.prototype.clear = function () {
  13431. if (this.attachedElement) {
  13432. this.detachElement(this.attachedElement);
  13433. }
  13434. this.attached = {};
  13435. this.attachedElement = null;
  13436. this.checkInputs = function () { };
  13437. };
  13438. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13439. var inputs = {};
  13440. for (var cam in this.attached) {
  13441. var input = this.attached[cam];
  13442. var res = BABYLON.SerializationHelper.Serialize(input);
  13443. inputs[input.getTypeName()] = res;
  13444. }
  13445. serializedCamera.inputsmgr = inputs;
  13446. };
  13447. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13448. var parsedInputs = parsedCamera.inputsmgr;
  13449. if (parsedInputs) {
  13450. this.clear();
  13451. for (var n in parsedInputs) {
  13452. var construct = BABYLON.CameraInputTypes[n];
  13453. if (construct) {
  13454. var parsedinput = parsedInputs[n];
  13455. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13456. this.add(input);
  13457. }
  13458. }
  13459. }
  13460. else {
  13461. //2016-03-08 this part is for managing backward compatibility
  13462. for (var n in this.attached) {
  13463. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13464. if (construct) {
  13465. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13466. this.remove(this.attached[n]);
  13467. this.add(input);
  13468. }
  13469. }
  13470. }
  13471. };
  13472. return CameraInputsManager;
  13473. }());
  13474. BABYLON.CameraInputsManager = CameraInputsManager;
  13475. })(BABYLON || (BABYLON = {}));
  13476. var BABYLON;
  13477. (function (BABYLON) {
  13478. var FreeCameraMouseInput = (function () {
  13479. function FreeCameraMouseInput(touchEnabled) {
  13480. if (touchEnabled === void 0) { touchEnabled = true; }
  13481. this.touchEnabled = touchEnabled;
  13482. this.angularSensibility = 2000.0;
  13483. }
  13484. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13485. var _this = this;
  13486. var engine = this.camera.getEngine();
  13487. if (!this._pointerInput) {
  13488. this._pointerInput = function (p, s) {
  13489. var evt = p.event;
  13490. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13491. return;
  13492. }
  13493. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13494. try {
  13495. evt.srcElement.setPointerCapture(evt.pointerId);
  13496. }
  13497. catch (e) {
  13498. }
  13499. _this.previousPosition = {
  13500. x: evt.clientX,
  13501. y: evt.clientY
  13502. };
  13503. if (!noPreventDefault) {
  13504. evt.preventDefault();
  13505. element.focus();
  13506. }
  13507. }
  13508. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13509. try {
  13510. evt.srcElement.releasePointerCapture(evt.pointerId);
  13511. }
  13512. catch (e) {
  13513. }
  13514. _this.previousPosition = null;
  13515. if (!noPreventDefault) {
  13516. evt.preventDefault();
  13517. }
  13518. }
  13519. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13520. if (!_this.previousPosition || engine.isPointerLock) {
  13521. return;
  13522. }
  13523. var offsetX = evt.clientX - _this.previousPosition.x;
  13524. var offsetY = evt.clientY - _this.previousPosition.y;
  13525. if (_this.camera.getScene().useRightHandedSystem) {
  13526. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13527. }
  13528. else {
  13529. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13530. }
  13531. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13532. _this.previousPosition = {
  13533. x: evt.clientX,
  13534. y: evt.clientY
  13535. };
  13536. if (!noPreventDefault) {
  13537. evt.preventDefault();
  13538. }
  13539. }
  13540. };
  13541. }
  13542. this._onMouseMove = function (evt) {
  13543. if (!engine.isPointerLock) {
  13544. return;
  13545. }
  13546. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13547. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13548. if (_this.camera.getScene().useRightHandedSystem) {
  13549. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13550. }
  13551. else {
  13552. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13553. }
  13554. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13555. _this.previousPosition = null;
  13556. if (!noPreventDefault) {
  13557. evt.preventDefault();
  13558. }
  13559. };
  13560. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13561. element.addEventListener("mousemove", this._onMouseMove, false);
  13562. };
  13563. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13564. if (this._observer && element) {
  13565. this.camera.getScene().onPointerObservable.remove(this._observer);
  13566. element.removeEventListener("mousemove", this._onMouseMove);
  13567. this._observer = null;
  13568. this._onMouseMove = null;
  13569. this.previousPosition = null;
  13570. }
  13571. };
  13572. FreeCameraMouseInput.prototype.getTypeName = function () {
  13573. return "FreeCameraMouseInput";
  13574. };
  13575. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13576. return "mouse";
  13577. };
  13578. __decorate([
  13579. BABYLON.serialize()
  13580. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13581. return FreeCameraMouseInput;
  13582. }());
  13583. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13584. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13585. })(BABYLON || (BABYLON = {}));
  13586. var BABYLON;
  13587. (function (BABYLON) {
  13588. var FreeCameraKeyboardMoveInput = (function () {
  13589. function FreeCameraKeyboardMoveInput() {
  13590. this._keys = [];
  13591. this.keysUp = [38];
  13592. this.keysDown = [40];
  13593. this.keysLeft = [37];
  13594. this.keysRight = [39];
  13595. }
  13596. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13597. var _this = this;
  13598. if (!this._onKeyDown) {
  13599. element.tabIndex = 1;
  13600. this._onKeyDown = function (evt) {
  13601. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13602. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13603. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13604. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13605. var index = _this._keys.indexOf(evt.keyCode);
  13606. if (index === -1) {
  13607. _this._keys.push(evt.keyCode);
  13608. }
  13609. if (!noPreventDefault) {
  13610. evt.preventDefault();
  13611. }
  13612. }
  13613. };
  13614. this._onKeyUp = function (evt) {
  13615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13619. var index = _this._keys.indexOf(evt.keyCode);
  13620. if (index >= 0) {
  13621. _this._keys.splice(index, 1);
  13622. }
  13623. if (!noPreventDefault) {
  13624. evt.preventDefault();
  13625. }
  13626. }
  13627. };
  13628. element.addEventListener("keydown", this._onKeyDown, false);
  13629. element.addEventListener("keyup", this._onKeyUp, false);
  13630. BABYLON.Tools.RegisterTopRootEvents([
  13631. { name: "blur", handler: this._onLostFocus }
  13632. ]);
  13633. }
  13634. };
  13635. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13636. if (this._onKeyDown) {
  13637. element.removeEventListener("keydown", this._onKeyDown);
  13638. element.removeEventListener("keyup", this._onKeyUp);
  13639. BABYLON.Tools.UnregisterTopRootEvents([
  13640. { name: "blur", handler: this._onLostFocus }
  13641. ]);
  13642. this._keys = [];
  13643. this._onKeyDown = null;
  13644. this._onKeyUp = null;
  13645. }
  13646. };
  13647. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13648. if (this._onKeyDown) {
  13649. var camera = this.camera;
  13650. // Keyboard
  13651. for (var index = 0; index < this._keys.length; index++) {
  13652. var keyCode = this._keys[index];
  13653. var speed = camera._computeLocalCameraSpeed();
  13654. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13655. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13656. }
  13657. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13658. camera._localDirection.copyFromFloats(0, 0, speed);
  13659. }
  13660. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13661. camera._localDirection.copyFromFloats(speed, 0, 0);
  13662. }
  13663. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13664. camera._localDirection.copyFromFloats(0, 0, -speed);
  13665. }
  13666. if (camera.getScene().useRightHandedSystem) {
  13667. camera._localDirection.z *= -1;
  13668. }
  13669. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13670. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13671. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13672. }
  13673. }
  13674. };
  13675. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13676. return "FreeCameraKeyboardMoveInput";
  13677. };
  13678. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13679. this._keys = [];
  13680. };
  13681. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13682. return "keyboard";
  13683. };
  13684. __decorate([
  13685. BABYLON.serialize()
  13686. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13687. __decorate([
  13688. BABYLON.serialize()
  13689. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13690. __decorate([
  13691. BABYLON.serialize()
  13692. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13693. __decorate([
  13694. BABYLON.serialize()
  13695. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13696. return FreeCameraKeyboardMoveInput;
  13697. }());
  13698. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13699. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13700. })(BABYLON || (BABYLON = {}));
  13701. var BABYLON;
  13702. (function (BABYLON) {
  13703. var FreeCameraTouchInput = (function () {
  13704. function FreeCameraTouchInput() {
  13705. this._offsetX = null;
  13706. this._offsetY = null;
  13707. this._pointerCount = 0;
  13708. this._pointerPressed = [];
  13709. this.touchAngularSensibility = 200000.0;
  13710. this.touchMoveSensibility = 250.0;
  13711. }
  13712. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13713. var _this = this;
  13714. var previousPosition;
  13715. if (this._pointerInput === undefined) {
  13716. this._onLostFocus = function (evt) {
  13717. _this._offsetX = null;
  13718. _this._offsetY = null;
  13719. };
  13720. this._pointerInput = function (p, s) {
  13721. var evt = p.event;
  13722. if (evt.pointerType === "mouse") {
  13723. return;
  13724. }
  13725. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13726. if (!noPreventDefault) {
  13727. evt.preventDefault();
  13728. }
  13729. _this._pointerPressed.push(evt.pointerId);
  13730. if (_this._pointerPressed.length !== 1) {
  13731. return;
  13732. }
  13733. previousPosition = {
  13734. x: evt.clientX,
  13735. y: evt.clientY
  13736. };
  13737. }
  13738. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13739. if (!noPreventDefault) {
  13740. evt.preventDefault();
  13741. }
  13742. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13743. if (index === -1) {
  13744. return;
  13745. }
  13746. _this._pointerPressed.splice(index, 1);
  13747. if (index != 0) {
  13748. return;
  13749. }
  13750. previousPosition = null;
  13751. _this._offsetX = null;
  13752. _this._offsetY = null;
  13753. }
  13754. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13755. if (!noPreventDefault) {
  13756. evt.preventDefault();
  13757. }
  13758. if (!previousPosition) {
  13759. return;
  13760. }
  13761. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13762. if (index != 0) {
  13763. return;
  13764. }
  13765. _this._offsetX = evt.clientX - previousPosition.x;
  13766. _this._offsetY = -(evt.clientY - previousPosition.y);
  13767. }
  13768. };
  13769. }
  13770. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13771. element.addEventListener("blur", this._onLostFocus);
  13772. };
  13773. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13774. if (this._pointerInput && element) {
  13775. this.camera.getScene().onPointerObservable.remove(this._observer);
  13776. this._observer = null;
  13777. element.removeEventListener("blur", this._onLostFocus);
  13778. this._onLostFocus = null;
  13779. this._pointerPressed = [];
  13780. this._offsetX = null;
  13781. this._offsetY = null;
  13782. this._pointerCount = 0;
  13783. }
  13784. };
  13785. FreeCameraTouchInput.prototype.checkInputs = function () {
  13786. if (this._offsetX) {
  13787. var camera = this.camera;
  13788. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13789. if (this._pointerPressed.length > 1) {
  13790. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13791. }
  13792. else {
  13793. var speed = camera._computeLocalCameraSpeed();
  13794. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13795. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13796. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13797. }
  13798. }
  13799. };
  13800. FreeCameraTouchInput.prototype.getTypeName = function () {
  13801. return "FreeCameraTouchInput";
  13802. };
  13803. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13804. return "touch";
  13805. };
  13806. __decorate([
  13807. BABYLON.serialize()
  13808. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13809. __decorate([
  13810. BABYLON.serialize()
  13811. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13812. return FreeCameraTouchInput;
  13813. }());
  13814. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13815. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13816. })(BABYLON || (BABYLON = {}));
  13817. var BABYLON;
  13818. (function (BABYLON) {
  13819. var FreeCameraDeviceOrientationInput = (function () {
  13820. function FreeCameraDeviceOrientationInput() {
  13821. var _this = this;
  13822. this._screenOrientationAngle = 0;
  13823. this._screenQuaternion = new BABYLON.Quaternion();
  13824. this._alpha = 0;
  13825. this._beta = 0;
  13826. this._gamma = 0;
  13827. this._orientationChanged = function () {
  13828. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13829. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13830. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13831. };
  13832. this._deviceOrientation = function (evt) {
  13833. _this._alpha = evt.alpha;
  13834. _this._beta = evt.beta;
  13835. _this._gamma = evt.gamma;
  13836. };
  13837. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13838. this._orientationChanged();
  13839. }
  13840. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13841. get: function () {
  13842. return this._camera;
  13843. },
  13844. set: function (camera) {
  13845. this._camera = camera;
  13846. if (!this._camera.rotationQuaternion)
  13847. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13848. },
  13849. enumerable: true,
  13850. configurable: true
  13851. });
  13852. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13853. window.addEventListener("orientationchange", this._orientationChanged);
  13854. window.addEventListener("deviceorientation", this._deviceOrientation);
  13855. //In certain cases, the attach control is called AFTER orientation was changed,
  13856. //So this is needed.
  13857. this._orientationChanged();
  13858. };
  13859. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13860. window.removeEventListener("orientationchange", this._orientationChanged);
  13861. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13862. };
  13863. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13864. //if no device orientation provided, don't update the rotation.
  13865. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13866. if (!this._alpha)
  13867. return;
  13868. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13869. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13870. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13871. //Mirror on XY Plane
  13872. this._camera.rotationQuaternion.z *= -1;
  13873. this._camera.rotationQuaternion.w *= -1;
  13874. };
  13875. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13876. return "FreeCameraDeviceOrientationInput";
  13877. };
  13878. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13879. return "deviceOrientation";
  13880. };
  13881. return FreeCameraDeviceOrientationInput;
  13882. }());
  13883. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13884. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13885. })(BABYLON || (BABYLON = {}));
  13886. var BABYLON;
  13887. (function (BABYLON) {
  13888. var FreeCameraGamepadInput = (function () {
  13889. function FreeCameraGamepadInput() {
  13890. this.gamepadAngularSensibility = 200;
  13891. this.gamepadMoveSensibility = 40;
  13892. }
  13893. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13894. var _this = this;
  13895. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13896. };
  13897. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13898. if (this._gamepads) {
  13899. this._gamepads.dispose();
  13900. }
  13901. this.gamepad = null;
  13902. };
  13903. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13904. if (this.gamepad) {
  13905. var camera = this.camera;
  13906. var LSValues = this.gamepad.leftStick;
  13907. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13908. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13909. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13910. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13911. var RSValues = this.gamepad.rightStick;
  13912. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13913. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13914. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13915. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13916. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13917. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13918. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13919. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13920. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13921. }
  13922. };
  13923. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13924. // Only the first gamepad can control the camera
  13925. if (gamepad.index === 0) {
  13926. this.gamepad = gamepad;
  13927. }
  13928. };
  13929. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13930. return "FreeCameraGamepadInput";
  13931. };
  13932. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13933. return "gamepad";
  13934. };
  13935. __decorate([
  13936. BABYLON.serialize()
  13937. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13938. __decorate([
  13939. BABYLON.serialize()
  13940. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13941. return FreeCameraGamepadInput;
  13942. }());
  13943. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13944. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13945. })(BABYLON || (BABYLON = {}));
  13946. var BABYLON;
  13947. (function (BABYLON) {
  13948. var ArcRotateCameraKeyboardMoveInput = (function () {
  13949. function ArcRotateCameraKeyboardMoveInput() {
  13950. this._keys = [];
  13951. this.keysUp = [38];
  13952. this.keysDown = [40];
  13953. this.keysLeft = [37];
  13954. this.keysRight = [39];
  13955. }
  13956. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13957. var _this = this;
  13958. element.tabIndex = 1;
  13959. this._onKeyDown = function (evt) {
  13960. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13961. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13962. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13963. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13964. var index = _this._keys.indexOf(evt.keyCode);
  13965. if (index === -1) {
  13966. _this._keys.push(evt.keyCode);
  13967. }
  13968. if (evt.preventDefault) {
  13969. if (!noPreventDefault) {
  13970. evt.preventDefault();
  13971. }
  13972. }
  13973. }
  13974. };
  13975. this._onKeyUp = function (evt) {
  13976. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13977. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13978. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13979. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13980. var index = _this._keys.indexOf(evt.keyCode);
  13981. if (index >= 0) {
  13982. _this._keys.splice(index, 1);
  13983. }
  13984. if (evt.preventDefault) {
  13985. if (!noPreventDefault) {
  13986. evt.preventDefault();
  13987. }
  13988. }
  13989. }
  13990. };
  13991. this._onLostFocus = function () {
  13992. _this._keys = [];
  13993. };
  13994. element.addEventListener("keydown", this._onKeyDown, false);
  13995. element.addEventListener("keyup", this._onKeyUp, false);
  13996. BABYLON.Tools.RegisterTopRootEvents([
  13997. { name: "blur", handler: this._onLostFocus }
  13998. ]);
  13999. };
  14000. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14001. if (element) {
  14002. element.removeEventListener("keydown", this._onKeyDown);
  14003. element.removeEventListener("keyup", this._onKeyUp);
  14004. }
  14005. BABYLON.Tools.UnregisterTopRootEvents([
  14006. { name: "blur", handler: this._onLostFocus }
  14007. ]);
  14008. this._keys = [];
  14009. this._onKeyDown = null;
  14010. this._onKeyUp = null;
  14011. this._onLostFocus = null;
  14012. };
  14013. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14014. if (this._onKeyDown) {
  14015. var camera = this.camera;
  14016. for (var index = 0; index < this._keys.length; index++) {
  14017. var keyCode = this._keys[index];
  14018. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14019. camera.inertialAlphaOffset -= 0.01;
  14020. }
  14021. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14022. camera.inertialBetaOffset -= 0.01;
  14023. }
  14024. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14025. camera.inertialAlphaOffset += 0.01;
  14026. }
  14027. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14028. camera.inertialBetaOffset += 0.01;
  14029. }
  14030. }
  14031. }
  14032. };
  14033. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14034. return "ArcRotateCameraKeyboardMoveInput";
  14035. };
  14036. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14037. return "keyboard";
  14038. };
  14039. __decorate([
  14040. BABYLON.serialize()
  14041. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14042. __decorate([
  14043. BABYLON.serialize()
  14044. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14045. __decorate([
  14046. BABYLON.serialize()
  14047. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14048. __decorate([
  14049. BABYLON.serialize()
  14050. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14051. return ArcRotateCameraKeyboardMoveInput;
  14052. }());
  14053. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14054. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14055. })(BABYLON || (BABYLON = {}));
  14056. var BABYLON;
  14057. (function (BABYLON) {
  14058. var ArcRotateCameraMouseWheelInput = (function () {
  14059. function ArcRotateCameraMouseWheelInput() {
  14060. this.wheelPrecision = 3.0;
  14061. }
  14062. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14063. var _this = this;
  14064. this._wheel = function (p, s) {
  14065. //sanity check - this should be a PointerWheel event.
  14066. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14067. return;
  14068. var event = p.event;
  14069. var delta = 0;
  14070. if (event.wheelDelta) {
  14071. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14072. }
  14073. else if (event.detail) {
  14074. delta = -event.detail / _this.wheelPrecision;
  14075. }
  14076. if (delta)
  14077. _this.camera.inertialRadiusOffset += delta;
  14078. if (event.preventDefault) {
  14079. if (!noPreventDefault) {
  14080. event.preventDefault();
  14081. }
  14082. }
  14083. };
  14084. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14085. };
  14086. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14087. if (this._observer && element) {
  14088. this.camera.getScene().onPointerObservable.remove(this._observer);
  14089. this._observer = null;
  14090. this._wheel = null;
  14091. }
  14092. };
  14093. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14094. return "ArcRotateCameraMouseWheelInput";
  14095. };
  14096. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14097. return "mousewheel";
  14098. };
  14099. __decorate([
  14100. BABYLON.serialize()
  14101. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14102. return ArcRotateCameraMouseWheelInput;
  14103. }());
  14104. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14105. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14106. })(BABYLON || (BABYLON = {}));
  14107. var BABYLON;
  14108. (function (BABYLON) {
  14109. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14110. var ArcRotateCameraPointersInput = (function () {
  14111. function ArcRotateCameraPointersInput() {
  14112. this.angularSensibilityX = 1000.0;
  14113. this.angularSensibilityY = 1000.0;
  14114. this.pinchPrecision = 6.0;
  14115. this.panningSensibility = 50.0;
  14116. this._isPanClick = false;
  14117. this.pinchInwards = true;
  14118. }
  14119. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14120. var _this = this;
  14121. var engine = this.camera.getEngine();
  14122. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14123. var pointA, pointB;
  14124. var previousPinchDistance = 0;
  14125. this._pointerInput = function (p, s) {
  14126. var evt = p.event;
  14127. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14128. try {
  14129. evt.srcElement.setPointerCapture(evt.pointerId);
  14130. }
  14131. catch (e) {
  14132. }
  14133. // Manage panning with pan button click
  14134. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14135. // manage pointers
  14136. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14137. if (pointA === undefined) {
  14138. pointA = cacheSoloPointer;
  14139. }
  14140. else if (pointB === undefined) {
  14141. pointB = cacheSoloPointer;
  14142. }
  14143. if (!noPreventDefault) {
  14144. evt.preventDefault();
  14145. element.focus();
  14146. }
  14147. }
  14148. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14149. try {
  14150. evt.srcElement.releasePointerCapture(evt.pointerId);
  14151. }
  14152. catch (e) {
  14153. }
  14154. cacheSoloPointer = null;
  14155. previousPinchDistance = 0;
  14156. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14157. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14158. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14159. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14160. pointA = pointB = undefined;
  14161. if (!noPreventDefault) {
  14162. evt.preventDefault();
  14163. }
  14164. }
  14165. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14166. if (!noPreventDefault) {
  14167. evt.preventDefault();
  14168. }
  14169. // One button down
  14170. if (pointA && pointB === undefined) {
  14171. if (_this.panningSensibility !== 0 &&
  14172. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14173. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14174. _this.camera
  14175. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14176. _this.camera
  14177. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14178. }
  14179. else {
  14180. var offsetX = evt.clientX - cacheSoloPointer.x;
  14181. var offsetY = evt.clientY - cacheSoloPointer.y;
  14182. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14183. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14184. }
  14185. cacheSoloPointer.x = evt.clientX;
  14186. cacheSoloPointer.y = evt.clientY;
  14187. }
  14188. else if (pointA && pointB) {
  14189. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14190. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14191. ed.x = evt.clientX;
  14192. ed.y = evt.clientY;
  14193. var direction = _this.pinchInwards ? 1 : -1;
  14194. var distX = pointA.x - pointB.x;
  14195. var distY = pointA.y - pointB.y;
  14196. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14197. if (previousPinchDistance === 0) {
  14198. previousPinchDistance = pinchSquaredDistance;
  14199. return;
  14200. }
  14201. if (pinchSquaredDistance !== previousPinchDistance) {
  14202. _this.camera
  14203. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14204. (_this.pinchPrecision *
  14205. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14206. direction);
  14207. previousPinchDistance = pinchSquaredDistance;
  14208. }
  14209. }
  14210. }
  14211. };
  14212. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14213. this._onContextMenu = function (evt) {
  14214. evt.preventDefault();
  14215. };
  14216. if (!this.camera._useCtrlForPanning) {
  14217. element.addEventListener("contextmenu", this._onContextMenu, false);
  14218. }
  14219. this._onLostFocus = function () {
  14220. //this._keys = [];
  14221. pointA = pointB = undefined;
  14222. previousPinchDistance = 0;
  14223. cacheSoloPointer = null;
  14224. };
  14225. this._onMouseMove = function (evt) {
  14226. if (!engine.isPointerLock) {
  14227. return;
  14228. }
  14229. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14230. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14231. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14232. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14233. if (!noPreventDefault) {
  14234. evt.preventDefault();
  14235. }
  14236. };
  14237. this._onGestureStart = function (e) {
  14238. if (window.MSGesture === undefined) {
  14239. return;
  14240. }
  14241. if (!_this._MSGestureHandler) {
  14242. _this._MSGestureHandler = new MSGesture();
  14243. _this._MSGestureHandler.target = element;
  14244. }
  14245. _this._MSGestureHandler.addPointer(e.pointerId);
  14246. };
  14247. this._onGesture = function (e) {
  14248. _this.camera.radius *= e.scale;
  14249. if (e.preventDefault) {
  14250. if (!noPreventDefault) {
  14251. e.stopPropagation();
  14252. e.preventDefault();
  14253. }
  14254. }
  14255. };
  14256. element.addEventListener("mousemove", this._onMouseMove, false);
  14257. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14258. element.addEventListener("MSGestureChange", this._onGesture, false);
  14259. element.addEventListener("keydown", this._onKeyDown, false);
  14260. element.addEventListener("keyup", this._onKeyUp, false);
  14261. BABYLON.Tools.RegisterTopRootEvents([
  14262. { name: "blur", handler: this._onLostFocus }
  14263. ]);
  14264. };
  14265. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14266. if (element && this._observer) {
  14267. this.camera.getScene().onPointerObservable.remove(this._observer);
  14268. this._observer = null;
  14269. element.removeEventListener("contextmenu", this._onContextMenu);
  14270. element.removeEventListener("mousemove", this._onMouseMove);
  14271. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14272. element.removeEventListener("MSGestureChange", this._onGesture);
  14273. element.removeEventListener("keydown", this._onKeyDown);
  14274. element.removeEventListener("keyup", this._onKeyUp);
  14275. this._isPanClick = false;
  14276. this.pinchInwards = true;
  14277. this._onKeyDown = null;
  14278. this._onKeyUp = null;
  14279. this._onMouseMove = null;
  14280. this._onGestureStart = null;
  14281. this._onGesture = null;
  14282. this._MSGestureHandler = null;
  14283. this._onLostFocus = null;
  14284. this._onContextMenu = null;
  14285. }
  14286. BABYLON.Tools.UnregisterTopRootEvents([
  14287. { name: "blur", handler: this._onLostFocus }
  14288. ]);
  14289. };
  14290. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14291. return "ArcRotateCameraPointersInput";
  14292. };
  14293. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14294. return "pointers";
  14295. };
  14296. __decorate([
  14297. BABYLON.serialize()
  14298. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14299. __decorate([
  14300. BABYLON.serialize()
  14301. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14302. __decorate([
  14303. BABYLON.serialize()
  14304. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14305. __decorate([
  14306. BABYLON.serialize()
  14307. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14308. return ArcRotateCameraPointersInput;
  14309. }());
  14310. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14311. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14312. })(BABYLON || (BABYLON = {}));
  14313. var BABYLON;
  14314. (function (BABYLON) {
  14315. var ArcRotateCameraGamepadInput = (function () {
  14316. function ArcRotateCameraGamepadInput() {
  14317. this.gamepadRotationSensibility = 80;
  14318. this.gamepadMoveSensibility = 40;
  14319. }
  14320. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14321. var _this = this;
  14322. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14323. };
  14324. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14325. if (this._gamepads) {
  14326. this._gamepads.dispose();
  14327. }
  14328. this.gamepad = null;
  14329. };
  14330. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14331. if (this.gamepad) {
  14332. var camera = this.camera;
  14333. var RSValues = this.gamepad.rightStick;
  14334. if (RSValues.x != 0) {
  14335. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14336. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14337. camera.inertialAlphaOffset += normalizedRX;
  14338. }
  14339. }
  14340. if (RSValues.y != 0) {
  14341. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14342. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14343. camera.inertialBetaOffset += normalizedRY;
  14344. }
  14345. }
  14346. var LSValues = this.gamepad.leftStick;
  14347. if (LSValues.y != 0) {
  14348. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14349. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14350. this.camera.inertialRadiusOffset -= normalizedLY;
  14351. }
  14352. }
  14353. }
  14354. };
  14355. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14356. // Only the first gamepad can control the camera
  14357. if (gamepad.index === 0) {
  14358. this.gamepad = gamepad;
  14359. }
  14360. };
  14361. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14362. return "ArcRotateCameraGamepadInput";
  14363. };
  14364. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14365. return "gamepad";
  14366. };
  14367. __decorate([
  14368. BABYLON.serialize()
  14369. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14370. __decorate([
  14371. BABYLON.serialize()
  14372. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14373. return ArcRotateCameraGamepadInput;
  14374. }());
  14375. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14376. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14377. })(BABYLON || (BABYLON = {}));
  14378. var BABYLON;
  14379. (function (BABYLON) {
  14380. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14381. function ArcRotateCameraVRDeviceOrientationInput() {
  14382. this.alphaCorrection = 1;
  14383. this.betaCorrection = 1;
  14384. this.gammaCorrection = 1;
  14385. this._alpha = 0;
  14386. this._beta = 0;
  14387. this._gamma = 0;
  14388. this._dirty = false;
  14389. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14390. }
  14391. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14392. this.camera.attachControl(element, noPreventDefault);
  14393. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14394. };
  14395. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14396. var camera = this.camera;
  14397. this._alpha = +evt.alpha | 0;
  14398. this._beta = +evt.beta | 0;
  14399. this._gamma = +evt.gamma | 0;
  14400. this._dirty = true;
  14401. };
  14402. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14403. if (this._dirty) {
  14404. this._dirty = false;
  14405. if (this._gamma < 0) {
  14406. this._gamma = 180 + this._gamma;
  14407. }
  14408. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14409. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14410. }
  14411. };
  14412. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14413. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14414. };
  14415. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14416. return "ArcRotateCameraVRDeviceOrientationInput";
  14417. };
  14418. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14419. return "VRDeviceOrientation";
  14420. };
  14421. return ArcRotateCameraVRDeviceOrientationInput;
  14422. }());
  14423. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14424. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14425. })(BABYLON || (BABYLON = {}));
  14426. var BABYLON;
  14427. (function (BABYLON) {
  14428. var TargetCamera = (function (_super) {
  14429. __extends(TargetCamera, _super);
  14430. function TargetCamera(name, position, scene) {
  14431. _super.call(this, name, position, scene);
  14432. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14433. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14434. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14435. this.speed = 2.0;
  14436. this.noRotationConstraint = false;
  14437. this.lockedTarget = null;
  14438. this._currentTarget = BABYLON.Vector3.Zero();
  14439. this._viewMatrix = BABYLON.Matrix.Zero();
  14440. this._camMatrix = BABYLON.Matrix.Zero();
  14441. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14442. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14443. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14444. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14445. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14446. this._lookAtTemp = BABYLON.Matrix.Zero();
  14447. this._tempMatrix = BABYLON.Matrix.Zero();
  14448. }
  14449. TargetCamera.prototype.getFrontPosition = function (distance) {
  14450. var direction = this.getTarget().subtract(this.position);
  14451. direction.normalize();
  14452. direction.scaleInPlace(distance);
  14453. return this.globalPosition.add(direction);
  14454. };
  14455. TargetCamera.prototype._getLockedTargetPosition = function () {
  14456. if (!this.lockedTarget) {
  14457. return null;
  14458. }
  14459. return this.lockedTarget.position || this.lockedTarget;
  14460. };
  14461. // Cache
  14462. TargetCamera.prototype._initCache = function () {
  14463. _super.prototype._initCache.call(this);
  14464. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14465. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14466. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14467. };
  14468. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14469. if (!ignoreParentClass) {
  14470. _super.prototype._updateCache.call(this);
  14471. }
  14472. var lockedTargetPosition = this._getLockedTargetPosition();
  14473. if (!lockedTargetPosition) {
  14474. this._cache.lockedTarget = null;
  14475. }
  14476. else {
  14477. if (!this._cache.lockedTarget) {
  14478. this._cache.lockedTarget = lockedTargetPosition.clone();
  14479. }
  14480. else {
  14481. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14482. }
  14483. }
  14484. this._cache.rotation.copyFrom(this.rotation);
  14485. if (this.rotationQuaternion)
  14486. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14487. };
  14488. // Synchronized
  14489. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14490. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14491. return false;
  14492. }
  14493. var lockedTargetPosition = this._getLockedTargetPosition();
  14494. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14495. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14496. };
  14497. // Methods
  14498. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14499. var engine = this.getEngine();
  14500. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14501. };
  14502. // Target
  14503. TargetCamera.prototype.setTarget = function (target) {
  14504. this.upVector.normalize();
  14505. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14506. this._camMatrix.invert();
  14507. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14508. var vDir = target.subtract(this.position);
  14509. if (vDir.x >= 0.0) {
  14510. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14511. }
  14512. else {
  14513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14514. }
  14515. this.rotation.z = 0;
  14516. if (isNaN(this.rotation.x)) {
  14517. this.rotation.x = 0;
  14518. }
  14519. if (isNaN(this.rotation.y)) {
  14520. this.rotation.y = 0;
  14521. }
  14522. if (isNaN(this.rotation.z)) {
  14523. this.rotation.z = 0;
  14524. }
  14525. if (this.rotationQuaternion) {
  14526. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14527. }
  14528. };
  14529. TargetCamera.prototype.getTarget = function () {
  14530. return this._currentTarget;
  14531. };
  14532. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14533. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14534. };
  14535. TargetCamera.prototype._updatePosition = function () {
  14536. this.position.addInPlace(this.cameraDirection);
  14537. };
  14538. TargetCamera.prototype._checkInputs = function () {
  14539. var needToMove = this._decideIfNeedsToMove();
  14540. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14541. // Move
  14542. if (needToMove) {
  14543. this._updatePosition();
  14544. }
  14545. // Rotate
  14546. if (needToRotate) {
  14547. this.rotation.x += this.cameraRotation.x;
  14548. this.rotation.y += this.cameraRotation.y;
  14549. if (!this.noRotationConstraint) {
  14550. var limit = (Math.PI / 2) * 0.95;
  14551. if (this.rotation.x > limit)
  14552. this.rotation.x = limit;
  14553. if (this.rotation.x < -limit)
  14554. this.rotation.x = -limit;
  14555. }
  14556. }
  14557. // Inertia
  14558. if (needToMove) {
  14559. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14560. this.cameraDirection.x = 0;
  14561. }
  14562. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14563. this.cameraDirection.y = 0;
  14564. }
  14565. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14566. this.cameraDirection.z = 0;
  14567. }
  14568. this.cameraDirection.scaleInPlace(this.inertia);
  14569. }
  14570. if (needToRotate) {
  14571. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14572. this.cameraRotation.x = 0;
  14573. }
  14574. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14575. this.cameraRotation.y = 0;
  14576. }
  14577. this.cameraRotation.scaleInPlace(this.inertia);
  14578. }
  14579. _super.prototype._checkInputs.call(this);
  14580. };
  14581. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14582. if (this.rotationQuaternion) {
  14583. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14584. //update the up vector!
  14585. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14586. }
  14587. else {
  14588. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14589. }
  14590. };
  14591. TargetCamera.prototype._getViewMatrix = function () {
  14592. if (!this.lockedTarget) {
  14593. // Compute
  14594. this._updateCameraRotationMatrix();
  14595. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14596. // Computing target and final matrix
  14597. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14598. }
  14599. else {
  14600. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14601. }
  14602. if (this.getScene().useRightHandedSystem) {
  14603. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14604. }
  14605. else {
  14606. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14607. }
  14608. return this._viewMatrix;
  14609. };
  14610. /**
  14611. * @override
  14612. * Override Camera.createRigCamera
  14613. */
  14614. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14615. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14616. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14617. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14618. if (!this.rotationQuaternion) {
  14619. this.rotationQuaternion = new BABYLON.Quaternion();
  14620. }
  14621. rigCamera._cameraRigParams = {};
  14622. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14623. }
  14624. return rigCamera;
  14625. }
  14626. return null;
  14627. };
  14628. /**
  14629. * @override
  14630. * Override Camera._updateRigCameras
  14631. */
  14632. TargetCamera.prototype._updateRigCameras = function () {
  14633. var camLeft = this._rigCameras[0];
  14634. var camRight = this._rigCameras[1];
  14635. switch (this.cameraRigMode) {
  14636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14640. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14641. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14642. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14643. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14644. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14645. camLeft.setTarget(this.getTarget());
  14646. camRight.setTarget(this.getTarget());
  14647. break;
  14648. case BABYLON.Camera.RIG_MODE_VR:
  14649. case BABYLON.Camera.RIG_MODE_WEBVR:
  14650. if (camLeft.rotationQuaternion) {
  14651. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14652. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14653. }
  14654. else {
  14655. camLeft.rotation.copyFrom(this.rotation);
  14656. camRight.rotation.copyFrom(this.rotation);
  14657. }
  14658. camLeft.position.copyFrom(this.position);
  14659. camRight.position.copyFrom(this.position);
  14660. break;
  14661. }
  14662. _super.prototype._updateRigCameras.call(this);
  14663. };
  14664. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14665. if (!this._rigCamTransformMatrix) {
  14666. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14667. }
  14668. var target = this.getTarget();
  14669. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14670. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14671. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14672. };
  14673. TargetCamera.prototype.getTypeName = function () {
  14674. return "TargetCamera";
  14675. };
  14676. __decorate([
  14677. BABYLON.serializeAsVector3()
  14678. ], TargetCamera.prototype, "rotation", void 0);
  14679. __decorate([
  14680. BABYLON.serialize()
  14681. ], TargetCamera.prototype, "speed", void 0);
  14682. __decorate([
  14683. BABYLON.serializeAsMeshReference("lockedTargetId")
  14684. ], TargetCamera.prototype, "lockedTarget", void 0);
  14685. return TargetCamera;
  14686. }(BABYLON.Camera));
  14687. BABYLON.TargetCamera = TargetCamera;
  14688. })(BABYLON || (BABYLON = {}));
  14689. var BABYLON;
  14690. (function (BABYLON) {
  14691. var FreeCamera = (function (_super) {
  14692. __extends(FreeCamera, _super);
  14693. function FreeCamera(name, position, scene) {
  14694. var _this = this;
  14695. _super.call(this, name, position, scene);
  14696. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14697. this.checkCollisions = false;
  14698. this.applyGravity = false;
  14699. this._collider = new BABYLON.Collider();
  14700. this._needMoveForGravity = false;
  14701. this._oldPosition = BABYLON.Vector3.Zero();
  14702. this._diffPosition = BABYLON.Vector3.Zero();
  14703. this._newPosition = BABYLON.Vector3.Zero();
  14704. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14705. if (collidedMesh === void 0) { collidedMesh = null; }
  14706. //TODO move this to the collision coordinator!
  14707. if (_this.getScene().workerCollisions)
  14708. newPosition.multiplyInPlace(_this._collider.radius);
  14709. var updatePosition = function (newPos) {
  14710. _this._newPosition.copyFrom(newPos);
  14711. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14712. var oldPosition = _this.position.clone();
  14713. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14714. _this.position.addInPlace(_this._diffPosition);
  14715. if (_this.onCollide && collidedMesh) {
  14716. _this.onCollide(collidedMesh);
  14717. }
  14718. }
  14719. };
  14720. updatePosition(newPosition);
  14721. };
  14722. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14723. this.inputs.addKeyboard().addMouse();
  14724. }
  14725. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14726. //-- begin properties for backward compatibility for inputs
  14727. get: function () {
  14728. var mouse = this.inputs.attached["mouse"];
  14729. if (mouse)
  14730. return mouse.angularSensibility;
  14731. },
  14732. set: function (value) {
  14733. var mouse = this.inputs.attached["mouse"];
  14734. if (mouse)
  14735. mouse.angularSensibility = value;
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14741. get: function () {
  14742. var keyboard = this.inputs.attached["keyboard"];
  14743. if (keyboard)
  14744. return keyboard.keysUp;
  14745. },
  14746. set: function (value) {
  14747. var keyboard = this.inputs.attached["keyboard"];
  14748. if (keyboard)
  14749. keyboard.keysUp = value;
  14750. },
  14751. enumerable: true,
  14752. configurable: true
  14753. });
  14754. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14755. get: function () {
  14756. var keyboard = this.inputs.attached["keyboard"];
  14757. if (keyboard)
  14758. return keyboard.keysDown;
  14759. },
  14760. set: function (value) {
  14761. var keyboard = this.inputs.attached["keyboard"];
  14762. if (keyboard)
  14763. keyboard.keysDown = value;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14769. get: function () {
  14770. var keyboard = this.inputs.attached["keyboard"];
  14771. if (keyboard)
  14772. return keyboard.keysLeft;
  14773. },
  14774. set: function (value) {
  14775. var keyboard = this.inputs.attached["keyboard"];
  14776. if (keyboard)
  14777. keyboard.keysLeft = value;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14783. get: function () {
  14784. var keyboard = this.inputs.attached["keyboard"];
  14785. if (keyboard)
  14786. return keyboard.keysRight;
  14787. },
  14788. set: function (value) {
  14789. var keyboard = this.inputs.attached["keyboard"];
  14790. if (keyboard)
  14791. keyboard.keysRight = value;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. // Controls
  14797. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14798. this.inputs.attachElement(element, noPreventDefault);
  14799. };
  14800. FreeCamera.prototype.detachControl = function (element) {
  14801. this.inputs.detachElement(element);
  14802. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14803. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14804. };
  14805. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14806. var globalPosition;
  14807. if (this.parent) {
  14808. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14809. }
  14810. else {
  14811. globalPosition = this.position;
  14812. }
  14813. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14814. this._collider.radius = this.ellipsoid;
  14815. //no need for clone, as long as gravity is not on.
  14816. var actualVelocity = velocity;
  14817. //add gravity to the velocity to prevent the dual-collision checking
  14818. if (this.applyGravity) {
  14819. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14820. actualVelocity = velocity.add(this.getScene().gravity);
  14821. }
  14822. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14823. };
  14824. FreeCamera.prototype._checkInputs = function () {
  14825. if (!this._localDirection) {
  14826. this._localDirection = BABYLON.Vector3.Zero();
  14827. this._transformedDirection = BABYLON.Vector3.Zero();
  14828. }
  14829. this.inputs.checkInputs();
  14830. _super.prototype._checkInputs.call(this);
  14831. };
  14832. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14833. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14834. };
  14835. FreeCamera.prototype._updatePosition = function () {
  14836. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14837. this._collideWithWorld(this.cameraDirection);
  14838. }
  14839. else {
  14840. this.position.addInPlace(this.cameraDirection);
  14841. }
  14842. };
  14843. FreeCamera.prototype.dispose = function () {
  14844. this.inputs.clear();
  14845. _super.prototype.dispose.call(this);
  14846. };
  14847. FreeCamera.prototype.getTypeName = function () {
  14848. return "FreeCamera";
  14849. };
  14850. __decorate([
  14851. BABYLON.serializeAsVector3()
  14852. ], FreeCamera.prototype, "ellipsoid", void 0);
  14853. __decorate([
  14854. BABYLON.serialize()
  14855. ], FreeCamera.prototype, "checkCollisions", void 0);
  14856. __decorate([
  14857. BABYLON.serialize()
  14858. ], FreeCamera.prototype, "applyGravity", void 0);
  14859. return FreeCamera;
  14860. }(BABYLON.TargetCamera));
  14861. BABYLON.FreeCamera = FreeCamera;
  14862. })(BABYLON || (BABYLON = {}));
  14863. var BABYLON;
  14864. (function (BABYLON) {
  14865. var FreeCameraInputsManager = (function (_super) {
  14866. __extends(FreeCameraInputsManager, _super);
  14867. function FreeCameraInputsManager(camera) {
  14868. _super.call(this, camera);
  14869. }
  14870. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14871. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14872. return this;
  14873. };
  14874. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14875. if (touchEnabled === void 0) { touchEnabled = true; }
  14876. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14877. return this;
  14878. };
  14879. FreeCameraInputsManager.prototype.addGamepad = function () {
  14880. this.add(new BABYLON.FreeCameraGamepadInput());
  14881. return this;
  14882. };
  14883. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14884. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14885. return this;
  14886. };
  14887. FreeCameraInputsManager.prototype.addTouch = function () {
  14888. this.add(new BABYLON.FreeCameraTouchInput());
  14889. return this;
  14890. };
  14891. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14892. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14893. return this;
  14894. };
  14895. return FreeCameraInputsManager;
  14896. }(BABYLON.CameraInputsManager));
  14897. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14898. })(BABYLON || (BABYLON = {}));
  14899. var BABYLON;
  14900. (function (BABYLON) {
  14901. var FollowCamera = (function (_super) {
  14902. __extends(FollowCamera, _super);
  14903. function FollowCamera(name, position, scene, target) {
  14904. _super.call(this, name, position, scene);
  14905. this.radius = 12;
  14906. this.rotationOffset = 0;
  14907. this.heightOffset = 4;
  14908. this.cameraAcceleration = 0.05;
  14909. this.maxCameraSpeed = 20;
  14910. this.target = target;
  14911. }
  14912. FollowCamera.prototype.getRadians = function (degrees) {
  14913. return degrees * Math.PI / 180;
  14914. };
  14915. FollowCamera.prototype.follow = function (cameraTarget) {
  14916. if (!cameraTarget)
  14917. return;
  14918. var yRotation;
  14919. if (cameraTarget.rotationQuaternion) {
  14920. var rotMatrix = new BABYLON.Matrix();
  14921. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14922. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14923. }
  14924. else {
  14925. yRotation = cameraTarget.rotation.y;
  14926. }
  14927. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14928. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14929. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14930. var dx = targetX - this.position.x;
  14931. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14932. var dz = (targetZ) - this.position.z;
  14933. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14934. var vy = dy * this.cameraAcceleration;
  14935. var vz = dz * this.cameraAcceleration * 2;
  14936. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14937. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14938. }
  14939. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14940. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14941. }
  14942. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14943. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14944. }
  14945. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14946. this.setTarget(cameraTarget.position);
  14947. };
  14948. FollowCamera.prototype._checkInputs = function () {
  14949. _super.prototype._checkInputs.call(this);
  14950. this.follow(this.target);
  14951. };
  14952. FollowCamera.prototype.getTypeName = function () {
  14953. return "FollowCamera";
  14954. };
  14955. __decorate([
  14956. BABYLON.serialize()
  14957. ], FollowCamera.prototype, "radius", void 0);
  14958. __decorate([
  14959. BABYLON.serialize()
  14960. ], FollowCamera.prototype, "rotationOffset", void 0);
  14961. __decorate([
  14962. BABYLON.serialize()
  14963. ], FollowCamera.prototype, "heightOffset", void 0);
  14964. __decorate([
  14965. BABYLON.serialize()
  14966. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14967. __decorate([
  14968. BABYLON.serialize()
  14969. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14970. __decorate([
  14971. BABYLON.serializeAsMeshReference("lockedTargetId")
  14972. ], FollowCamera.prototype, "target", void 0);
  14973. return FollowCamera;
  14974. }(BABYLON.TargetCamera));
  14975. BABYLON.FollowCamera = FollowCamera;
  14976. var ArcFollowCamera = (function (_super) {
  14977. __extends(ArcFollowCamera, _super);
  14978. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14979. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14980. this.alpha = alpha;
  14981. this.beta = beta;
  14982. this.radius = radius;
  14983. this.target = target;
  14984. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14985. this.follow();
  14986. }
  14987. ArcFollowCamera.prototype.follow = function () {
  14988. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14989. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14990. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14991. this.position = this.target.position.add(this._cartesianCoordinates);
  14992. this.setTarget(this.target.position);
  14993. };
  14994. ArcFollowCamera.prototype._checkInputs = function () {
  14995. _super.prototype._checkInputs.call(this);
  14996. this.follow();
  14997. };
  14998. ArcFollowCamera.prototype.getTypeName = function () {
  14999. return "ArcFollowCamera";
  15000. };
  15001. return ArcFollowCamera;
  15002. }(BABYLON.TargetCamera));
  15003. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15004. })(BABYLON || (BABYLON = {}));
  15005. var BABYLON;
  15006. (function (BABYLON) {
  15007. // We're mainly based on the logic defined into the FreeCamera code
  15008. var TouchCamera = (function (_super) {
  15009. __extends(TouchCamera, _super);
  15010. //-- end properties for backward compatibility for inputs
  15011. function TouchCamera(name, position, scene) {
  15012. _super.call(this, name, position, scene);
  15013. this.inputs.addTouch();
  15014. this._setupInputs();
  15015. }
  15016. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15017. //-- Begin properties for backward compatibility for inputs
  15018. get: function () {
  15019. var touch = this.inputs.attached["touch"];
  15020. if (touch)
  15021. return touch.touchAngularSensibility;
  15022. },
  15023. set: function (value) {
  15024. var touch = this.inputs.attached["touch"];
  15025. if (touch)
  15026. touch.touchAngularSensibility = value;
  15027. },
  15028. enumerable: true,
  15029. configurable: true
  15030. });
  15031. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15032. get: function () {
  15033. var touch = this.inputs.attached["touch"];
  15034. if (touch)
  15035. return touch.touchMoveSensibility;
  15036. },
  15037. set: function (value) {
  15038. var touch = this.inputs.attached["touch"];
  15039. if (touch)
  15040. touch.touchMoveSensibility = value;
  15041. },
  15042. enumerable: true,
  15043. configurable: true
  15044. });
  15045. TouchCamera.prototype.getTypeName = function () {
  15046. return "TouchCamera";
  15047. };
  15048. TouchCamera.prototype._setupInputs = function () {
  15049. var mouse = this.inputs.attached["mouse"];
  15050. if (mouse) {
  15051. mouse.touchEnabled = false;
  15052. }
  15053. };
  15054. return TouchCamera;
  15055. }(BABYLON.FreeCamera));
  15056. BABYLON.TouchCamera = TouchCamera;
  15057. })(BABYLON || (BABYLON = {}));
  15058. var BABYLON;
  15059. (function (BABYLON) {
  15060. var ArcRotateCamera = (function (_super) {
  15061. __extends(ArcRotateCamera, _super);
  15062. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15063. var _this = this;
  15064. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15065. this.inertialAlphaOffset = 0;
  15066. this.inertialBetaOffset = 0;
  15067. this.inertialRadiusOffset = 0;
  15068. this.lowerAlphaLimit = null;
  15069. this.upperAlphaLimit = null;
  15070. this.lowerBetaLimit = 0.01;
  15071. this.upperBetaLimit = Math.PI;
  15072. this.lowerRadiusLimit = null;
  15073. this.upperRadiusLimit = null;
  15074. this.inertialPanningX = 0;
  15075. this.inertialPanningY = 0;
  15076. //-- end properties for backward compatibility for inputs
  15077. this.zoomOnFactor = 1;
  15078. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15079. this.allowUpsideDown = true;
  15080. this._viewMatrix = new BABYLON.Matrix();
  15081. // Panning
  15082. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15083. this.checkCollisions = false;
  15084. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15085. this._collider = new BABYLON.Collider();
  15086. this._previousPosition = BABYLON.Vector3.Zero();
  15087. this._collisionVelocity = BABYLON.Vector3.Zero();
  15088. this._newPosition = BABYLON.Vector3.Zero();
  15089. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15090. if (collidedMesh === void 0) { collidedMesh = null; }
  15091. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15092. newPosition.multiplyInPlace(_this._collider.radius);
  15093. }
  15094. if (!collidedMesh) {
  15095. _this._previousPosition.copyFrom(_this.position);
  15096. }
  15097. else {
  15098. _this.setPosition(newPosition);
  15099. if (_this.onCollide) {
  15100. _this.onCollide(collidedMesh);
  15101. }
  15102. }
  15103. // Recompute because of constraints
  15104. var cosa = Math.cos(_this.alpha);
  15105. var sina = Math.sin(_this.alpha);
  15106. var cosb = Math.cos(_this.beta);
  15107. var sinb = Math.sin(_this.beta);
  15108. if (sinb === 0) {
  15109. sinb = 0.0001;
  15110. }
  15111. var target = _this._getTargetPosition();
  15112. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15113. _this.position.copyFrom(_this._newPosition);
  15114. var up = _this.upVector;
  15115. if (_this.allowUpsideDown && _this.beta < 0) {
  15116. up = up.clone();
  15117. up = up.negate();
  15118. }
  15119. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15120. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15121. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15122. _this._collisionTriggered = false;
  15123. };
  15124. if (!target) {
  15125. this.target = BABYLON.Vector3.Zero();
  15126. }
  15127. else {
  15128. this.target = target;
  15129. }
  15130. this.alpha = alpha;
  15131. this.beta = beta;
  15132. this.radius = radius;
  15133. this.getViewMatrix();
  15134. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15135. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15136. }
  15137. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15138. //-- begin properties for backward compatibility for inputs
  15139. get: function () {
  15140. var pointers = this.inputs.attached["pointers"];
  15141. if (pointers)
  15142. return pointers.angularSensibilityX;
  15143. },
  15144. set: function (value) {
  15145. var pointers = this.inputs.attached["pointers"];
  15146. if (pointers) {
  15147. pointers.angularSensibilityX = value;
  15148. }
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15154. get: function () {
  15155. var pointers = this.inputs.attached["pointers"];
  15156. if (pointers)
  15157. return pointers.angularSensibilityY;
  15158. },
  15159. set: function (value) {
  15160. var pointers = this.inputs.attached["pointers"];
  15161. if (pointers) {
  15162. pointers.angularSensibilityY = value;
  15163. }
  15164. },
  15165. enumerable: true,
  15166. configurable: true
  15167. });
  15168. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15169. get: function () {
  15170. var pointers = this.inputs.attached["pointers"];
  15171. if (pointers)
  15172. return pointers.pinchPrecision;
  15173. },
  15174. set: function (value) {
  15175. var pointers = this.inputs.attached["pointers"];
  15176. if (pointers) {
  15177. pointers.pinchPrecision = value;
  15178. }
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15184. get: function () {
  15185. var pointers = this.inputs.attached["pointers"];
  15186. if (pointers)
  15187. return pointers.panningSensibility;
  15188. },
  15189. set: function (value) {
  15190. var pointers = this.inputs.attached["pointers"];
  15191. if (pointers) {
  15192. pointers.panningSensibility = value;
  15193. }
  15194. },
  15195. enumerable: true,
  15196. configurable: true
  15197. });
  15198. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15199. get: function () {
  15200. var keyboard = this.inputs.attached["keyboard"];
  15201. if (keyboard)
  15202. return keyboard.keysUp;
  15203. },
  15204. set: function (value) {
  15205. var keyboard = this.inputs.attached["keyboard"];
  15206. if (keyboard)
  15207. keyboard.keysUp = value;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15213. get: function () {
  15214. var keyboard = this.inputs.attached["keyboard"];
  15215. if (keyboard)
  15216. return keyboard.keysDown;
  15217. },
  15218. set: function (value) {
  15219. var keyboard = this.inputs.attached["keyboard"];
  15220. if (keyboard)
  15221. keyboard.keysDown = value;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15227. get: function () {
  15228. var keyboard = this.inputs.attached["keyboard"];
  15229. if (keyboard)
  15230. return keyboard.keysLeft;
  15231. },
  15232. set: function (value) {
  15233. var keyboard = this.inputs.attached["keyboard"];
  15234. if (keyboard)
  15235. keyboard.keysLeft = value;
  15236. },
  15237. enumerable: true,
  15238. configurable: true
  15239. });
  15240. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15241. get: function () {
  15242. var keyboard = this.inputs.attached["keyboard"];
  15243. if (keyboard)
  15244. return keyboard.keysRight;
  15245. },
  15246. set: function (value) {
  15247. var keyboard = this.inputs.attached["keyboard"];
  15248. if (keyboard)
  15249. keyboard.keysRight = value;
  15250. },
  15251. enumerable: true,
  15252. configurable: true
  15253. });
  15254. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15255. get: function () {
  15256. var mousewheel = this.inputs.attached["mousewheel"];
  15257. if (mousewheel)
  15258. return mousewheel.wheelPrecision;
  15259. },
  15260. set: function (value) {
  15261. var mousewheel = this.inputs.attached["mousewheel"];
  15262. if (mousewheel)
  15263. mousewheel.wheelPrecision = value;
  15264. },
  15265. enumerable: true,
  15266. configurable: true
  15267. });
  15268. // Cache
  15269. ArcRotateCamera.prototype._initCache = function () {
  15270. _super.prototype._initCache.call(this);
  15271. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15272. this._cache.alpha = undefined;
  15273. this._cache.beta = undefined;
  15274. this._cache.radius = undefined;
  15275. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15276. };
  15277. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15278. if (!ignoreParentClass) {
  15279. _super.prototype._updateCache.call(this);
  15280. }
  15281. this._cache.target.copyFrom(this._getTargetPosition());
  15282. this._cache.alpha = this.alpha;
  15283. this._cache.beta = this.beta;
  15284. this._cache.radius = this.radius;
  15285. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15286. };
  15287. ArcRotateCamera.prototype._getTargetPosition = function () {
  15288. if (this.target.getAbsolutePosition) {
  15289. var pos = this.target.getAbsolutePosition();
  15290. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15291. }
  15292. return this.target;
  15293. };
  15294. // Synchronized
  15295. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15296. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15297. return false;
  15298. return this._cache.target.equals(this.target)
  15299. && this._cache.alpha === this.alpha
  15300. && this._cache.beta === this.beta
  15301. && this._cache.radius === this.radius
  15302. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15303. };
  15304. // Methods
  15305. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15306. var _this = this;
  15307. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15308. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15309. this._useCtrlForPanning = useCtrlForPanning;
  15310. this._panningMouseButton = panningMouseButton;
  15311. this.inputs.attachElement(element, noPreventDefault);
  15312. this._reset = function () {
  15313. _this.inertialAlphaOffset = 0;
  15314. _this.inertialBetaOffset = 0;
  15315. _this.inertialRadiusOffset = 0;
  15316. };
  15317. };
  15318. ArcRotateCamera.prototype.detachControl = function (element) {
  15319. this.inputs.detachElement(element);
  15320. if (this._reset) {
  15321. this._reset();
  15322. }
  15323. };
  15324. ArcRotateCamera.prototype._checkInputs = function () {
  15325. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15326. if (this._collisionTriggered) {
  15327. return;
  15328. }
  15329. this.inputs.checkInputs();
  15330. // Inertia
  15331. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15332. this.beta += this.inertialBetaOffset;
  15333. if (this.getScene().useRightHandedSystem) {
  15334. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15335. }
  15336. else {
  15337. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15338. }
  15339. this.radius -= this.inertialRadiusOffset;
  15340. this.inertialAlphaOffset *= this.inertia;
  15341. this.inertialBetaOffset *= this.inertia;
  15342. this.inertialRadiusOffset *= this.inertia;
  15343. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15344. this.inertialAlphaOffset = 0;
  15345. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15346. this.inertialBetaOffset = 0;
  15347. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15348. this.inertialRadiusOffset = 0;
  15349. }
  15350. // Panning inertia
  15351. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15352. if (!this._localDirection) {
  15353. this._localDirection = BABYLON.Vector3.Zero();
  15354. this._transformedDirection = BABYLON.Vector3.Zero();
  15355. }
  15356. this.inertialPanningX *= this.inertia;
  15357. this.inertialPanningY *= this.inertia;
  15358. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15359. this.inertialPanningX = 0;
  15360. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15361. this.inertialPanningY = 0;
  15362. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15363. this._localDirection.multiplyInPlace(this.panningAxis);
  15364. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15365. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15366. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15367. if (!this.panningAxis.y) {
  15368. this._transformedDirection.y = 0;
  15369. }
  15370. if (!this.target.getAbsolutePosition) {
  15371. this.target.addInPlace(this._transformedDirection);
  15372. }
  15373. }
  15374. // Limits
  15375. this._checkLimits();
  15376. _super.prototype._checkInputs.call(this);
  15377. };
  15378. ArcRotateCamera.prototype._checkLimits = function () {
  15379. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15380. if (this.allowUpsideDown && this.beta > Math.PI) {
  15381. this.beta = this.beta - (2 * Math.PI);
  15382. }
  15383. }
  15384. else {
  15385. if (this.beta < this.lowerBetaLimit) {
  15386. this.beta = this.lowerBetaLimit;
  15387. }
  15388. }
  15389. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15390. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15391. this.beta = this.beta + (2 * Math.PI);
  15392. }
  15393. }
  15394. else {
  15395. if (this.beta > this.upperBetaLimit) {
  15396. this.beta = this.upperBetaLimit;
  15397. }
  15398. }
  15399. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15400. this.alpha = this.lowerAlphaLimit;
  15401. }
  15402. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15403. this.alpha = this.upperAlphaLimit;
  15404. }
  15405. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15406. this.radius = this.lowerRadiusLimit;
  15407. }
  15408. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15409. this.radius = this.upperRadiusLimit;
  15410. }
  15411. };
  15412. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15413. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15414. this.radius = radiusv3.length();
  15415. // Alpha
  15416. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15417. if (radiusv3.z < 0) {
  15418. this.alpha = 2 * Math.PI - this.alpha;
  15419. }
  15420. // Beta
  15421. this.beta = Math.acos(radiusv3.y / this.radius);
  15422. this._checkLimits();
  15423. };
  15424. ArcRotateCamera.prototype.setPosition = function (position) {
  15425. if (this.position.equals(position)) {
  15426. return;
  15427. }
  15428. this.position.copyFrom(position);
  15429. this.rebuildAnglesAndRadius();
  15430. };
  15431. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15432. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15433. if (this._getTargetPosition().equals(target)) {
  15434. return;
  15435. }
  15436. if (toBoundingCenter && target.getBoundingInfo) {
  15437. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15438. }
  15439. else {
  15440. this._targetBoundingCenter = null;
  15441. }
  15442. this.target = target;
  15443. this.rebuildAnglesAndRadius();
  15444. };
  15445. ArcRotateCamera.prototype._getViewMatrix = function () {
  15446. // Compute
  15447. var cosa = Math.cos(this.alpha);
  15448. var sina = Math.sin(this.alpha);
  15449. var cosb = Math.cos(this.beta);
  15450. var sinb = Math.sin(this.beta);
  15451. if (sinb === 0) {
  15452. sinb = 0.0001;
  15453. }
  15454. var target = this._getTargetPosition();
  15455. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15456. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15457. this._collider.radius = this.collisionRadius;
  15458. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15459. this._collisionTriggered = true;
  15460. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15461. }
  15462. else {
  15463. this.position.copyFrom(this._newPosition);
  15464. var up = this.upVector;
  15465. if (this.allowUpsideDown && this.beta < 0) {
  15466. up = up.clone();
  15467. up = up.negate();
  15468. }
  15469. if (this.getScene().useRightHandedSystem) {
  15470. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15471. }
  15472. else {
  15473. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15474. }
  15475. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15476. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15477. }
  15478. return this._viewMatrix;
  15479. };
  15480. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15481. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15482. meshes = meshes || this.getScene().meshes;
  15483. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15484. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15485. this.radius = distance * this.zoomOnFactor;
  15486. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15487. };
  15488. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15489. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15490. var meshesOrMinMaxVector;
  15491. var distance;
  15492. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15493. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15494. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15495. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15496. }
  15497. else {
  15498. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15499. distance = meshesOrMinMaxVectorAndDistance.distance;
  15500. }
  15501. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15502. if (!doNotUpdateMaxZ) {
  15503. this.maxZ = distance * 2;
  15504. }
  15505. };
  15506. /**
  15507. * @override
  15508. * Override Camera.createRigCamera
  15509. */
  15510. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15511. var alphaShift;
  15512. switch (this.cameraRigMode) {
  15513. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15514. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15515. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15516. case BABYLON.Camera.RIG_MODE_VR:
  15517. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15518. break;
  15519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15520. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15521. break;
  15522. }
  15523. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15524. rigCam._cameraRigParams = {};
  15525. return rigCam;
  15526. };
  15527. /**
  15528. * @override
  15529. * Override Camera._updateRigCameras
  15530. */
  15531. ArcRotateCamera.prototype._updateRigCameras = function () {
  15532. var camLeft = this._rigCameras[0];
  15533. var camRight = this._rigCameras[1];
  15534. camLeft.beta = camRight.beta = this.beta;
  15535. camLeft.radius = camRight.radius = this.radius;
  15536. switch (this.cameraRigMode) {
  15537. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15538. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15539. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15540. case BABYLON.Camera.RIG_MODE_VR:
  15541. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15542. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15543. break;
  15544. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15545. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15546. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15547. break;
  15548. }
  15549. _super.prototype._updateRigCameras.call(this);
  15550. };
  15551. ArcRotateCamera.prototype.dispose = function () {
  15552. this.inputs.clear();
  15553. _super.prototype.dispose.call(this);
  15554. };
  15555. ArcRotateCamera.prototype.getTypeName = function () {
  15556. return "ArcRotateCamera";
  15557. };
  15558. __decorate([
  15559. BABYLON.serialize()
  15560. ], ArcRotateCamera.prototype, "alpha", void 0);
  15561. __decorate([
  15562. BABYLON.serialize()
  15563. ], ArcRotateCamera.prototype, "beta", void 0);
  15564. __decorate([
  15565. BABYLON.serialize()
  15566. ], ArcRotateCamera.prototype, "radius", void 0);
  15567. __decorate([
  15568. BABYLON.serializeAsVector3()
  15569. ], ArcRotateCamera.prototype, "target", void 0);
  15570. __decorate([
  15571. BABYLON.serialize()
  15572. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15573. __decorate([
  15574. BABYLON.serialize()
  15575. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15576. __decorate([
  15577. BABYLON.serialize()
  15578. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15579. __decorate([
  15580. BABYLON.serialize()
  15581. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15582. __decorate([
  15583. BABYLON.serialize()
  15584. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15585. __decorate([
  15586. BABYLON.serialize()
  15587. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15588. __decorate([
  15589. BABYLON.serialize()
  15590. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15591. __decorate([
  15592. BABYLON.serialize()
  15593. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15594. __decorate([
  15595. BABYLON.serialize()
  15596. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15597. __decorate([
  15598. BABYLON.serialize()
  15599. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15600. __decorate([
  15601. BABYLON.serialize()
  15602. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15603. __decorate([
  15604. BABYLON.serialize()
  15605. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15606. __decorate([
  15607. BABYLON.serialize()
  15608. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15609. return ArcRotateCamera;
  15610. }(BABYLON.TargetCamera));
  15611. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15612. })(BABYLON || (BABYLON = {}));
  15613. var BABYLON;
  15614. (function (BABYLON) {
  15615. var ArcRotateCameraInputsManager = (function (_super) {
  15616. __extends(ArcRotateCameraInputsManager, _super);
  15617. function ArcRotateCameraInputsManager(camera) {
  15618. _super.call(this, camera);
  15619. }
  15620. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15621. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15622. return this;
  15623. };
  15624. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15625. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15626. return this;
  15627. };
  15628. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15629. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15630. return this;
  15631. };
  15632. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15633. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15634. return this;
  15635. };
  15636. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15637. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15638. return this;
  15639. };
  15640. return ArcRotateCameraInputsManager;
  15641. }(BABYLON.CameraInputsManager));
  15642. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15643. })(BABYLON || (BABYLON = {}));
  15644. var BABYLON;
  15645. (function (BABYLON) {
  15646. var RenderingManager = (function () {
  15647. function RenderingManager(scene) {
  15648. this._renderingGroups = new Array();
  15649. this._autoClearDepthStencil = {};
  15650. this._customOpaqueSortCompareFn = {};
  15651. this._customAlphaTestSortCompareFn = {};
  15652. this._customTransparentSortCompareFn = {};
  15653. this._renderinGroupInfo = null;
  15654. this._scene = scene;
  15655. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15656. this._autoClearDepthStencil[i] = true;
  15657. }
  15658. }
  15659. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15660. if (this._scene._activeParticleSystems.length === 0) {
  15661. return;
  15662. }
  15663. // Particles
  15664. var activeCamera = this._scene.activeCamera;
  15665. this._scene._particlesDuration.beginMonitoring();
  15666. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15667. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15668. if (particleSystem.renderingGroupId !== index) {
  15669. continue;
  15670. }
  15671. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15672. continue;
  15673. }
  15674. this._clearDepthStencilBuffer();
  15675. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15676. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15677. }
  15678. }
  15679. this._scene._particlesDuration.endMonitoring(false);
  15680. };
  15681. RenderingManager.prototype._renderSprites = function (index) {
  15682. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15683. return;
  15684. }
  15685. // Sprites
  15686. var activeCamera = this._scene.activeCamera;
  15687. this._scene._spritesDuration.beginMonitoring();
  15688. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15689. var spriteManager = this._scene.spriteManagers[id];
  15690. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15691. this._clearDepthStencilBuffer();
  15692. spriteManager.render();
  15693. }
  15694. }
  15695. this._scene._spritesDuration.endMonitoring(false);
  15696. };
  15697. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15698. if (this._depthStencilBufferAlreadyCleaned) {
  15699. return;
  15700. }
  15701. this._scene.getEngine().clear(0, false, true, true);
  15702. this._depthStencilBufferAlreadyCleaned = true;
  15703. };
  15704. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15705. if (this._currentRenderSprites) {
  15706. this._renderSprites(this._currentIndex);
  15707. }
  15708. if (this._currentRenderParticles) {
  15709. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15710. }
  15711. };
  15712. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15713. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15714. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15715. var info = null;
  15716. if (observable) {
  15717. if (!this._renderinGroupInfo) {
  15718. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15719. }
  15720. info = this._renderinGroupInfo;
  15721. info.scene = this._scene;
  15722. info.camera = this._scene.activeCamera;
  15723. }
  15724. this._currentActiveMeshes = activeMeshes;
  15725. this._currentRenderParticles = renderParticles;
  15726. this._currentRenderSprites = renderSprites;
  15727. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15728. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15729. var renderingGroup = this._renderingGroups[index];
  15730. var needToStepBack = false;
  15731. this._currentIndex = index;
  15732. if (renderingGroup) {
  15733. var renderingGroupMask = 0;
  15734. // Fire PRECLEAR stage
  15735. if (observable) {
  15736. renderingGroupMask = Math.pow(2, index);
  15737. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15738. info.renderingGroupId = index;
  15739. observable.notifyObservers(info, renderingGroupMask);
  15740. }
  15741. // Clear depth/stencil if needed
  15742. if (this._autoClearDepthStencil[index]) {
  15743. this._clearDepthStencilBuffer();
  15744. }
  15745. // Fire PREOPAQUE stage
  15746. if (observable) {
  15747. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15748. observable.notifyObservers(info, renderingGroupMask);
  15749. }
  15750. if (!renderingGroup.onBeforeTransparentRendering) {
  15751. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15752. }
  15753. // Fire PRETRANSPARENT stage
  15754. if (observable) {
  15755. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15756. observable.notifyObservers(info, renderingGroupMask);
  15757. }
  15758. if (!renderingGroup.render(customRenderFunction)) {
  15759. this._renderingGroups.splice(index, 1);
  15760. needToStepBack = true;
  15761. this._renderSpritesAndParticles();
  15762. }
  15763. // Fire POSTTRANSPARENT stage
  15764. if (observable) {
  15765. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15766. observable.notifyObservers(info, renderingGroupMask);
  15767. }
  15768. }
  15769. else {
  15770. this._renderSpritesAndParticles();
  15771. if (observable) {
  15772. var renderingGroupMask = Math.pow(2, index);
  15773. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15774. info.renderingGroupId = index;
  15775. observable.notifyObservers(info, renderingGroupMask);
  15776. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15777. observable.notifyObservers(info, renderingGroupMask);
  15778. }
  15779. }
  15780. if (needToStepBack) {
  15781. index--;
  15782. }
  15783. }
  15784. };
  15785. RenderingManager.prototype.reset = function () {
  15786. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15787. var renderingGroup = this._renderingGroups[index];
  15788. if (renderingGroup) {
  15789. renderingGroup.prepare();
  15790. }
  15791. }
  15792. };
  15793. RenderingManager.prototype.dispatch = function (subMesh) {
  15794. var mesh = subMesh.getMesh();
  15795. var renderingGroupId = mesh.renderingGroupId || 0;
  15796. if (!this._renderingGroups[renderingGroupId]) {
  15797. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15798. }
  15799. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15800. };
  15801. /**
  15802. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15803. * This allowed control for front to back rendering or reversly depending of the special needs.
  15804. *
  15805. * @param renderingGroupId The rendering group id corresponding to its index
  15806. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15807. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15808. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15809. */
  15810. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15811. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15812. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15813. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15814. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15815. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15816. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15817. if (this._renderingGroups[renderingGroupId]) {
  15818. var group = this._renderingGroups[renderingGroupId];
  15819. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15820. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15821. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15822. }
  15823. };
  15824. /**
  15825. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15826. *
  15827. * @param renderingGroupId The rendering group id corresponding to its index
  15828. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15829. */
  15830. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15831. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15832. };
  15833. /**
  15834. * The max id used for rendering groups (not included)
  15835. */
  15836. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15837. /**
  15838. * The min id used for rendering groups (included)
  15839. */
  15840. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15841. return RenderingManager;
  15842. }());
  15843. BABYLON.RenderingManager = RenderingManager;
  15844. })(BABYLON || (BABYLON = {}));
  15845. var BABYLON;
  15846. (function (BABYLON) {
  15847. var RenderingGroup = (function () {
  15848. /**
  15849. * Creates a new rendering group.
  15850. * @param index The rendering group index
  15851. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15852. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15853. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15854. */
  15855. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15856. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15857. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15858. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15859. this.index = index;
  15860. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15861. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15862. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15863. this._scene = scene;
  15864. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15865. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15866. this.transparentSortCompareFn = transparentSortCompareFn;
  15867. }
  15868. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15869. /**
  15870. * Set the opaque sort comparison function.
  15871. * If null the sub meshes will be render in the order they were created
  15872. */
  15873. set: function (value) {
  15874. this._opaqueSortCompareFn = value;
  15875. if (value) {
  15876. this._renderOpaque = this.renderOpaqueSorted;
  15877. }
  15878. else {
  15879. this._renderOpaque = RenderingGroup.renderUnsorted;
  15880. }
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15886. /**
  15887. * Set the alpha test sort comparison function.
  15888. * If null the sub meshes will be render in the order they were created
  15889. */
  15890. set: function (value) {
  15891. this._alphaTestSortCompareFn = value;
  15892. if (value) {
  15893. this._renderAlphaTest = this.renderAlphaTestSorted;
  15894. }
  15895. else {
  15896. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15897. }
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15903. /**
  15904. * Set the transparent sort comparison function.
  15905. * If null the sub meshes will be render in the order they were created
  15906. */
  15907. set: function (value) {
  15908. if (value) {
  15909. this._transparentSortCompareFn = value;
  15910. }
  15911. else {
  15912. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15913. }
  15914. this._renderTransparent = this.renderTransparentSorted;
  15915. },
  15916. enumerable: true,
  15917. configurable: true
  15918. });
  15919. /**
  15920. * Render all the sub meshes contained in the group.
  15921. * @param customRenderFunction Used to override the default render behaviour of the group.
  15922. * @returns true if rendered some submeshes.
  15923. */
  15924. RenderingGroup.prototype.render = function (customRenderFunction) {
  15925. if (customRenderFunction) {
  15926. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15927. return true;
  15928. }
  15929. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15930. if (this.onBeforeTransparentRendering) {
  15931. this.onBeforeTransparentRendering();
  15932. }
  15933. return false;
  15934. }
  15935. var engine = this._scene.getEngine();
  15936. // Opaque
  15937. this._renderOpaque(this._opaqueSubMeshes);
  15938. // Alpha test
  15939. engine.setAlphaTesting(true);
  15940. this._renderAlphaTest(this._alphaTestSubMeshes);
  15941. engine.setAlphaTesting(false);
  15942. if (this.onBeforeTransparentRendering) {
  15943. this.onBeforeTransparentRendering();
  15944. }
  15945. // Transparent
  15946. this._renderTransparent(this._transparentSubMeshes);
  15947. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15948. return true;
  15949. };
  15950. /**
  15951. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15952. * @param subMeshes The submeshes to render
  15953. */
  15954. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15955. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15956. };
  15957. /**
  15958. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15959. * @param subMeshes The submeshes to render
  15960. */
  15961. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15962. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15963. };
  15964. /**
  15965. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15966. * @param subMeshes The submeshes to render
  15967. */
  15968. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15969. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15970. };
  15971. /**
  15972. * Renders the submeshes in a specified order.
  15973. * @param subMeshes The submeshes to sort before render
  15974. * @param sortCompareFn The comparison function use to sort
  15975. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15976. * @param transparent Specifies to activate blending if true
  15977. */
  15978. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15979. var subIndex = 0;
  15980. var subMesh;
  15981. for (; subIndex < subMeshes.length; subIndex++) {
  15982. subMesh = subMeshes.data[subIndex];
  15983. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15984. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15985. }
  15986. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15987. sortedArray.sort(sortCompareFn);
  15988. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15989. subMesh = sortedArray[subIndex];
  15990. subMesh.render(transparent);
  15991. }
  15992. };
  15993. /**
  15994. * Renders the submeshes in the order they were dispatched (no sort applied).
  15995. * @param subMeshes The submeshes to render
  15996. */
  15997. RenderingGroup.renderUnsorted = function (subMeshes) {
  15998. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15999. var submesh = subMeshes.data[subIndex];
  16000. submesh.render(false);
  16001. }
  16002. };
  16003. /**
  16004. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16005. * are rendered back to front if in the same alpha index.
  16006. *
  16007. * @param a The first submesh
  16008. * @param b The second submesh
  16009. * @returns The result of the comparison
  16010. */
  16011. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16012. // Alpha index first
  16013. if (a._alphaIndex > b._alphaIndex) {
  16014. return 1;
  16015. }
  16016. if (a._alphaIndex < b._alphaIndex) {
  16017. return -1;
  16018. }
  16019. // Then distance to camera
  16020. return RenderingGroup.backToFrontSortCompare(a, b);
  16021. };
  16022. /**
  16023. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16024. * are rendered back to front.
  16025. *
  16026. * @param a The first submesh
  16027. * @param b The second submesh
  16028. * @returns The result of the comparison
  16029. */
  16030. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16031. // Then distance to camera
  16032. if (a._distanceToCamera < b._distanceToCamera) {
  16033. return 1;
  16034. }
  16035. if (a._distanceToCamera > b._distanceToCamera) {
  16036. return -1;
  16037. }
  16038. return 0;
  16039. };
  16040. /**
  16041. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16042. * are rendered front to back (prevent overdraw).
  16043. *
  16044. * @param a The first submesh
  16045. * @param b The second submesh
  16046. * @returns The result of the comparison
  16047. */
  16048. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16049. // Then distance to camera
  16050. if (a._distanceToCamera < b._distanceToCamera) {
  16051. return -1;
  16052. }
  16053. if (a._distanceToCamera > b._distanceToCamera) {
  16054. return 1;
  16055. }
  16056. return 0;
  16057. };
  16058. /**
  16059. * Resets the different lists of submeshes to prepare a new frame.
  16060. */
  16061. RenderingGroup.prototype.prepare = function () {
  16062. this._opaqueSubMeshes.reset();
  16063. this._transparentSubMeshes.reset();
  16064. this._alphaTestSubMeshes.reset();
  16065. };
  16066. /**
  16067. * Inserts the submesh in its correct queue depending on its material.
  16068. * @param subMesh The submesh to dispatch
  16069. */
  16070. RenderingGroup.prototype.dispatch = function (subMesh) {
  16071. var material = subMesh.getMaterial();
  16072. var mesh = subMesh.getMesh();
  16073. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16074. this._transparentSubMeshes.push(subMesh);
  16075. }
  16076. else if (material.needAlphaTesting()) {
  16077. this._alphaTestSubMeshes.push(subMesh);
  16078. }
  16079. else {
  16080. this._opaqueSubMeshes.push(subMesh); // Opaque
  16081. }
  16082. };
  16083. return RenderingGroup;
  16084. }());
  16085. BABYLON.RenderingGroup = RenderingGroup;
  16086. })(BABYLON || (BABYLON = {}));
  16087. var BABYLON;
  16088. (function (BABYLON) {
  16089. var PointerEventTypes = (function () {
  16090. function PointerEventTypes() {
  16091. }
  16092. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16093. get: function () {
  16094. return PointerEventTypes._POINTERDOWN;
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16100. get: function () {
  16101. return PointerEventTypes._POINTERUP;
  16102. },
  16103. enumerable: true,
  16104. configurable: true
  16105. });
  16106. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16107. get: function () {
  16108. return PointerEventTypes._POINTERMOVE;
  16109. },
  16110. enumerable: true,
  16111. configurable: true
  16112. });
  16113. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16114. get: function () {
  16115. return PointerEventTypes._POINTERWHEEL;
  16116. },
  16117. enumerable: true,
  16118. configurable: true
  16119. });
  16120. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16121. get: function () {
  16122. return PointerEventTypes._POINTERPICK;
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. PointerEventTypes._POINTERDOWN = 0x01;
  16128. PointerEventTypes._POINTERUP = 0x02;
  16129. PointerEventTypes._POINTERMOVE = 0x04;
  16130. PointerEventTypes._POINTERWHEEL = 0x08;
  16131. PointerEventTypes._POINTERPICK = 0x10;
  16132. return PointerEventTypes;
  16133. }());
  16134. BABYLON.PointerEventTypes = PointerEventTypes;
  16135. var PointerInfoBase = (function () {
  16136. function PointerInfoBase(type, event) {
  16137. this.type = type;
  16138. this.event = event;
  16139. }
  16140. return PointerInfoBase;
  16141. }());
  16142. BABYLON.PointerInfoBase = PointerInfoBase;
  16143. /**
  16144. * This class is used to store pointer related info for the onPrePointerObservable event.
  16145. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16146. */
  16147. var PointerInfoPre = (function (_super) {
  16148. __extends(PointerInfoPre, _super);
  16149. function PointerInfoPre(type, event, localX, localY) {
  16150. _super.call(this, type, event);
  16151. this.skipOnPointerObservable = false;
  16152. this.localPosition = new BABYLON.Vector2(localX, localY);
  16153. }
  16154. return PointerInfoPre;
  16155. }(PointerInfoBase));
  16156. BABYLON.PointerInfoPre = PointerInfoPre;
  16157. /**
  16158. * This type contains all the data related to a pointer event in Babylon.js.
  16159. * 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.
  16160. */
  16161. var PointerInfo = (function (_super) {
  16162. __extends(PointerInfo, _super);
  16163. function PointerInfo(type, event, pickInfo) {
  16164. _super.call(this, type, event);
  16165. this.pickInfo = pickInfo;
  16166. }
  16167. return PointerInfo;
  16168. }(PointerInfoBase));
  16169. BABYLON.PointerInfo = PointerInfo;
  16170. /**
  16171. * This class is used by the onRenderingGroupObservable
  16172. */
  16173. var RenderingGroupInfo = (function () {
  16174. function RenderingGroupInfo() {
  16175. }
  16176. /**
  16177. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16178. * This stage will be fired no matter what
  16179. */
  16180. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16181. /**
  16182. * Called before opaque object are rendered.
  16183. * This stage will be fired only if there's 3D Opaque content to render
  16184. */
  16185. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16186. /**
  16187. * Called after the opaque objects are rendered and before the transparent ones
  16188. * This stage will be fired only if there's 3D transparent content to render
  16189. */
  16190. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16191. /**
  16192. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16193. * This stage will be fired no matter what
  16194. */
  16195. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16196. return RenderingGroupInfo;
  16197. }());
  16198. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16199. /**
  16200. * Represents a scene to be rendered by the engine.
  16201. * @see http://doc.babylonjs.com/page.php?p=21911
  16202. */
  16203. var Scene = (function () {
  16204. /**
  16205. * @constructor
  16206. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16207. */
  16208. function Scene(engine) {
  16209. // Members
  16210. this.autoClear = true;
  16211. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16212. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16213. this.forceWireframe = false;
  16214. this.forcePointsCloud = false;
  16215. this.forceShowBoundingBoxes = false;
  16216. this.animationsEnabled = true;
  16217. this.constantlyUpdateMeshUnderPointer = false;
  16218. this.useRightHandedSystem = false;
  16219. this.hoverCursor = "pointer";
  16220. // Events
  16221. /**
  16222. * An event triggered when the scene is disposed.
  16223. * @type {BABYLON.Observable}
  16224. */
  16225. this.onDisposeObservable = new BABYLON.Observable();
  16226. /**
  16227. * An event triggered before rendering the scene
  16228. * @type {BABYLON.Observable}
  16229. */
  16230. this.onBeforeRenderObservable = new BABYLON.Observable();
  16231. /**
  16232. * An event triggered after rendering the scene
  16233. * @type {BABYLON.Observable}
  16234. */
  16235. this.onAfterRenderObservable = new BABYLON.Observable();
  16236. /**
  16237. * An event triggered when the scene is ready
  16238. * @type {BABYLON.Observable}
  16239. */
  16240. this.onReadyObservable = new BABYLON.Observable();
  16241. /**
  16242. * An event triggered before rendering a camera
  16243. * @type {BABYLON.Observable}
  16244. */
  16245. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16246. /**
  16247. * An event triggered after rendering a camera
  16248. * @type {BABYLON.Observable}
  16249. */
  16250. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16251. /**
  16252. * An event triggered when a camera is created
  16253. * @type {BABYLON.Observable}
  16254. */
  16255. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16256. /**
  16257. * An event triggered when a camera is removed
  16258. * @type {BABYLON.Observable}
  16259. */
  16260. this.onCameraRemovedObservable = new BABYLON.Observable();
  16261. /**
  16262. * An event triggered when a light is created
  16263. * @type {BABYLON.Observable}
  16264. */
  16265. this.onNewLightAddedObservable = new BABYLON.Observable();
  16266. /**
  16267. * An event triggered when a light is removed
  16268. * @type {BABYLON.Observable}
  16269. */
  16270. this.onLightRemovedObservable = new BABYLON.Observable();
  16271. /**
  16272. * An event triggered when a geometry is created
  16273. * @type {BABYLON.Observable}
  16274. */
  16275. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16276. /**
  16277. * An event triggered when a geometry is removed
  16278. * @type {BABYLON.Observable}
  16279. */
  16280. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16281. /**
  16282. * An event triggered when a mesh is created
  16283. * @type {BABYLON.Observable}
  16284. */
  16285. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16286. /**
  16287. * An event triggered when a mesh is removed
  16288. * @type {BABYLON.Observable}
  16289. */
  16290. this.onMeshRemovedObservable = new BABYLON.Observable();
  16291. /**
  16292. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16293. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16294. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  16295. */
  16296. this.onRenderingGroupObservable = new BABYLON.Observable();
  16297. // Animations
  16298. this.animations = [];
  16299. /**
  16300. * 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).
  16301. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16302. */
  16303. this.onPrePointerObservable = new BABYLON.Observable();
  16304. /**
  16305. * Observable event triggered each time an input event is received from the rendering canvas
  16306. */
  16307. this.onPointerObservable = new BABYLON.Observable();
  16308. 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
  16309. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16310. this._startingPointerTime = 0;
  16311. // Fog
  16312. /**
  16313. * is fog enabled on this scene.
  16314. * @type {boolean}
  16315. */
  16316. this.fogEnabled = true;
  16317. this.fogMode = Scene.FOGMODE_NONE;
  16318. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16319. this.fogDensity = 0.1;
  16320. this.fogStart = 0;
  16321. this.fogEnd = 1000.0;
  16322. // Lights
  16323. /**
  16324. * is shadow enabled on this scene.
  16325. * @type {boolean}
  16326. */
  16327. this.shadowsEnabled = true;
  16328. /**
  16329. * is light enabled on this scene.
  16330. * @type {boolean}
  16331. */
  16332. this.lightsEnabled = true;
  16333. /**
  16334. * All of the lights added to this scene.
  16335. * @see BABYLON.Light
  16336. * @type {BABYLON.Light[]}
  16337. */
  16338. this.lights = new Array();
  16339. // Cameras
  16340. /**
  16341. * All of the cameras added to this scene.
  16342. * @see BABYLON.Camera
  16343. * @type {BABYLON.Camera[]}
  16344. */
  16345. this.cameras = new Array();
  16346. this.activeCameras = new Array();
  16347. // Meshes
  16348. /**
  16349. * All of the (abstract) meshes added to this scene.
  16350. * @see BABYLON.AbstractMesh
  16351. * @type {BABYLON.AbstractMesh[]}
  16352. */
  16353. this.meshes = new Array();
  16354. // Geometries
  16355. this._geometries = new Array();
  16356. this.materials = new Array();
  16357. this.multiMaterials = new Array();
  16358. // Textures
  16359. this.texturesEnabled = true;
  16360. this.textures = new Array();
  16361. // Particles
  16362. this.particlesEnabled = true;
  16363. this.particleSystems = new Array();
  16364. // Sprites
  16365. this.spritesEnabled = true;
  16366. this.spriteManagers = new Array();
  16367. // Layers
  16368. this.layers = new Array();
  16369. this.highlightLayers = new Array();
  16370. // Skeletons
  16371. this.skeletonsEnabled = true;
  16372. this.skeletons = new Array();
  16373. // Lens flares
  16374. this.lensFlaresEnabled = true;
  16375. this.lensFlareSystems = new Array();
  16376. // Collisions
  16377. this.collisionsEnabled = true;
  16378. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16379. // Postprocesses
  16380. this.postProcessesEnabled = true;
  16381. // Customs render targets
  16382. this.renderTargetsEnabled = true;
  16383. this.dumpNextRenderTargets = false;
  16384. this.customRenderTargets = new Array();
  16385. // Imported meshes
  16386. this.importedMeshesFiles = new Array();
  16387. // Probes
  16388. this.probesEnabled = true;
  16389. this.reflectionProbes = new Array();
  16390. this._actionManagers = new Array();
  16391. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16392. // Procedural textures
  16393. this.proceduralTexturesEnabled = true;
  16394. this._proceduralTextures = new Array();
  16395. this.soundTracks = new Array();
  16396. this._audioEnabled = true;
  16397. this._headphone = false;
  16398. // Performance counters
  16399. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16400. this._totalLightsCounter = new BABYLON.PerfCounter();
  16401. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16402. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16403. this._totalVertices = new BABYLON.PerfCounter();
  16404. this._activeIndices = new BABYLON.PerfCounter();
  16405. this._activeParticles = new BABYLON.PerfCounter();
  16406. this._lastFrameDuration = new BABYLON.PerfCounter();
  16407. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16408. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16409. this._particlesDuration = new BABYLON.PerfCounter();
  16410. this._renderDuration = new BABYLON.PerfCounter();
  16411. this._spritesDuration = new BABYLON.PerfCounter();
  16412. this._activeBones = new BABYLON.PerfCounter();
  16413. this._renderId = 0;
  16414. this._executeWhenReadyTimeoutId = -1;
  16415. this._intermediateRendering = false;
  16416. this._toBeDisposed = new BABYLON.SmartArray(256);
  16417. this._pendingData = []; //ANY
  16418. this._activeMeshes = new BABYLON.SmartArray(256);
  16419. this._processedMaterials = new BABYLON.SmartArray(256);
  16420. this._renderTargets = new BABYLON.SmartArray(256);
  16421. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16422. this._activeSkeletons = new BABYLON.SmartArray(32);
  16423. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16424. this._activeAnimatables = new Array();
  16425. this._transformMatrix = BABYLON.Matrix.Zero();
  16426. this._edgesRenderers = new BABYLON.SmartArray(16);
  16427. this._uniqueIdCounter = 0;
  16428. this._engine = engine;
  16429. engine.scenes.push(this);
  16430. this._externalData = new BABYLON.StringDictionary();
  16431. this._uid = null;
  16432. this._renderingManager = new BABYLON.RenderingManager(this);
  16433. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16434. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16435. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16436. if (BABYLON.OutlineRenderer) {
  16437. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16438. }
  16439. this.attachControl();
  16440. if (BABYLON.SoundTrack) {
  16441. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16442. }
  16443. //simplification queue
  16444. if (BABYLON.SimplificationQueue) {
  16445. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16446. }
  16447. //collision coordinator initialization. For now legacy per default.
  16448. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16449. }
  16450. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16451. get: function () {
  16452. return Scene._FOGMODE_NONE;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16458. get: function () {
  16459. return Scene._FOGMODE_EXP;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16465. get: function () {
  16466. return Scene._FOGMODE_EXP2;
  16467. },
  16468. enumerable: true,
  16469. configurable: true
  16470. });
  16471. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16472. get: function () {
  16473. return Scene._FOGMODE_LINEAR;
  16474. },
  16475. enumerable: true,
  16476. configurable: true
  16477. });
  16478. Object.defineProperty(Scene.prototype, "onDispose", {
  16479. set: function (callback) {
  16480. if (this._onDisposeObserver) {
  16481. this.onDisposeObservable.remove(this._onDisposeObserver);
  16482. }
  16483. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16484. },
  16485. enumerable: true,
  16486. configurable: true
  16487. });
  16488. Object.defineProperty(Scene.prototype, "beforeRender", {
  16489. set: function (callback) {
  16490. if (this._onBeforeRenderObserver) {
  16491. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16492. }
  16493. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16494. },
  16495. enumerable: true,
  16496. configurable: true
  16497. });
  16498. Object.defineProperty(Scene.prototype, "afterRender", {
  16499. set: function (callback) {
  16500. if (this._onAfterRenderObserver) {
  16501. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16502. }
  16503. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16504. },
  16505. enumerable: true,
  16506. configurable: true
  16507. });
  16508. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16509. set: function (callback) {
  16510. if (this._onBeforeCameraRenderObserver) {
  16511. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16512. }
  16513. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16519. set: function (callback) {
  16520. if (this._onAfterCameraRenderObserver) {
  16521. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16522. }
  16523. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16529. get: function () {
  16530. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16531. },
  16532. enumerable: true,
  16533. configurable: true
  16534. });
  16535. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16536. get: function () {
  16537. if (!this._defaultMaterial) {
  16538. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16539. }
  16540. return this._defaultMaterial;
  16541. },
  16542. enumerable: true,
  16543. configurable: true
  16544. });
  16545. Object.defineProperty(Scene.prototype, "debugLayer", {
  16546. // Properties
  16547. get: function () {
  16548. if (!this._debugLayer) {
  16549. this._debugLayer = new BABYLON.DebugLayer(this);
  16550. }
  16551. return this._debugLayer;
  16552. },
  16553. enumerable: true,
  16554. configurable: true
  16555. });
  16556. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16557. get: function () {
  16558. return this._workerCollisions;
  16559. },
  16560. set: function (enabled) {
  16561. enabled = (enabled && !!Worker);
  16562. this._workerCollisions = enabled;
  16563. if (this.collisionCoordinator) {
  16564. this.collisionCoordinator.destroy();
  16565. }
  16566. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16567. this.collisionCoordinator.init(this);
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16573. get: function () {
  16574. return this._selectionOctree;
  16575. },
  16576. enumerable: true,
  16577. configurable: true
  16578. });
  16579. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16580. /**
  16581. * The mesh that is currently under the pointer.
  16582. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16583. */
  16584. get: function () {
  16585. return this._pointerOverMesh;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(Scene.prototype, "pointerX", {
  16591. /**
  16592. * Current on-screen X position of the pointer
  16593. * @return {number} X position of the pointer
  16594. */
  16595. get: function () {
  16596. return this._pointerX;
  16597. },
  16598. enumerable: true,
  16599. configurable: true
  16600. });
  16601. Object.defineProperty(Scene.prototype, "pointerY", {
  16602. /**
  16603. * Current on-screen Y position of the pointer
  16604. * @return {number} Y position of the pointer
  16605. */
  16606. get: function () {
  16607. return this._pointerY;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Scene.prototype.getCachedMaterial = function () {
  16613. return this._cachedMaterial;
  16614. };
  16615. Scene.prototype.getBoundingBoxRenderer = function () {
  16616. return this._boundingBoxRenderer;
  16617. };
  16618. Scene.prototype.getOutlineRenderer = function () {
  16619. return this._outlineRenderer;
  16620. };
  16621. Scene.prototype.getEngine = function () {
  16622. return this._engine;
  16623. };
  16624. Scene.prototype.getTotalVertices = function () {
  16625. return this._totalVertices.current;
  16626. };
  16627. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16628. get: function () {
  16629. return this._totalVertices;
  16630. },
  16631. enumerable: true,
  16632. configurable: true
  16633. });
  16634. Scene.prototype.getActiveIndices = function () {
  16635. return this._activeIndices.current;
  16636. };
  16637. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16638. get: function () {
  16639. return this._activeIndices;
  16640. },
  16641. enumerable: true,
  16642. configurable: true
  16643. });
  16644. Scene.prototype.getActiveParticles = function () {
  16645. return this._activeParticles.current;
  16646. };
  16647. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16648. get: function () {
  16649. return this._activeParticles;
  16650. },
  16651. enumerable: true,
  16652. configurable: true
  16653. });
  16654. Scene.prototype.getActiveBones = function () {
  16655. return this._activeBones.current;
  16656. };
  16657. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16658. get: function () {
  16659. return this._activeBones;
  16660. },
  16661. enumerable: true,
  16662. configurable: true
  16663. });
  16664. // Stats
  16665. Scene.prototype.getLastFrameDuration = function () {
  16666. return this._lastFrameDuration.current;
  16667. };
  16668. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16669. get: function () {
  16670. return this._lastFrameDuration;
  16671. },
  16672. enumerable: true,
  16673. configurable: true
  16674. });
  16675. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16676. return this._evaluateActiveMeshesDuration.current;
  16677. };
  16678. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16679. get: function () {
  16680. return this._evaluateActiveMeshesDuration;
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Scene.prototype.getActiveMeshes = function () {
  16686. return this._activeMeshes;
  16687. };
  16688. Scene.prototype.getRenderTargetsDuration = function () {
  16689. return this._renderTargetsDuration.current;
  16690. };
  16691. Scene.prototype.getRenderDuration = function () {
  16692. return this._renderDuration.current;
  16693. };
  16694. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16695. get: function () {
  16696. return this._renderDuration;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. Scene.prototype.getParticlesDuration = function () {
  16702. return this._particlesDuration.current;
  16703. };
  16704. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16705. get: function () {
  16706. return this._particlesDuration;
  16707. },
  16708. enumerable: true,
  16709. configurable: true
  16710. });
  16711. Scene.prototype.getSpritesDuration = function () {
  16712. return this._spritesDuration.current;
  16713. };
  16714. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16715. get: function () {
  16716. return this._spritesDuration;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Scene.prototype.getAnimationRatio = function () {
  16722. return this._animationRatio;
  16723. };
  16724. Scene.prototype.getRenderId = function () {
  16725. return this._renderId;
  16726. };
  16727. Scene.prototype.incrementRenderId = function () {
  16728. this._renderId++;
  16729. };
  16730. Scene.prototype._updatePointerPosition = function (evt) {
  16731. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16732. this._pointerX = evt.clientX - canvasRect.left;
  16733. this._pointerY = evt.clientY - canvasRect.top;
  16734. this._unTranslatedPointerX = this._pointerX;
  16735. this._unTranslatedPointerY = this._pointerY;
  16736. if (this.cameraToUseForPointers) {
  16737. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16738. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16739. }
  16740. };
  16741. // Pointers handling
  16742. /**
  16743. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16744. * @param attachUp defines if you want to attach events to pointerup
  16745. * @param attachDown defines if you want to attach events to pointerdown
  16746. * @param attachMove defines if you want to attach events to pointermove
  16747. */
  16748. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16749. var _this = this;
  16750. if (attachUp === void 0) { attachUp = true; }
  16751. if (attachDown === void 0) { attachDown = true; }
  16752. if (attachMove === void 0) { attachMove = true; }
  16753. var spritePredicate = function (sprite) {
  16754. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16755. };
  16756. this._onPointerMove = function (evt) {
  16757. _this._updatePointerPosition(evt);
  16758. // PreObservable support
  16759. if (_this.onPrePointerObservable.hasObservers()) {
  16760. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  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. var canvas = _this._engine.getRenderingCanvas();
  16771. if (!_this.pointerMovePredicate) {
  16772. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16773. }
  16774. // Meshes
  16775. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16776. if (pickResult.hit && pickResult.pickedMesh) {
  16777. _this.setPointerOverSprite(null);
  16778. _this.setPointerOverMesh(pickResult.pickedMesh);
  16779. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16780. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16781. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16782. }
  16783. else {
  16784. canvas.style.cursor = _this.hoverCursor;
  16785. }
  16786. }
  16787. else {
  16788. canvas.style.cursor = "";
  16789. }
  16790. }
  16791. else {
  16792. _this.setPointerOverMesh(null);
  16793. // Sprites
  16794. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16795. if (pickResult.hit && pickResult.pickedSprite) {
  16796. _this.setPointerOverSprite(pickResult.pickedSprite);
  16797. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16798. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16799. }
  16800. else {
  16801. canvas.style.cursor = _this.hoverCursor;
  16802. }
  16803. }
  16804. else {
  16805. _this.setPointerOverSprite(null);
  16806. // Restore pointer
  16807. canvas.style.cursor = "";
  16808. }
  16809. }
  16810. if (_this.onPointerMove) {
  16811. _this.onPointerMove(evt, pickResult);
  16812. }
  16813. if (_this.onPointerObservable.hasObservers()) {
  16814. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16815. var pi = new PointerInfo(type, evt, pickResult);
  16816. _this.onPointerObservable.notifyObservers(pi, type);
  16817. }
  16818. };
  16819. this._onPointerDown = function (evt) {
  16820. _this._updatePointerPosition(evt);
  16821. // PreObservable support
  16822. if (_this.onPrePointerObservable.hasObservers()) {
  16823. var type = PointerEventTypes.POINTERDOWN;
  16824. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16825. _this.onPrePointerObservable.notifyObservers(pi, type);
  16826. if (pi.skipOnPointerObservable) {
  16827. return;
  16828. }
  16829. }
  16830. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16831. return;
  16832. }
  16833. _this._startingPointerPosition.x = _this._pointerX;
  16834. _this._startingPointerPosition.y = _this._pointerY;
  16835. _this._startingPointerTime = new Date().getTime();
  16836. if (!_this.pointerDownPredicate) {
  16837. _this.pointerDownPredicate = function (mesh) {
  16838. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16839. };
  16840. }
  16841. // Meshes
  16842. _this._pickedDownMesh = null;
  16843. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16844. if (pickResult.hit && pickResult.pickedMesh) {
  16845. if (pickResult.pickedMesh.actionManager) {
  16846. _this._pickedDownMesh = pickResult.pickedMesh;
  16847. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16848. switch (evt.button) {
  16849. case 0:
  16850. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16851. break;
  16852. case 1:
  16853. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16854. break;
  16855. case 2:
  16856. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16857. break;
  16858. }
  16859. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16860. }
  16861. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16862. var that = _this;
  16863. window.setTimeout(function () {
  16864. 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);
  16865. if (pickResult.hit && pickResult.pickedMesh) {
  16866. if (pickResult.pickedMesh.actionManager) {
  16867. 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)) {
  16868. that._startingPointerTime = 0;
  16869. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16870. }
  16871. }
  16872. }
  16873. }, BABYLON.ActionManager.LongPressDelay);
  16874. }
  16875. }
  16876. }
  16877. if (_this.onPointerDown) {
  16878. _this.onPointerDown(evt, pickResult);
  16879. }
  16880. if (_this.onPointerObservable.hasObservers()) {
  16881. var type = PointerEventTypes.POINTERDOWN;
  16882. var pi = new PointerInfo(type, evt, pickResult);
  16883. _this.onPointerObservable.notifyObservers(pi, type);
  16884. }
  16885. // Sprites
  16886. _this._pickedDownSprite = null;
  16887. if (_this.spriteManagers.length > 0) {
  16888. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16889. if (pickResult.hit && pickResult.pickedSprite) {
  16890. if (pickResult.pickedSprite.actionManager) {
  16891. _this._pickedDownSprite = pickResult.pickedSprite;
  16892. switch (evt.button) {
  16893. case 0:
  16894. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16895. break;
  16896. case 1:
  16897. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16898. break;
  16899. case 2:
  16900. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16901. break;
  16902. }
  16903. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16904. }
  16905. }
  16906. }
  16907. };
  16908. this._onPointerUp = function (evt) {
  16909. _this._updatePointerPosition(evt);
  16910. // PreObservable support
  16911. if (_this.onPrePointerObservable.hasObservers()) {
  16912. var type = PointerEventTypes.POINTERUP;
  16913. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16914. _this.onPrePointerObservable.notifyObservers(pi, type);
  16915. if (pi.skipOnPointerObservable) {
  16916. return;
  16917. }
  16918. }
  16919. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16920. return;
  16921. }
  16922. if (!_this.pointerUpPredicate) {
  16923. _this.pointerUpPredicate = function (mesh) {
  16924. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16925. };
  16926. }
  16927. // Meshes
  16928. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16929. if (pickResult.hit && pickResult.pickedMesh) {
  16930. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16931. if (_this.onPointerPick) {
  16932. _this.onPointerPick(evt, pickResult);
  16933. }
  16934. if (_this.onPointerObservable.hasObservers()) {
  16935. var type = PointerEventTypes.POINTERPICK;
  16936. var pi = new PointerInfo(type, evt, pickResult);
  16937. _this.onPointerObservable.notifyObservers(pi, type);
  16938. }
  16939. }
  16940. if (pickResult.pickedMesh.actionManager) {
  16941. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16942. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16943. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16944. }
  16945. }
  16946. }
  16947. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16948. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16949. }
  16950. if (_this.onPointerUp) {
  16951. _this.onPointerUp(evt, pickResult);
  16952. }
  16953. if (_this.onPointerObservable.hasObservers()) {
  16954. var type = PointerEventTypes.POINTERUP;
  16955. var pi = new PointerInfo(type, evt, pickResult);
  16956. _this.onPointerObservable.notifyObservers(pi, type);
  16957. }
  16958. _this._startingPointerTime = 0;
  16959. // Sprites
  16960. if (_this.spriteManagers.length > 0) {
  16961. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16962. if (pickResult.hit && pickResult.pickedSprite) {
  16963. if (pickResult.pickedSprite.actionManager) {
  16964. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16965. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16966. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16967. }
  16968. }
  16969. }
  16970. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16971. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16972. }
  16973. }
  16974. };
  16975. this._onKeyDown = function (evt) {
  16976. if (_this.actionManager) {
  16977. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16978. }
  16979. };
  16980. this._onKeyUp = function (evt) {
  16981. if (_this.actionManager) {
  16982. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16983. }
  16984. };
  16985. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16986. var canvas = this._engine.getRenderingCanvas();
  16987. if (attachMove) {
  16988. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16989. // Wheel
  16990. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16991. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16992. }
  16993. if (attachDown) {
  16994. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16995. }
  16996. if (attachUp) {
  16997. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16998. }
  16999. canvas.tabIndex = 1;
  17000. canvas.addEventListener("keydown", this._onKeyDown, false);
  17001. canvas.addEventListener("keyup", this._onKeyUp, false);
  17002. };
  17003. Scene.prototype.detachControl = function () {
  17004. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17005. var canvas = this._engine.getRenderingCanvas();
  17006. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17007. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17008. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17009. // Wheel
  17010. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17011. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17012. canvas.removeEventListener("keydown", this._onKeyDown);
  17013. canvas.removeEventListener("keyup", this._onKeyUp);
  17014. };
  17015. // Ready
  17016. Scene.prototype.isReady = function () {
  17017. if (this._pendingData.length > 0) {
  17018. return false;
  17019. }
  17020. var index;
  17021. for (index = 0; index < this._geometries.length; index++) {
  17022. var geometry = this._geometries[index];
  17023. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17024. return false;
  17025. }
  17026. }
  17027. for (index = 0; index < this.meshes.length; index++) {
  17028. var mesh = this.meshes[index];
  17029. if (!mesh.isReady()) {
  17030. return false;
  17031. }
  17032. var mat = mesh.material;
  17033. if (mat) {
  17034. if (!mat.isReady(mesh)) {
  17035. return false;
  17036. }
  17037. }
  17038. }
  17039. return true;
  17040. };
  17041. Scene.prototype.resetCachedMaterial = function () {
  17042. this._cachedMaterial = null;
  17043. };
  17044. Scene.prototype.registerBeforeRender = function (func) {
  17045. this.onBeforeRenderObservable.add(func);
  17046. };
  17047. Scene.prototype.unregisterBeforeRender = function (func) {
  17048. this.onBeforeRenderObservable.removeCallback(func);
  17049. };
  17050. Scene.prototype.registerAfterRender = function (func) {
  17051. this.onAfterRenderObservable.add(func);
  17052. };
  17053. Scene.prototype.unregisterAfterRender = function (func) {
  17054. this.onAfterRenderObservable.removeCallback(func);
  17055. };
  17056. Scene.prototype._addPendingData = function (data) {
  17057. this._pendingData.push(data);
  17058. };
  17059. Scene.prototype._removePendingData = function (data) {
  17060. var index = this._pendingData.indexOf(data);
  17061. if (index !== -1) {
  17062. this._pendingData.splice(index, 1);
  17063. }
  17064. };
  17065. Scene.prototype.getWaitingItemsCount = function () {
  17066. return this._pendingData.length;
  17067. };
  17068. /**
  17069. * Registers a function to be executed when the scene is ready.
  17070. * @param {Function} func - the function to be executed.
  17071. */
  17072. Scene.prototype.executeWhenReady = function (func) {
  17073. var _this = this;
  17074. this.onReadyObservable.add(func);
  17075. if (this._executeWhenReadyTimeoutId !== -1) {
  17076. return;
  17077. }
  17078. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17079. _this._checkIsReady();
  17080. }, 150);
  17081. };
  17082. Scene.prototype._checkIsReady = function () {
  17083. var _this = this;
  17084. if (this.isReady()) {
  17085. this.onReadyObservable.notifyObservers(this);
  17086. this.onReadyObservable.clear();
  17087. this._executeWhenReadyTimeoutId = -1;
  17088. return;
  17089. }
  17090. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17091. _this._checkIsReady();
  17092. }, 150);
  17093. };
  17094. // Animations
  17095. /**
  17096. * Will start the animation sequence of a given target
  17097. * @param target - the target
  17098. * @param {number} from - from which frame should animation start
  17099. * @param {number} to - till which frame should animation run.
  17100. * @param {boolean} [loop] - should the animation loop
  17101. * @param {number} [speedRatio] - the speed in which to run the animation
  17102. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17103. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17104. * @return {BABYLON.Animatable} the animatable object created for this animation
  17105. * @see BABYLON.Animatable
  17106. * @see http://doc.babylonjs.com/page.php?p=22081
  17107. */
  17108. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17109. if (speedRatio === void 0) { speedRatio = 1.0; }
  17110. this.stopAnimation(target);
  17111. if (!animatable) {
  17112. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17113. }
  17114. // Local animations
  17115. if (target.animations) {
  17116. animatable.appendAnimations(target, target.animations);
  17117. }
  17118. // Children animations
  17119. if (target.getAnimatables) {
  17120. var animatables = target.getAnimatables();
  17121. for (var index = 0; index < animatables.length; index++) {
  17122. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17123. }
  17124. }
  17125. animatable.reset();
  17126. return animatable;
  17127. };
  17128. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17129. if (speedRatio === undefined) {
  17130. speedRatio = 1.0;
  17131. }
  17132. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17133. return animatable;
  17134. };
  17135. Scene.prototype.getAnimatableByTarget = function (target) {
  17136. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17137. if (this._activeAnimatables[index].target === target) {
  17138. return this._activeAnimatables[index];
  17139. }
  17140. }
  17141. return null;
  17142. };
  17143. Object.defineProperty(Scene.prototype, "Animatables", {
  17144. get: function () {
  17145. return this._activeAnimatables;
  17146. },
  17147. enumerable: true,
  17148. configurable: true
  17149. });
  17150. /**
  17151. * Will stop the animation of the given target
  17152. * @param target - the target
  17153. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17154. * @see beginAnimation
  17155. */
  17156. Scene.prototype.stopAnimation = function (target, animationName) {
  17157. var animatable = this.getAnimatableByTarget(target);
  17158. if (animatable) {
  17159. animatable.stop(animationName);
  17160. }
  17161. };
  17162. Scene.prototype._animate = function () {
  17163. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17164. return;
  17165. }
  17166. if (!this._animationStartDate) {
  17167. if (this._pendingData.length > 0) {
  17168. return;
  17169. }
  17170. this._animationStartDate = BABYLON.Tools.Now;
  17171. }
  17172. // Getting time
  17173. var now = BABYLON.Tools.Now;
  17174. var delay = now - this._animationStartDate;
  17175. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17176. this._activeAnimatables[index]._animate(delay);
  17177. }
  17178. };
  17179. // Matrix
  17180. Scene.prototype.getViewMatrix = function () {
  17181. return this._viewMatrix;
  17182. };
  17183. Scene.prototype.getProjectionMatrix = function () {
  17184. return this._projectionMatrix;
  17185. };
  17186. Scene.prototype.getTransformMatrix = function () {
  17187. return this._transformMatrix;
  17188. };
  17189. Scene.prototype.setTransformMatrix = function (view, projection) {
  17190. this._viewMatrix = view;
  17191. this._projectionMatrix = projection;
  17192. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17193. // Update frustum
  17194. if (!this._frustumPlanes) {
  17195. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17196. }
  17197. else {
  17198. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17199. }
  17200. };
  17201. // Methods
  17202. Scene.prototype.addMesh = function (newMesh) {
  17203. newMesh.uniqueId = this._uniqueIdCounter++;
  17204. var position = this.meshes.push(newMesh);
  17205. //notify the collision coordinator
  17206. this.collisionCoordinator.onMeshAdded(newMesh);
  17207. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17208. };
  17209. Scene.prototype.removeMesh = function (toRemove) {
  17210. var index = this.meshes.indexOf(toRemove);
  17211. if (index !== -1) {
  17212. // Remove from the scene if mesh found
  17213. this.meshes.splice(index, 1);
  17214. }
  17215. //notify the collision coordinator
  17216. this.collisionCoordinator.onMeshRemoved(toRemove);
  17217. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17218. return index;
  17219. };
  17220. Scene.prototype.removeSkeleton = function (toRemove) {
  17221. var index = this.skeletons.indexOf(toRemove);
  17222. if (index !== -1) {
  17223. // Remove from the scene if mesh found
  17224. this.skeletons.splice(index, 1);
  17225. }
  17226. return index;
  17227. };
  17228. Scene.prototype.removeLight = function (toRemove) {
  17229. var index = this.lights.indexOf(toRemove);
  17230. if (index !== -1) {
  17231. // Remove from the scene if mesh found
  17232. this.lights.splice(index, 1);
  17233. }
  17234. this.onLightRemovedObservable.notifyObservers(toRemove);
  17235. return index;
  17236. };
  17237. Scene.prototype.removeCamera = function (toRemove) {
  17238. var index = this.cameras.indexOf(toRemove);
  17239. if (index !== -1) {
  17240. // Remove from the scene if mesh found
  17241. this.cameras.splice(index, 1);
  17242. }
  17243. // Remove from activeCameras
  17244. var index2 = this.activeCameras.indexOf(toRemove);
  17245. if (index2 !== -1) {
  17246. // Remove from the scene if mesh found
  17247. this.activeCameras.splice(index2, 1);
  17248. }
  17249. // Reset the activeCamera
  17250. if (this.activeCamera === toRemove) {
  17251. if (this.cameras.length > 0) {
  17252. this.activeCamera = this.cameras[0];
  17253. }
  17254. else {
  17255. this.activeCamera = null;
  17256. }
  17257. }
  17258. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17259. return index;
  17260. };
  17261. Scene.prototype.addLight = function (newLight) {
  17262. newLight.uniqueId = this._uniqueIdCounter++;
  17263. var position = this.lights.push(newLight);
  17264. this.onNewLightAddedObservable.notifyObservers(newLight);
  17265. };
  17266. Scene.prototype.addCamera = function (newCamera) {
  17267. newCamera.uniqueId = this._uniqueIdCounter++;
  17268. var position = this.cameras.push(newCamera);
  17269. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17270. };
  17271. /**
  17272. * Switch active camera
  17273. * @param {Camera} newCamera - new active camera
  17274. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17275. */
  17276. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17277. if (attachControl === void 0) { attachControl = true; }
  17278. var canvas = this._engine.getRenderingCanvas();
  17279. this.activeCamera.detachControl(canvas);
  17280. this.activeCamera = newCamera;
  17281. if (attachControl) {
  17282. newCamera.attachControl(canvas);
  17283. }
  17284. };
  17285. /**
  17286. * sets the active camera of the scene using its ID
  17287. * @param {string} id - the camera's ID
  17288. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17289. * @see activeCamera
  17290. */
  17291. Scene.prototype.setActiveCameraByID = function (id) {
  17292. var camera = this.getCameraByID(id);
  17293. if (camera) {
  17294. this.activeCamera = camera;
  17295. return camera;
  17296. }
  17297. return null;
  17298. };
  17299. /**
  17300. * sets the active camera of the scene using its name
  17301. * @param {string} name - the camera's name
  17302. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17303. * @see activeCamera
  17304. */
  17305. Scene.prototype.setActiveCameraByName = function (name) {
  17306. var camera = this.getCameraByName(name);
  17307. if (camera) {
  17308. this.activeCamera = camera;
  17309. return camera;
  17310. }
  17311. return null;
  17312. };
  17313. /**
  17314. * get a material using its id
  17315. * @param {string} the material's ID
  17316. * @return {BABYLON.Material|null} the material or null if none found.
  17317. */
  17318. Scene.prototype.getMaterialByID = function (id) {
  17319. for (var index = 0; index < this.materials.length; index++) {
  17320. if (this.materials[index].id === id) {
  17321. return this.materials[index];
  17322. }
  17323. }
  17324. return null;
  17325. };
  17326. /**
  17327. * get a material using its name
  17328. * @param {string} the material's name
  17329. * @return {BABYLON.Material|null} the material or null if none found.
  17330. */
  17331. Scene.prototype.getMaterialByName = function (name) {
  17332. for (var index = 0; index < this.materials.length; index++) {
  17333. if (this.materials[index].name === name) {
  17334. return this.materials[index];
  17335. }
  17336. }
  17337. return null;
  17338. };
  17339. Scene.prototype.getLensFlareSystemByName = function (name) {
  17340. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17341. if (this.lensFlareSystems[index].name === name) {
  17342. return this.lensFlareSystems[index];
  17343. }
  17344. }
  17345. return null;
  17346. };
  17347. Scene.prototype.getLensFlareSystemByID = function (id) {
  17348. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17349. if (this.lensFlareSystems[index].id === id) {
  17350. return this.lensFlareSystems[index];
  17351. }
  17352. }
  17353. return null;
  17354. };
  17355. Scene.prototype.getCameraByID = function (id) {
  17356. for (var index = 0; index < this.cameras.length; index++) {
  17357. if (this.cameras[index].id === id) {
  17358. return this.cameras[index];
  17359. }
  17360. }
  17361. return null;
  17362. };
  17363. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17364. for (var index = 0; index < this.cameras.length; index++) {
  17365. if (this.cameras[index].uniqueId === uniqueId) {
  17366. return this.cameras[index];
  17367. }
  17368. }
  17369. return null;
  17370. };
  17371. /**
  17372. * get a camera using its name
  17373. * @param {string} the camera's name
  17374. * @return {BABYLON.Camera|null} the camera or null if none found.
  17375. */
  17376. Scene.prototype.getCameraByName = function (name) {
  17377. for (var index = 0; index < this.cameras.length; index++) {
  17378. if (this.cameras[index].name === name) {
  17379. return this.cameras[index];
  17380. }
  17381. }
  17382. return null;
  17383. };
  17384. /**
  17385. * get a bone using its id
  17386. * @param {string} the bone's id
  17387. * @return {BABYLON.Bone|null} the bone or null if not found
  17388. */
  17389. Scene.prototype.getBoneByID = function (id) {
  17390. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17391. var skeleton = this.skeletons[skeletonIndex];
  17392. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17393. if (skeleton.bones[boneIndex].id === id) {
  17394. return skeleton.bones[boneIndex];
  17395. }
  17396. }
  17397. }
  17398. return null;
  17399. };
  17400. /**
  17401. * get a bone using its id
  17402. * @param {string} the bone's name
  17403. * @return {BABYLON.Bone|null} the bone or null if not found
  17404. */
  17405. Scene.prototype.getBoneByName = function (name) {
  17406. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17407. var skeleton = this.skeletons[skeletonIndex];
  17408. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17409. if (skeleton.bones[boneIndex].name === name) {
  17410. return skeleton.bones[boneIndex];
  17411. }
  17412. }
  17413. }
  17414. return null;
  17415. };
  17416. /**
  17417. * get a light node using its name
  17418. * @param {string} the light's name
  17419. * @return {BABYLON.Light|null} the light or null if none found.
  17420. */
  17421. Scene.prototype.getLightByName = function (name) {
  17422. for (var index = 0; index < this.lights.length; index++) {
  17423. if (this.lights[index].name === name) {
  17424. return this.lights[index];
  17425. }
  17426. }
  17427. return null;
  17428. };
  17429. /**
  17430. * get a light node using its ID
  17431. * @param {string} the light's id
  17432. * @return {BABYLON.Light|null} the light or null if none found.
  17433. */
  17434. Scene.prototype.getLightByID = function (id) {
  17435. for (var index = 0; index < this.lights.length; index++) {
  17436. if (this.lights[index].id === id) {
  17437. return this.lights[index];
  17438. }
  17439. }
  17440. return null;
  17441. };
  17442. /**
  17443. * get a light node using its scene-generated unique ID
  17444. * @param {number} the light's unique id
  17445. * @return {BABYLON.Light|null} the light or null if none found.
  17446. */
  17447. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17448. for (var index = 0; index < this.lights.length; index++) {
  17449. if (this.lights[index].uniqueId === uniqueId) {
  17450. return this.lights[index];
  17451. }
  17452. }
  17453. return null;
  17454. };
  17455. /**
  17456. * get a particle system by id
  17457. * @param id {number} the particle system id
  17458. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17459. */
  17460. Scene.prototype.getParticleSystemByID = function (id) {
  17461. for (var index = 0; index < this.particleSystems.length; index++) {
  17462. if (this.particleSystems[index].id === id) {
  17463. return this.particleSystems[index];
  17464. }
  17465. }
  17466. return null;
  17467. };
  17468. /**
  17469. * get a geometry using its ID
  17470. * @param {string} the geometry's id
  17471. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17472. */
  17473. Scene.prototype.getGeometryByID = function (id) {
  17474. for (var index = 0; index < this._geometries.length; index++) {
  17475. if (this._geometries[index].id === id) {
  17476. return this._geometries[index];
  17477. }
  17478. }
  17479. return null;
  17480. };
  17481. /**
  17482. * add a new geometry to this scene.
  17483. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17484. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17485. * @return {boolean} was the geometry added or not
  17486. */
  17487. Scene.prototype.pushGeometry = function (geometry, force) {
  17488. if (!force && this.getGeometryByID(geometry.id)) {
  17489. return false;
  17490. }
  17491. this._geometries.push(geometry);
  17492. //notify the collision coordinator
  17493. this.collisionCoordinator.onGeometryAdded(geometry);
  17494. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17495. return true;
  17496. };
  17497. /**
  17498. * Removes an existing geometry
  17499. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17500. * @return {boolean} was the geometry removed or not
  17501. */
  17502. Scene.prototype.removeGeometry = function (geometry) {
  17503. var index = this._geometries.indexOf(geometry);
  17504. if (index > -1) {
  17505. this._geometries.splice(index, 1);
  17506. //notify the collision coordinator
  17507. this.collisionCoordinator.onGeometryDeleted(geometry);
  17508. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17509. return true;
  17510. }
  17511. return false;
  17512. };
  17513. Scene.prototype.getGeometries = function () {
  17514. return this._geometries;
  17515. };
  17516. /**
  17517. * Get the first added mesh found of a given ID
  17518. * @param {string} id - the id to search for
  17519. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17520. */
  17521. Scene.prototype.getMeshByID = function (id) {
  17522. for (var index = 0; index < this.meshes.length; index++) {
  17523. if (this.meshes[index].id === id) {
  17524. return this.meshes[index];
  17525. }
  17526. }
  17527. return null;
  17528. };
  17529. Scene.prototype.getMeshesByID = function (id) {
  17530. return this.meshes.filter(function (m) {
  17531. return m.id === id;
  17532. });
  17533. };
  17534. /**
  17535. * Get a mesh with its auto-generated unique id
  17536. * @param {number} uniqueId - the unique id to search for
  17537. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17538. */
  17539. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17540. for (var index = 0; index < this.meshes.length; index++) {
  17541. if (this.meshes[index].uniqueId === uniqueId) {
  17542. return this.meshes[index];
  17543. }
  17544. }
  17545. return null;
  17546. };
  17547. /**
  17548. * Get a the last added mesh found of a given ID
  17549. * @param {string} id - the id to search for
  17550. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17551. */
  17552. Scene.prototype.getLastMeshByID = function (id) {
  17553. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17554. if (this.meshes[index].id === id) {
  17555. return this.meshes[index];
  17556. }
  17557. }
  17558. return null;
  17559. };
  17560. /**
  17561. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17562. * @param {string} id - the id to search for
  17563. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17564. */
  17565. Scene.prototype.getLastEntryByID = function (id) {
  17566. var index;
  17567. for (index = this.meshes.length - 1; index >= 0; index--) {
  17568. if (this.meshes[index].id === id) {
  17569. return this.meshes[index];
  17570. }
  17571. }
  17572. for (index = this.cameras.length - 1; index >= 0; index--) {
  17573. if (this.cameras[index].id === id) {
  17574. return this.cameras[index];
  17575. }
  17576. }
  17577. for (index = this.lights.length - 1; index >= 0; index--) {
  17578. if (this.lights[index].id === id) {
  17579. return this.lights[index];
  17580. }
  17581. }
  17582. return null;
  17583. };
  17584. Scene.prototype.getNodeByID = function (id) {
  17585. var mesh = this.getMeshByID(id);
  17586. if (mesh) {
  17587. return mesh;
  17588. }
  17589. var light = this.getLightByID(id);
  17590. if (light) {
  17591. return light;
  17592. }
  17593. var camera = this.getCameraByID(id);
  17594. if (camera) {
  17595. return camera;
  17596. }
  17597. var bone = this.getBoneByID(id);
  17598. return bone;
  17599. };
  17600. Scene.prototype.getNodeByName = function (name) {
  17601. var mesh = this.getMeshByName(name);
  17602. if (mesh) {
  17603. return mesh;
  17604. }
  17605. var light = this.getLightByName(name);
  17606. if (light) {
  17607. return light;
  17608. }
  17609. var camera = this.getCameraByName(name);
  17610. if (camera) {
  17611. return camera;
  17612. }
  17613. var bone = this.getBoneByName(name);
  17614. return bone;
  17615. };
  17616. Scene.prototype.getMeshByName = function (name) {
  17617. for (var index = 0; index < this.meshes.length; index++) {
  17618. if (this.meshes[index].name === name) {
  17619. return this.meshes[index];
  17620. }
  17621. }
  17622. return null;
  17623. };
  17624. Scene.prototype.getSoundByName = function (name) {
  17625. var index;
  17626. if (BABYLON.AudioEngine) {
  17627. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17628. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17629. return this.mainSoundTrack.soundCollection[index];
  17630. }
  17631. }
  17632. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17633. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17634. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17635. return this.soundTracks[sdIndex].soundCollection[index];
  17636. }
  17637. }
  17638. }
  17639. }
  17640. return null;
  17641. };
  17642. Scene.prototype.getLastSkeletonByID = function (id) {
  17643. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17644. if (this.skeletons[index].id === id) {
  17645. return this.skeletons[index];
  17646. }
  17647. }
  17648. return null;
  17649. };
  17650. Scene.prototype.getSkeletonById = function (id) {
  17651. for (var index = 0; index < this.skeletons.length; index++) {
  17652. if (this.skeletons[index].id === id) {
  17653. return this.skeletons[index];
  17654. }
  17655. }
  17656. return null;
  17657. };
  17658. Scene.prototype.getSkeletonByName = function (name) {
  17659. for (var index = 0; index < this.skeletons.length; index++) {
  17660. if (this.skeletons[index].name === name) {
  17661. return this.skeletons[index];
  17662. }
  17663. }
  17664. return null;
  17665. };
  17666. Scene.prototype.isActiveMesh = function (mesh) {
  17667. return (this._activeMeshes.indexOf(mesh) !== -1);
  17668. };
  17669. Object.defineProperty(Scene.prototype, "uid", {
  17670. /**
  17671. * Return a unique id as a string which can serve as an identifier for the scene
  17672. */
  17673. get: function () {
  17674. if (!this._uid) {
  17675. this._uid = BABYLON.Tools.RandomId();
  17676. }
  17677. return this._uid;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. /**
  17683. * Add an externaly attached data from its key.
  17684. * This method call will fail and return false, if such key already exists.
  17685. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17686. * @param key the unique key that identifies the data
  17687. * @param data the data object to associate to the key for this Engine instance
  17688. * @return true if no such key were already present and the data was added successfully, false otherwise
  17689. */
  17690. Scene.prototype.addExternalData = function (key, data) {
  17691. return this._externalData.add(key, data);
  17692. };
  17693. /**
  17694. * Get an externaly attached data from its key
  17695. * @param key the unique key that identifies the data
  17696. * @return the associated data, if present (can be null), or undefined if not present
  17697. */
  17698. Scene.prototype.getExternalData = function (key) {
  17699. return this._externalData.get(key);
  17700. };
  17701. /**
  17702. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17703. * @param key the unique key that identifies the data
  17704. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17705. * @return the associated data, can be null if the factory returned null.
  17706. */
  17707. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17708. return this._externalData.getOrAddWithFactory(key, factory);
  17709. };
  17710. /**
  17711. * Remove an externaly attached data from the Engine instance
  17712. * @param key the unique key that identifies the data
  17713. * @return true if the data was successfully removed, false if it doesn't exist
  17714. */
  17715. Scene.prototype.removeExternalData = function (key) {
  17716. return this._externalData.remove(key);
  17717. };
  17718. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17719. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17720. var material = subMesh.getMaterial();
  17721. if (mesh.showSubMeshesBoundingBox) {
  17722. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17723. }
  17724. if (material) {
  17725. // Render targets
  17726. if (material.getRenderTargetTextures) {
  17727. if (this._processedMaterials.indexOf(material) === -1) {
  17728. this._processedMaterials.push(material);
  17729. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17730. }
  17731. }
  17732. // Dispatch
  17733. this._activeIndices.addCount(subMesh.indexCount, false);
  17734. this._renderingManager.dispatch(subMesh);
  17735. }
  17736. }
  17737. };
  17738. Scene.prototype._isInIntermediateRendering = function () {
  17739. return this._intermediateRendering;
  17740. };
  17741. Scene.prototype._evaluateActiveMeshes = function () {
  17742. this.activeCamera._activeMeshes.reset();
  17743. this._activeMeshes.reset();
  17744. this._renderingManager.reset();
  17745. this._processedMaterials.reset();
  17746. this._activeParticleSystems.reset();
  17747. this._activeSkeletons.reset();
  17748. this._softwareSkinnedMeshes.reset();
  17749. this._boundingBoxRenderer.reset();
  17750. this._edgesRenderers.reset();
  17751. // Meshes
  17752. var meshes;
  17753. var len;
  17754. if (this._selectionOctree) {
  17755. var selection = this._selectionOctree.select(this._frustumPlanes);
  17756. meshes = selection.data;
  17757. len = selection.length;
  17758. }
  17759. else {
  17760. len = this.meshes.length;
  17761. meshes = this.meshes;
  17762. }
  17763. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17764. var mesh = meshes[meshIndex];
  17765. if (mesh.isBlocked) {
  17766. continue;
  17767. }
  17768. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17769. if (!mesh.isReady() || !mesh.isEnabled()) {
  17770. continue;
  17771. }
  17772. mesh.computeWorldMatrix();
  17773. // Intersections
  17774. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17775. this._meshesForIntersections.pushNoDuplicate(mesh);
  17776. }
  17777. // Switch to current LOD
  17778. var meshLOD = mesh.getLOD(this.activeCamera);
  17779. if (!meshLOD) {
  17780. continue;
  17781. }
  17782. mesh._preActivate();
  17783. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17784. this._activeMeshes.push(mesh);
  17785. this.activeCamera._activeMeshes.push(mesh);
  17786. mesh._activate(this._renderId);
  17787. this._activeMesh(mesh, meshLOD);
  17788. }
  17789. }
  17790. // Particle systems
  17791. this._particlesDuration.beginMonitoring();
  17792. var beforeParticlesDate = BABYLON.Tools.Now;
  17793. if (this.particlesEnabled) {
  17794. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17795. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17796. var particleSystem = this.particleSystems[particleIndex];
  17797. if (!particleSystem.isStarted()) {
  17798. continue;
  17799. }
  17800. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17801. this._activeParticleSystems.push(particleSystem);
  17802. particleSystem.animate();
  17803. }
  17804. }
  17805. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17806. }
  17807. this._particlesDuration.endMonitoring(false);
  17808. };
  17809. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17810. if (mesh.skeleton && this.skeletonsEnabled) {
  17811. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17812. mesh.skeleton.prepare();
  17813. }
  17814. if (!mesh.computeBonesUsingShaders) {
  17815. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17816. }
  17817. }
  17818. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17819. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17820. }
  17821. if (sourceMesh._edgesRenderer) {
  17822. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17823. }
  17824. if (mesh && mesh.subMeshes) {
  17825. // Submeshes Octrees
  17826. var len;
  17827. var subMeshes;
  17828. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17829. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17830. len = intersections.length;
  17831. subMeshes = intersections.data;
  17832. }
  17833. else {
  17834. subMeshes = mesh.subMeshes;
  17835. len = subMeshes.length;
  17836. }
  17837. for (var subIndex = 0; subIndex < len; subIndex++) {
  17838. var subMesh = subMeshes[subIndex];
  17839. this._evaluateSubMesh(subMesh, mesh);
  17840. }
  17841. }
  17842. };
  17843. Scene.prototype.updateTransformMatrix = function (force) {
  17844. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17845. };
  17846. Scene.prototype._renderForCamera = function (camera) {
  17847. var engine = this._engine;
  17848. var startTime = BABYLON.Tools.Now;
  17849. this.activeCamera = camera;
  17850. if (!this.activeCamera)
  17851. throw new Error("Active camera not set");
  17852. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17853. // Viewport
  17854. engine.setViewport(this.activeCamera.viewport);
  17855. // Camera
  17856. this.resetCachedMaterial();
  17857. this._renderId++;
  17858. this.updateTransformMatrix();
  17859. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17860. // Meshes
  17861. this._evaluateActiveMeshesDuration.beginMonitoring();
  17862. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17863. this._evaluateActiveMeshes();
  17864. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17865. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17866. // Software skinning
  17867. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17868. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17869. mesh.applySkeleton(mesh.skeleton);
  17870. }
  17871. // Render targets
  17872. this._renderTargetsDuration.beginMonitoring();
  17873. var needsRestoreFrameBuffer = false;
  17874. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17875. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17876. this._intermediateRendering = true;
  17877. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17878. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17879. var renderTarget = this._renderTargets.data[renderIndex];
  17880. if (renderTarget._shouldRender()) {
  17881. this._renderId++;
  17882. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17883. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17884. }
  17885. }
  17886. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17887. this._intermediateRendering = false;
  17888. this._renderId++;
  17889. needsRestoreFrameBuffer = true; // Restore back buffer
  17890. }
  17891. // Render HighlightLayer Texture
  17892. var stencilState = this._engine.getStencilBuffer();
  17893. var renderhighlights = false;
  17894. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17895. this._intermediateRendering = true;
  17896. for (var i = 0; i < this.highlightLayers.length; i++) {
  17897. var highlightLayer = this.highlightLayers[i];
  17898. if (highlightLayer.shouldRender() &&
  17899. (!highlightLayer.camera ||
  17900. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17901. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17902. renderhighlights = true;
  17903. var renderTarget = highlightLayer._mainTexture;
  17904. if (renderTarget._shouldRender()) {
  17905. this._renderId++;
  17906. renderTarget.render(false, false);
  17907. needsRestoreFrameBuffer = true;
  17908. }
  17909. }
  17910. }
  17911. this._intermediateRendering = false;
  17912. this._renderId++;
  17913. }
  17914. if (needsRestoreFrameBuffer) {
  17915. engine.restoreDefaultFramebuffer();
  17916. }
  17917. this._renderTargetsDuration.endMonitoring(false);
  17918. // Prepare Frame
  17919. this.postProcessManager._prepareFrame();
  17920. this._renderDuration.beginMonitoring();
  17921. // Backgrounds
  17922. var layerIndex;
  17923. var layer;
  17924. if (this.layers.length) {
  17925. engine.setDepthBuffer(false);
  17926. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17927. layer = this.layers[layerIndex];
  17928. if (layer.isBackground) {
  17929. layer.render();
  17930. }
  17931. }
  17932. engine.setDepthBuffer(true);
  17933. }
  17934. // Render
  17935. BABYLON.Tools.StartPerformanceCounter("Main render");
  17936. // Activate HighlightLayer stencil
  17937. if (renderhighlights) {
  17938. this._engine.setStencilBuffer(true);
  17939. }
  17940. this._renderingManager.render(null, null, true, true);
  17941. // Restore HighlightLayer stencil
  17942. if (renderhighlights) {
  17943. this._engine.setStencilBuffer(stencilState);
  17944. }
  17945. BABYLON.Tools.EndPerformanceCounter("Main render");
  17946. // Bounding boxes
  17947. this._boundingBoxRenderer.render();
  17948. // Edges
  17949. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17950. this._edgesRenderers.data[edgesRendererIndex].render();
  17951. }
  17952. // Lens flares
  17953. if (this.lensFlaresEnabled) {
  17954. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17955. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17956. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17957. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17958. lensFlareSystem.render();
  17959. }
  17960. }
  17961. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17962. }
  17963. // Foregrounds
  17964. if (this.layers.length) {
  17965. engine.setDepthBuffer(false);
  17966. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17967. layer = this.layers[layerIndex];
  17968. if (!layer.isBackground) {
  17969. layer.render();
  17970. }
  17971. }
  17972. engine.setDepthBuffer(true);
  17973. }
  17974. // Highlight Layer
  17975. if (renderhighlights) {
  17976. engine.setDepthBuffer(false);
  17977. for (var i = 0; i < this.highlightLayers.length; i++) {
  17978. if (this.highlightLayers[i].shouldRender()) {
  17979. this.highlightLayers[i].render();
  17980. }
  17981. }
  17982. engine.setDepthBuffer(true);
  17983. }
  17984. this._renderDuration.endMonitoring(false);
  17985. // Finalize frame
  17986. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17987. // Update camera
  17988. this.activeCamera._updateFromScene();
  17989. // Reset some special arrays
  17990. this._renderTargets.reset();
  17991. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17992. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17993. };
  17994. Scene.prototype._processSubCameras = function (camera) {
  17995. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17996. this._renderForCamera(camera);
  17997. return;
  17998. }
  17999. // rig cameras
  18000. for (var index = 0; index < camera._rigCameras.length; index++) {
  18001. this._renderForCamera(camera._rigCameras[index]);
  18002. }
  18003. this.activeCamera = camera;
  18004. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18005. // Update camera
  18006. this.activeCamera._updateFromScene();
  18007. };
  18008. Scene.prototype._checkIntersections = function () {
  18009. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18010. var sourceMesh = this._meshesForIntersections.data[index];
  18011. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18012. var action = sourceMesh.actionManager.actions[actionIndex];
  18013. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18014. var parameters = action.getTriggerParameter();
  18015. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18016. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18017. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18018. if (areIntersecting && currentIntersectionInProgress === -1) {
  18019. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18020. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18021. sourceMesh._intersectionsInProgress.push(otherMesh);
  18022. }
  18023. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18024. sourceMesh._intersectionsInProgress.push(otherMesh);
  18025. }
  18026. }
  18027. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18028. //They intersected, and now they don't.
  18029. //is this trigger an exit trigger? execute an event.
  18030. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18031. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18032. }
  18033. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18034. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18035. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18036. }
  18037. }
  18038. }
  18039. }
  18040. }
  18041. };
  18042. Scene.prototype.render = function () {
  18043. this._lastFrameDuration.beginMonitoring();
  18044. this._particlesDuration.fetchNewFrame();
  18045. this._spritesDuration.fetchNewFrame();
  18046. this._activeParticles.fetchNewFrame();
  18047. this._renderDuration.fetchNewFrame();
  18048. this._renderTargetsDuration.fetchNewFrame();
  18049. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18050. this._totalVertices.fetchNewFrame();
  18051. this._activeIndices.fetchNewFrame();
  18052. this._activeBones.fetchNewFrame();
  18053. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18054. this._meshesForIntersections.reset();
  18055. this.resetCachedMaterial();
  18056. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18057. // Actions
  18058. if (this.actionManager) {
  18059. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18060. }
  18061. //Simplification Queue
  18062. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18063. this.simplificationQueue.executeNext();
  18064. }
  18065. // Animations
  18066. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18067. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18068. this._animate();
  18069. // Physics
  18070. if (this._physicsEngine) {
  18071. BABYLON.Tools.StartPerformanceCounter("Physics");
  18072. this._physicsEngine._step(deltaTime / 1000.0);
  18073. BABYLON.Tools.EndPerformanceCounter("Physics");
  18074. }
  18075. // Before render
  18076. this.onBeforeRenderObservable.notifyObservers(this);
  18077. // Customs render targets
  18078. this._renderTargetsDuration.beginMonitoring();
  18079. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18080. var engine = this.getEngine();
  18081. var currentActiveCamera = this.activeCamera;
  18082. if (this.renderTargetsEnabled) {
  18083. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18084. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18085. var renderTarget = this.customRenderTargets[customIndex];
  18086. if (renderTarget._shouldRender()) {
  18087. this._renderId++;
  18088. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18089. if (!this.activeCamera)
  18090. throw new Error("Active camera not set");
  18091. // Viewport
  18092. engine.setViewport(this.activeCamera.viewport);
  18093. // Camera
  18094. this.updateTransformMatrix();
  18095. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18096. }
  18097. }
  18098. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18099. this._renderId++;
  18100. }
  18101. if (this.customRenderTargets.length > 0) {
  18102. engine.restoreDefaultFramebuffer();
  18103. }
  18104. this._renderTargetsDuration.endMonitoring();
  18105. this.activeCamera = currentActiveCamera;
  18106. // Procedural textures
  18107. if (this.proceduralTexturesEnabled) {
  18108. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18109. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18110. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18111. if (proceduralTexture._shouldRender()) {
  18112. proceduralTexture.render();
  18113. }
  18114. }
  18115. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18116. }
  18117. // Clear
  18118. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18119. // Shadows
  18120. if (this.shadowsEnabled) {
  18121. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18122. var light = this.lights[lightIndex];
  18123. var shadowGenerator = light.getShadowGenerator();
  18124. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18125. this._renderTargets.push(shadowGenerator.getShadowMap());
  18126. }
  18127. }
  18128. }
  18129. // Depth renderer
  18130. if (this._depthRenderer) {
  18131. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18132. }
  18133. // RenderPipeline
  18134. this.postProcessRenderPipelineManager.update();
  18135. // Multi-cameras?
  18136. if (this.activeCameras.length > 0) {
  18137. var currentRenderId = this._renderId;
  18138. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18139. this._renderId = currentRenderId;
  18140. if (cameraIndex > 0) {
  18141. this._engine.clear(0, false, true, true);
  18142. }
  18143. this._processSubCameras(this.activeCameras[cameraIndex]);
  18144. }
  18145. }
  18146. else {
  18147. if (!this.activeCamera) {
  18148. throw new Error("No camera defined");
  18149. }
  18150. this._processSubCameras(this.activeCamera);
  18151. }
  18152. // Intersection checks
  18153. this._checkIntersections();
  18154. // Update the audio listener attached to the camera
  18155. if (BABYLON.AudioEngine) {
  18156. this._updateAudioParameters();
  18157. }
  18158. // After render
  18159. if (this.afterRender) {
  18160. this.afterRender();
  18161. }
  18162. this.onAfterRenderObservable.notifyObservers(this);
  18163. // Cleaning
  18164. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18165. this._toBeDisposed.data[index].dispose();
  18166. this._toBeDisposed[index] = null;
  18167. }
  18168. this._toBeDisposed.reset();
  18169. if (this.dumpNextRenderTargets) {
  18170. this.dumpNextRenderTargets = false;
  18171. }
  18172. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18173. this._lastFrameDuration.endMonitoring();
  18174. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18175. this._totalLightsCounter.addCount(this.lights.length, true);
  18176. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18177. this._totalTexturesCounter.addCount(this.textures.length, true);
  18178. this._activeBones.addCount(0, true);
  18179. this._activeIndices.addCount(0, true);
  18180. this._activeParticles.addCount(0, true);
  18181. };
  18182. Scene.prototype._updateAudioParameters = function () {
  18183. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18184. return;
  18185. }
  18186. var listeningCamera;
  18187. var audioEngine = BABYLON.Engine.audioEngine;
  18188. if (this.activeCameras.length > 0) {
  18189. listeningCamera = this.activeCameras[0];
  18190. }
  18191. else {
  18192. listeningCamera = this.activeCamera;
  18193. }
  18194. if (listeningCamera && audioEngine.canUseWebAudio) {
  18195. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18196. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18197. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18198. cameraDirection.normalize();
  18199. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18200. var i;
  18201. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18202. var sound = this.mainSoundTrack.soundCollection[i];
  18203. if (sound.useCustomAttenuation) {
  18204. sound.updateDistanceFromListener();
  18205. }
  18206. }
  18207. for (i = 0; i < this.soundTracks.length; i++) {
  18208. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18209. sound = this.soundTracks[i].soundCollection[j];
  18210. if (sound.useCustomAttenuation) {
  18211. sound.updateDistanceFromListener();
  18212. }
  18213. }
  18214. }
  18215. }
  18216. };
  18217. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18218. // Audio
  18219. get: function () {
  18220. return this._audioEnabled;
  18221. },
  18222. set: function (value) {
  18223. this._audioEnabled = value;
  18224. if (BABYLON.AudioEngine) {
  18225. if (this._audioEnabled) {
  18226. this._enableAudio();
  18227. }
  18228. else {
  18229. this._disableAudio();
  18230. }
  18231. }
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Scene.prototype._disableAudio = function () {
  18237. var i;
  18238. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18239. this.mainSoundTrack.soundCollection[i].pause();
  18240. }
  18241. for (i = 0; i < this.soundTracks.length; i++) {
  18242. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18243. this.soundTracks[i].soundCollection[j].pause();
  18244. }
  18245. }
  18246. };
  18247. Scene.prototype._enableAudio = function () {
  18248. var i;
  18249. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18250. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18251. this.mainSoundTrack.soundCollection[i].play();
  18252. }
  18253. }
  18254. for (i = 0; i < this.soundTracks.length; i++) {
  18255. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18256. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18257. this.soundTracks[i].soundCollection[j].play();
  18258. }
  18259. }
  18260. }
  18261. };
  18262. Object.defineProperty(Scene.prototype, "headphone", {
  18263. get: function () {
  18264. return this._headphone;
  18265. },
  18266. set: function (value) {
  18267. this._headphone = value;
  18268. if (BABYLON.AudioEngine) {
  18269. if (this._headphone) {
  18270. this._switchAudioModeForHeadphones();
  18271. }
  18272. else {
  18273. this._switchAudioModeForNormalSpeakers();
  18274. }
  18275. }
  18276. },
  18277. enumerable: true,
  18278. configurable: true
  18279. });
  18280. Scene.prototype._switchAudioModeForHeadphones = function () {
  18281. this.mainSoundTrack.switchPanningModelToHRTF();
  18282. for (var i = 0; i < this.soundTracks.length; i++) {
  18283. this.soundTracks[i].switchPanningModelToHRTF();
  18284. }
  18285. };
  18286. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18287. this.mainSoundTrack.switchPanningModelToEqualPower();
  18288. for (var i = 0; i < this.soundTracks.length; i++) {
  18289. this.soundTracks[i].switchPanningModelToEqualPower();
  18290. }
  18291. };
  18292. Scene.prototype.enableDepthRenderer = function () {
  18293. if (this._depthRenderer) {
  18294. return this._depthRenderer;
  18295. }
  18296. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18297. return this._depthRenderer;
  18298. };
  18299. Scene.prototype.disableDepthRenderer = function () {
  18300. if (!this._depthRenderer) {
  18301. return;
  18302. }
  18303. this._depthRenderer.dispose();
  18304. this._depthRenderer = null;
  18305. };
  18306. Scene.prototype.freezeMaterials = function () {
  18307. for (var i = 0; i < this.materials.length; i++) {
  18308. this.materials[i].freeze();
  18309. }
  18310. };
  18311. Scene.prototype.unfreezeMaterials = function () {
  18312. for (var i = 0; i < this.materials.length; i++) {
  18313. this.materials[i].unfreeze();
  18314. }
  18315. };
  18316. Scene.prototype.dispose = function () {
  18317. this.beforeRender = null;
  18318. this.afterRender = null;
  18319. this.skeletons = [];
  18320. this._boundingBoxRenderer.dispose();
  18321. if (this._depthRenderer) {
  18322. this._depthRenderer.dispose();
  18323. }
  18324. // Debug layer
  18325. if (this._debugLayer) {
  18326. this._debugLayer.hide();
  18327. }
  18328. // Events
  18329. this.onDisposeObservable.notifyObservers(this);
  18330. this.onDisposeObservable.clear();
  18331. this.onBeforeRenderObservable.clear();
  18332. this.onAfterRenderObservable.clear();
  18333. this.detachControl();
  18334. // Release sounds & sounds tracks
  18335. if (BABYLON.AudioEngine) {
  18336. this.disposeSounds();
  18337. }
  18338. // Detach cameras
  18339. var canvas = this._engine.getRenderingCanvas();
  18340. var index;
  18341. for (index = 0; index < this.cameras.length; index++) {
  18342. this.cameras[index].detachControl(canvas);
  18343. }
  18344. // Release lights
  18345. while (this.lights.length) {
  18346. this.lights[0].dispose();
  18347. }
  18348. // Release meshes
  18349. while (this.meshes.length) {
  18350. this.meshes[0].dispose(true);
  18351. }
  18352. // Release cameras
  18353. while (this.cameras.length) {
  18354. this.cameras[0].dispose();
  18355. }
  18356. // Release materials
  18357. while (this.materials.length) {
  18358. this.materials[0].dispose();
  18359. }
  18360. // Release particles
  18361. while (this.particleSystems.length) {
  18362. this.particleSystems[0].dispose();
  18363. }
  18364. // Release sprites
  18365. while (this.spriteManagers.length) {
  18366. this.spriteManagers[0].dispose();
  18367. }
  18368. // Release layers
  18369. while (this.layers.length) {
  18370. this.layers[0].dispose();
  18371. }
  18372. while (this.highlightLayers.length) {
  18373. this.highlightLayers[0].dispose();
  18374. }
  18375. // Release textures
  18376. while (this.textures.length) {
  18377. this.textures[0].dispose();
  18378. }
  18379. // Post-processes
  18380. this.postProcessManager.dispose();
  18381. // Physics
  18382. if (this._physicsEngine) {
  18383. this.disablePhysicsEngine();
  18384. }
  18385. // Remove from engine
  18386. index = this._engine.scenes.indexOf(this);
  18387. if (index > -1) {
  18388. this._engine.scenes.splice(index, 1);
  18389. }
  18390. this._engine.wipeCaches();
  18391. };
  18392. // Release sounds & sounds tracks
  18393. Scene.prototype.disposeSounds = function () {
  18394. this.mainSoundTrack.dispose();
  18395. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18396. this.soundTracks[scIndex].dispose();
  18397. }
  18398. };
  18399. // Octrees
  18400. Scene.prototype.getWorldExtends = function () {
  18401. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18402. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18403. for (var index = 0; index < this.meshes.length; index++) {
  18404. var mesh = this.meshes[index];
  18405. mesh.computeWorldMatrix(true);
  18406. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18407. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18408. BABYLON.Tools.CheckExtends(minBox, min, max);
  18409. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18410. }
  18411. return {
  18412. min: min,
  18413. max: max
  18414. };
  18415. };
  18416. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18417. if (maxCapacity === void 0) { maxCapacity = 64; }
  18418. if (maxDepth === void 0) { maxDepth = 2; }
  18419. if (!this._selectionOctree) {
  18420. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18421. }
  18422. var worldExtends = this.getWorldExtends();
  18423. // Update octree
  18424. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18425. return this._selectionOctree;
  18426. };
  18427. // Picking
  18428. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18429. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18430. var engine = this._engine;
  18431. if (!camera) {
  18432. if (!this.activeCamera)
  18433. throw new Error("Active camera not set");
  18434. camera = this.activeCamera;
  18435. }
  18436. var cameraViewport = camera.viewport;
  18437. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18438. // Moving coordinates to local viewport world
  18439. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18440. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18441. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18442. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18443. };
  18444. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18445. var engine = this._engine;
  18446. if (!camera) {
  18447. if (!this.activeCamera)
  18448. throw new Error("Active camera not set");
  18449. camera = this.activeCamera;
  18450. }
  18451. var cameraViewport = camera.viewport;
  18452. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18453. var identity = BABYLON.Matrix.Identity();
  18454. // Moving coordinates to local viewport world
  18455. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18456. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18457. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18458. };
  18459. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18460. var pickingInfo = null;
  18461. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18462. var mesh = this.meshes[meshIndex];
  18463. if (predicate) {
  18464. if (!predicate(mesh)) {
  18465. continue;
  18466. }
  18467. }
  18468. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18469. continue;
  18470. }
  18471. var world = mesh.getWorldMatrix();
  18472. var ray = rayFunction(world);
  18473. var result = mesh.intersects(ray, fastCheck);
  18474. if (!result || !result.hit)
  18475. continue;
  18476. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18477. continue;
  18478. pickingInfo = result;
  18479. if (fastCheck) {
  18480. break;
  18481. }
  18482. }
  18483. return pickingInfo || new BABYLON.PickingInfo();
  18484. };
  18485. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18486. var pickingInfo = null;
  18487. camera = camera || this.activeCamera;
  18488. if (this.spriteManagers.length > 0) {
  18489. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18490. var spriteManager = this.spriteManagers[spriteIndex];
  18491. if (!spriteManager.isPickable) {
  18492. continue;
  18493. }
  18494. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18495. if (!result || !result.hit)
  18496. continue;
  18497. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18498. continue;
  18499. pickingInfo = result;
  18500. if (fastCheck) {
  18501. break;
  18502. }
  18503. }
  18504. }
  18505. return pickingInfo || new BABYLON.PickingInfo();
  18506. };
  18507. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18508. var _this = this;
  18509. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18510. /// <param name="x">X position on screen</param>
  18511. /// <param name="y">Y position on screen</param>
  18512. /// <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>
  18513. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18514. /// <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>
  18515. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18516. };
  18517. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18518. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18519. /// <param name="x">X position on screen</param>
  18520. /// <param name="y">Y position on screen</param>
  18521. /// <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>
  18522. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18523. /// <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>
  18524. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18525. };
  18526. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18527. var _this = this;
  18528. return this._internalPick(function (world) {
  18529. if (!_this._pickWithRayInverseMatrix) {
  18530. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18531. }
  18532. world.invertToRef(_this._pickWithRayInverseMatrix);
  18533. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18534. }, predicate, fastCheck);
  18535. };
  18536. Scene.prototype.setPointerOverMesh = function (mesh) {
  18537. if (this._pointerOverMesh === mesh) {
  18538. return;
  18539. }
  18540. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18541. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18542. }
  18543. this._pointerOverMesh = mesh;
  18544. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18545. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18546. }
  18547. };
  18548. Scene.prototype.getPointerOverMesh = function () {
  18549. return this._pointerOverMesh;
  18550. };
  18551. Scene.prototype.setPointerOverSprite = function (sprite) {
  18552. if (this._pointerOverSprite === sprite) {
  18553. return;
  18554. }
  18555. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18556. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18557. }
  18558. this._pointerOverSprite = sprite;
  18559. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18560. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18561. }
  18562. };
  18563. Scene.prototype.getPointerOverSprite = function () {
  18564. return this._pointerOverSprite;
  18565. };
  18566. // Physics
  18567. Scene.prototype.getPhysicsEngine = function () {
  18568. return this._physicsEngine;
  18569. };
  18570. /**
  18571. * Enables physics to the current scene
  18572. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18573. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18574. * @return {boolean} was the physics engine initialized
  18575. */
  18576. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18577. if (this._physicsEngine) {
  18578. return true;
  18579. }
  18580. try {
  18581. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18582. return true;
  18583. }
  18584. catch (e) {
  18585. BABYLON.Tools.Error(e.message);
  18586. return false;
  18587. }
  18588. };
  18589. Scene.prototype.disablePhysicsEngine = function () {
  18590. if (!this._physicsEngine) {
  18591. return;
  18592. }
  18593. this._physicsEngine.dispose();
  18594. this._physicsEngine = undefined;
  18595. };
  18596. Scene.prototype.isPhysicsEnabled = function () {
  18597. return this._physicsEngine !== undefined;
  18598. };
  18599. /**
  18600. *
  18601. * Sets the gravity of the physics engine (and NOT of the scene)
  18602. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18603. */
  18604. Scene.prototype.setGravity = function (gravity) {
  18605. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18606. if (!this._physicsEngine) {
  18607. return;
  18608. }
  18609. this._physicsEngine.setGravity(gravity);
  18610. };
  18611. /**
  18612. * Legacy support, using the new API
  18613. * @Deprecated
  18614. */
  18615. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18616. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18617. if (parts.parts) {
  18618. options = parts;
  18619. parts = parts.parts;
  18620. }
  18621. var mainMesh = parts[0].mesh;
  18622. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18623. for (var index = 1; index < parts.length; index++) {
  18624. var mesh = parts[index].mesh;
  18625. if (mesh.parent !== mainMesh) {
  18626. mesh.position = mesh.position.subtract(mainMesh.position);
  18627. mesh.parent = mainMesh;
  18628. }
  18629. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18630. }
  18631. mainMesh.physicsImpostor.forceUpdate();
  18632. };
  18633. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18634. var mesh = compound.parts[0].mesh;
  18635. mesh.physicsImpostor.dispose();
  18636. mesh.physicsImpostor = null;
  18637. };
  18638. // Misc.
  18639. Scene.prototype.createDefaultCameraOrLight = function () {
  18640. // Light
  18641. if (this.lights.length === 0) {
  18642. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18643. }
  18644. // Camera
  18645. if (!this.activeCamera) {
  18646. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18647. // Compute position
  18648. var worldExtends = this.getWorldExtends();
  18649. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18650. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18651. camera.setTarget(worldCenter);
  18652. this.activeCamera = camera;
  18653. }
  18654. };
  18655. // Tags
  18656. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18657. if (tagsQuery === undefined) {
  18658. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18659. return list;
  18660. }
  18661. var listByTags = [];
  18662. forEach = forEach || (function (item) { return; });
  18663. for (var i in list) {
  18664. var item = list[i];
  18665. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18666. listByTags.push(item);
  18667. forEach(item);
  18668. }
  18669. }
  18670. return listByTags;
  18671. };
  18672. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18673. return this._getByTags(this.meshes, tagsQuery, forEach);
  18674. };
  18675. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18676. return this._getByTags(this.cameras, tagsQuery, forEach);
  18677. };
  18678. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18679. return this._getByTags(this.lights, tagsQuery, forEach);
  18680. };
  18681. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18682. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18683. };
  18684. /**
  18685. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18686. * This allowed control for front to back rendering or reversly depending of the special needs.
  18687. *
  18688. * @param renderingGroupId The rendering group id corresponding to its index
  18689. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18690. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18691. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18692. */
  18693. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18694. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18695. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18696. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18697. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18698. };
  18699. /**
  18700. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18701. *
  18702. * @param renderingGroupId The rendering group id corresponding to its index
  18703. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18704. */
  18705. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18706. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18707. };
  18708. // Statics
  18709. Scene._FOGMODE_NONE = 0;
  18710. Scene._FOGMODE_EXP = 1;
  18711. Scene._FOGMODE_EXP2 = 2;
  18712. Scene._FOGMODE_LINEAR = 3;
  18713. Scene.MinDeltaTime = 1.0;
  18714. Scene.MaxDeltaTime = 1000.0;
  18715. return Scene;
  18716. }());
  18717. BABYLON.Scene = Scene;
  18718. })(BABYLON || (BABYLON = {}));
  18719. var BABYLON;
  18720. (function (BABYLON) {
  18721. var Buffer = (function () {
  18722. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18723. if (engine instanceof BABYLON.Mesh) {
  18724. this._engine = engine.getScene().getEngine();
  18725. }
  18726. else {
  18727. this._engine = engine;
  18728. }
  18729. this._updatable = updatable;
  18730. this._data = data;
  18731. this._strideSize = stride;
  18732. if (!postponeInternalCreation) {
  18733. this.create();
  18734. }
  18735. this._instanced = instanced;
  18736. }
  18737. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18738. // a lot of these parameters are ignored as they are overriden by the buffer
  18739. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18740. };
  18741. // Properties
  18742. Buffer.prototype.isUpdatable = function () {
  18743. return this._updatable;
  18744. };
  18745. Buffer.prototype.getData = function () {
  18746. return this._data;
  18747. };
  18748. Buffer.prototype.getBuffer = function () {
  18749. return this._buffer;
  18750. };
  18751. Buffer.prototype.getStrideSize = function () {
  18752. return this._strideSize;
  18753. };
  18754. Buffer.prototype.getIsInstanced = function () {
  18755. return this._instanced;
  18756. };
  18757. // Methods
  18758. Buffer.prototype.create = function (data) {
  18759. if (!data && this._buffer) {
  18760. return; // nothing to do
  18761. }
  18762. data = data || this._data;
  18763. if (!this._buffer) {
  18764. if (this._updatable) {
  18765. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18766. this._data = data;
  18767. }
  18768. else {
  18769. this._buffer = this._engine.createVertexBuffer(data);
  18770. }
  18771. }
  18772. else if (this._updatable) {
  18773. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18774. this._data = data;
  18775. }
  18776. };
  18777. Buffer.prototype.update = function (data) {
  18778. this.create(data);
  18779. };
  18780. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18781. if (!this._buffer) {
  18782. return;
  18783. }
  18784. if (this._updatable) {
  18785. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18786. this._data = null;
  18787. }
  18788. };
  18789. Buffer.prototype.dispose = function () {
  18790. if (!this._buffer) {
  18791. return;
  18792. }
  18793. if (this._engine._releaseBuffer(this._buffer)) {
  18794. this._buffer = null;
  18795. }
  18796. };
  18797. return Buffer;
  18798. }());
  18799. BABYLON.Buffer = Buffer;
  18800. })(BABYLON || (BABYLON = {}));
  18801. var BABYLON;
  18802. (function (BABYLON) {
  18803. var VertexBuffer = (function () {
  18804. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18805. if (!stride) {
  18806. // Deduce stride from kind
  18807. switch (kind) {
  18808. case VertexBuffer.PositionKind:
  18809. stride = 3;
  18810. break;
  18811. case VertexBuffer.NormalKind:
  18812. stride = 3;
  18813. break;
  18814. case VertexBuffer.UVKind:
  18815. case VertexBuffer.UV2Kind:
  18816. case VertexBuffer.UV3Kind:
  18817. case VertexBuffer.UV4Kind:
  18818. case VertexBuffer.UV5Kind:
  18819. case VertexBuffer.UV6Kind:
  18820. stride = 2;
  18821. break;
  18822. case VertexBuffer.ColorKind:
  18823. stride = 4;
  18824. break;
  18825. case VertexBuffer.MatricesIndicesKind:
  18826. case VertexBuffer.MatricesIndicesExtraKind:
  18827. stride = 4;
  18828. break;
  18829. case VertexBuffer.MatricesWeightsKind:
  18830. case VertexBuffer.MatricesWeightsExtraKind:
  18831. stride = 4;
  18832. break;
  18833. }
  18834. }
  18835. if (data instanceof BABYLON.Buffer) {
  18836. if (!stride) {
  18837. stride = data.getStrideSize();
  18838. }
  18839. this._buffer = data;
  18840. this._ownsBuffer = false;
  18841. }
  18842. else {
  18843. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18844. this._ownsBuffer = true;
  18845. }
  18846. this._stride = stride;
  18847. this._offset = offset ? offset : 0;
  18848. this._size = size ? size : stride;
  18849. this._kind = kind;
  18850. }
  18851. VertexBuffer.prototype.getKind = function () {
  18852. return this._kind;
  18853. };
  18854. // Properties
  18855. VertexBuffer.prototype.isUpdatable = function () {
  18856. return this._buffer.isUpdatable();
  18857. };
  18858. VertexBuffer.prototype.getData = function () {
  18859. return this._buffer.getData();
  18860. };
  18861. VertexBuffer.prototype.getBuffer = function () {
  18862. return this._buffer.getBuffer();
  18863. };
  18864. VertexBuffer.prototype.getStrideSize = function () {
  18865. return this._stride;
  18866. };
  18867. VertexBuffer.prototype.getOffset = function () {
  18868. return this._offset;
  18869. };
  18870. VertexBuffer.prototype.getSize = function () {
  18871. return this._size;
  18872. };
  18873. VertexBuffer.prototype.getIsInstanced = function () {
  18874. return this._buffer.getIsInstanced();
  18875. };
  18876. // Methods
  18877. VertexBuffer.prototype.create = function (data) {
  18878. return this._buffer.create(data);
  18879. };
  18880. VertexBuffer.prototype.update = function (data) {
  18881. return this._buffer.update(data);
  18882. };
  18883. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18884. return this._buffer.updateDirectly(data, offset);
  18885. };
  18886. VertexBuffer.prototype.dispose = function () {
  18887. if (this._ownsBuffer) {
  18888. this._buffer.dispose();
  18889. }
  18890. };
  18891. Object.defineProperty(VertexBuffer, "PositionKind", {
  18892. get: function () {
  18893. return VertexBuffer._PositionKind;
  18894. },
  18895. enumerable: true,
  18896. configurable: true
  18897. });
  18898. Object.defineProperty(VertexBuffer, "NormalKind", {
  18899. get: function () {
  18900. return VertexBuffer._NormalKind;
  18901. },
  18902. enumerable: true,
  18903. configurable: true
  18904. });
  18905. Object.defineProperty(VertexBuffer, "UVKind", {
  18906. get: function () {
  18907. return VertexBuffer._UVKind;
  18908. },
  18909. enumerable: true,
  18910. configurable: true
  18911. });
  18912. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18913. get: function () {
  18914. return VertexBuffer._UV2Kind;
  18915. },
  18916. enumerable: true,
  18917. configurable: true
  18918. });
  18919. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18920. get: function () {
  18921. return VertexBuffer._UV3Kind;
  18922. },
  18923. enumerable: true,
  18924. configurable: true
  18925. });
  18926. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18927. get: function () {
  18928. return VertexBuffer._UV4Kind;
  18929. },
  18930. enumerable: true,
  18931. configurable: true
  18932. });
  18933. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18934. get: function () {
  18935. return VertexBuffer._UV5Kind;
  18936. },
  18937. enumerable: true,
  18938. configurable: true
  18939. });
  18940. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18941. get: function () {
  18942. return VertexBuffer._UV6Kind;
  18943. },
  18944. enumerable: true,
  18945. configurable: true
  18946. });
  18947. Object.defineProperty(VertexBuffer, "ColorKind", {
  18948. get: function () {
  18949. return VertexBuffer._ColorKind;
  18950. },
  18951. enumerable: true,
  18952. configurable: true
  18953. });
  18954. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18955. get: function () {
  18956. return VertexBuffer._MatricesIndicesKind;
  18957. },
  18958. enumerable: true,
  18959. configurable: true
  18960. });
  18961. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18962. get: function () {
  18963. return VertexBuffer._MatricesWeightsKind;
  18964. },
  18965. enumerable: true,
  18966. configurable: true
  18967. });
  18968. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18969. get: function () {
  18970. return VertexBuffer._MatricesIndicesExtraKind;
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18976. get: function () {
  18977. return VertexBuffer._MatricesWeightsExtraKind;
  18978. },
  18979. enumerable: true,
  18980. configurable: true
  18981. });
  18982. // Enums
  18983. VertexBuffer._PositionKind = "position";
  18984. VertexBuffer._NormalKind = "normal";
  18985. VertexBuffer._UVKind = "uv";
  18986. VertexBuffer._UV2Kind = "uv2";
  18987. VertexBuffer._UV3Kind = "uv3";
  18988. VertexBuffer._UV4Kind = "uv4";
  18989. VertexBuffer._UV5Kind = "uv5";
  18990. VertexBuffer._UV6Kind = "uv6";
  18991. VertexBuffer._ColorKind = "color";
  18992. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18993. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18994. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18995. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18996. return VertexBuffer;
  18997. }());
  18998. BABYLON.VertexBuffer = VertexBuffer;
  18999. })(BABYLON || (BABYLON = {}));
  19000. var BABYLON;
  19001. (function (BABYLON) {
  19002. /**
  19003. * Creates an instance based on a source mesh.
  19004. */
  19005. var InstancedMesh = (function (_super) {
  19006. __extends(InstancedMesh, _super);
  19007. function InstancedMesh(name, source) {
  19008. _super.call(this, name, source.getScene());
  19009. source.instances.push(this);
  19010. this._sourceMesh = source;
  19011. this.position.copyFrom(source.position);
  19012. this.rotation.copyFrom(source.rotation);
  19013. this.scaling.copyFrom(source.scaling);
  19014. if (source.rotationQuaternion) {
  19015. this.rotationQuaternion = source.rotationQuaternion.clone();
  19016. }
  19017. this.infiniteDistance = source.infiniteDistance;
  19018. this.setPivotMatrix(source.getPivotMatrix());
  19019. this.refreshBoundingInfo();
  19020. this._syncSubMeshes();
  19021. }
  19022. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19023. // Methods
  19024. get: function () {
  19025. return this._sourceMesh.receiveShadows;
  19026. },
  19027. enumerable: true,
  19028. configurable: true
  19029. });
  19030. Object.defineProperty(InstancedMesh.prototype, "material", {
  19031. get: function () {
  19032. return this._sourceMesh.material;
  19033. },
  19034. enumerable: true,
  19035. configurable: true
  19036. });
  19037. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19038. get: function () {
  19039. return this._sourceMesh.visibility;
  19040. },
  19041. enumerable: true,
  19042. configurable: true
  19043. });
  19044. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19045. get: function () {
  19046. return this._sourceMesh.skeleton;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19052. get: function () {
  19053. return this._sourceMesh.renderingGroupId;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. InstancedMesh.prototype.getTotalVertices = function () {
  19059. return this._sourceMesh.getTotalVertices();
  19060. };
  19061. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19062. get: function () {
  19063. return this._sourceMesh;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19069. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19070. };
  19071. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19072. return this._sourceMesh.isVerticesDataPresent(kind);
  19073. };
  19074. InstancedMesh.prototype.getIndices = function () {
  19075. return this._sourceMesh.getIndices();
  19076. };
  19077. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19078. get: function () {
  19079. return this._sourceMesh._positions;
  19080. },
  19081. enumerable: true,
  19082. configurable: true
  19083. });
  19084. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19085. var meshBB = this._sourceMesh.getBoundingInfo();
  19086. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19087. this._updateBoundingInfo();
  19088. };
  19089. InstancedMesh.prototype._preActivate = function () {
  19090. if (this._currentLOD) {
  19091. this._currentLOD._preActivate();
  19092. }
  19093. };
  19094. InstancedMesh.prototype._activate = function (renderId) {
  19095. if (this._currentLOD) {
  19096. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19097. }
  19098. };
  19099. InstancedMesh.prototype.getLOD = function (camera) {
  19100. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19101. if (this._currentLOD === this.sourceMesh) {
  19102. return this;
  19103. }
  19104. return this._currentLOD;
  19105. };
  19106. InstancedMesh.prototype._syncSubMeshes = function () {
  19107. this.releaseSubMeshes();
  19108. if (this._sourceMesh.subMeshes) {
  19109. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19110. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19111. }
  19112. }
  19113. };
  19114. InstancedMesh.prototype._generatePointsArray = function () {
  19115. return this._sourceMesh._generatePointsArray();
  19116. };
  19117. // Clone
  19118. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19119. var result = this._sourceMesh.createInstance(name);
  19120. // Deep copy
  19121. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19122. // Bounding info
  19123. this.refreshBoundingInfo();
  19124. // Parent
  19125. if (newParent) {
  19126. result.parent = newParent;
  19127. }
  19128. if (!doNotCloneChildren) {
  19129. // Children
  19130. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19131. var mesh = this.getScene().meshes[index];
  19132. if (mesh.parent === this) {
  19133. mesh.clone(mesh.name, result);
  19134. }
  19135. }
  19136. }
  19137. result.computeWorldMatrix(true);
  19138. return result;
  19139. };
  19140. // Dispoe
  19141. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19142. // Remove from mesh
  19143. var index = this._sourceMesh.instances.indexOf(this);
  19144. this._sourceMesh.instances.splice(index, 1);
  19145. _super.prototype.dispose.call(this, doNotRecurse);
  19146. };
  19147. return InstancedMesh;
  19148. }(BABYLON.AbstractMesh));
  19149. BABYLON.InstancedMesh = InstancedMesh;
  19150. })(BABYLON || (BABYLON = {}));
  19151. var BABYLON;
  19152. (function (BABYLON) {
  19153. var _InstancesBatch = (function () {
  19154. function _InstancesBatch() {
  19155. this.mustReturn = false;
  19156. this.visibleInstances = new Array();
  19157. this.renderSelf = new Array();
  19158. }
  19159. return _InstancesBatch;
  19160. }());
  19161. BABYLON._InstancesBatch = _InstancesBatch;
  19162. var Mesh = (function (_super) {
  19163. __extends(Mesh, _super);
  19164. /**
  19165. * @constructor
  19166. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19167. * @param {Scene} scene The scene to add this mesh to.
  19168. * @param {Node} parent The parent of this mesh, if it has one
  19169. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19170. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19171. * When false, achieved by calling a clone(), also passing False.
  19172. * This will make creation of children, recursive.
  19173. */
  19174. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19175. if (parent === void 0) { parent = null; }
  19176. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19177. _super.call(this, name, scene);
  19178. // Events
  19179. /**
  19180. * An event triggered before rendering the mesh
  19181. * @type {BABYLON.Observable}
  19182. */
  19183. this.onBeforeRenderObservable = new BABYLON.Observable();
  19184. /**
  19185. * An event triggered after rendering the mesh
  19186. * @type {BABYLON.Observable}
  19187. */
  19188. this.onAfterRenderObservable = new BABYLON.Observable();
  19189. /**
  19190. * An event triggered before drawing the mesh
  19191. * @type {BABYLON.Observable}
  19192. */
  19193. this.onBeforeDrawObservable = new BABYLON.Observable();
  19194. // Members
  19195. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19196. this.instances = new Array();
  19197. this._LODLevels = new Array();
  19198. this._visibleInstances = {};
  19199. this._renderIdForInstances = new Array();
  19200. this._batchCache = new _InstancesBatch();
  19201. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19202. this._sideOrientation = Mesh._DEFAULTSIDE;
  19203. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19204. if (source) {
  19205. // Geometry
  19206. if (source._geometry) {
  19207. source._geometry.applyToMesh(this);
  19208. }
  19209. // Deep copy
  19210. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  19211. // Pivot
  19212. this.setPivotMatrix(source.getPivotMatrix());
  19213. this.id = name + "." + source.id;
  19214. // Material
  19215. this.material = source.material;
  19216. var index;
  19217. if (!doNotCloneChildren) {
  19218. // Children
  19219. for (index = 0; index < scene.meshes.length; index++) {
  19220. var mesh = scene.meshes[index];
  19221. if (mesh.parent === source) {
  19222. // doNotCloneChildren is always going to be False
  19223. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19224. }
  19225. }
  19226. }
  19227. // Physics clone
  19228. var physicsEngine = this.getScene().getPhysicsEngine();
  19229. if (clonePhysicsImpostor && physicsEngine) {
  19230. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19231. if (impostor) {
  19232. this.physicsImpostor = impostor.clone(this);
  19233. }
  19234. }
  19235. // Particles
  19236. for (index = 0; index < scene.particleSystems.length; index++) {
  19237. var system = scene.particleSystems[index];
  19238. if (system.emitter === source) {
  19239. system.clone(system.name, this);
  19240. }
  19241. }
  19242. this.computeWorldMatrix(true);
  19243. }
  19244. // Parent
  19245. if (parent !== null) {
  19246. this.parent = parent;
  19247. }
  19248. }
  19249. Object.defineProperty(Mesh, "FRONTSIDE", {
  19250. /**
  19251. * Mesh side orientation : usually the external or front surface
  19252. */
  19253. get: function () {
  19254. return Mesh._FRONTSIDE;
  19255. },
  19256. enumerable: true,
  19257. configurable: true
  19258. });
  19259. Object.defineProperty(Mesh, "BACKSIDE", {
  19260. /**
  19261. * Mesh side orientation : usually the internal or back surface
  19262. */
  19263. get: function () {
  19264. return Mesh._BACKSIDE;
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19270. /**
  19271. * Mesh side orientation : both internal and external or front and back surfaces
  19272. */
  19273. get: function () {
  19274. return Mesh._DOUBLESIDE;
  19275. },
  19276. enumerable: true,
  19277. configurable: true
  19278. });
  19279. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19280. /**
  19281. * Mesh side orientation : by default, `FRONTSIDE`
  19282. */
  19283. get: function () {
  19284. return Mesh._DEFAULTSIDE;
  19285. },
  19286. enumerable: true,
  19287. configurable: true
  19288. });
  19289. Object.defineProperty(Mesh, "NO_CAP", {
  19290. /**
  19291. * Mesh cap setting : no cap
  19292. */
  19293. get: function () {
  19294. return Mesh._NO_CAP;
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(Mesh, "CAP_START", {
  19300. /**
  19301. * Mesh cap setting : one cap at the beginning of the mesh
  19302. */
  19303. get: function () {
  19304. return Mesh._CAP_START;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. Object.defineProperty(Mesh, "CAP_END", {
  19310. /**
  19311. * Mesh cap setting : one cap at the end of the mesh
  19312. */
  19313. get: function () {
  19314. return Mesh._CAP_END;
  19315. },
  19316. enumerable: true,
  19317. configurable: true
  19318. });
  19319. Object.defineProperty(Mesh, "CAP_ALL", {
  19320. /**
  19321. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19322. */
  19323. get: function () {
  19324. return Mesh._CAP_ALL;
  19325. },
  19326. enumerable: true,
  19327. configurable: true
  19328. });
  19329. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19330. set: function (callback) {
  19331. if (this._onBeforeDrawObserver) {
  19332. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19333. }
  19334. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. // Methods
  19340. /**
  19341. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19342. */
  19343. Mesh.prototype.toString = function (fullDetails) {
  19344. var ret = _super.prototype.toString.call(this, fullDetails);
  19345. ret += ", n vertices: " + this.getTotalVertices();
  19346. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19347. if (this.animations) {
  19348. for (var i = 0; i < this.animations.length; i++) {
  19349. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19350. }
  19351. }
  19352. if (fullDetails) {
  19353. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19354. }
  19355. return ret;
  19356. };
  19357. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19358. get: function () {
  19359. return this._LODLevels.length > 0;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Mesh.prototype._sortLODLevels = function () {
  19365. this._LODLevels.sort(function (a, b) {
  19366. if (a.distance < b.distance) {
  19367. return 1;
  19368. }
  19369. if (a.distance > b.distance) {
  19370. return -1;
  19371. }
  19372. return 0;
  19373. });
  19374. };
  19375. /**
  19376. * Add a mesh as LOD level triggered at the given distance.
  19377. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19378. * @param {number} distance The distance from the center of the object to show this level
  19379. * @param {Mesh} mesh The mesh to be added as LOD level
  19380. * @return {Mesh} This mesh (for chaining)
  19381. */
  19382. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19383. if (mesh && mesh._masterMesh) {
  19384. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19385. return this;
  19386. }
  19387. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19388. this._LODLevels.push(level);
  19389. if (mesh) {
  19390. mesh._masterMesh = this;
  19391. }
  19392. this._sortLODLevels();
  19393. return this;
  19394. };
  19395. /**
  19396. * Returns the LOD level mesh at the passed distance or null if not found.
  19397. * It is related to the method `addLODLevel(distance, mesh)`.
  19398. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19399. */
  19400. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19401. for (var index = 0; index < this._LODLevels.length; index++) {
  19402. var level = this._LODLevels[index];
  19403. if (level.distance === distance) {
  19404. return level.mesh;
  19405. }
  19406. }
  19407. return null;
  19408. };
  19409. /**
  19410. * Remove a mesh from the LOD array
  19411. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19412. * @param {Mesh} mesh The mesh to be removed.
  19413. * @return {Mesh} This mesh (for chaining)
  19414. */
  19415. Mesh.prototype.removeLODLevel = function (mesh) {
  19416. for (var index = 0; index < this._LODLevels.length; index++) {
  19417. if (this._LODLevels[index].mesh === mesh) {
  19418. this._LODLevels.splice(index, 1);
  19419. if (mesh) {
  19420. mesh._masterMesh = null;
  19421. }
  19422. }
  19423. }
  19424. this._sortLODLevels();
  19425. return this;
  19426. };
  19427. /**
  19428. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19429. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19430. */
  19431. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19432. if (!this._LODLevels || this._LODLevels.length === 0) {
  19433. return this;
  19434. }
  19435. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19436. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19437. if (this.onLODLevelSelection) {
  19438. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19439. }
  19440. return this;
  19441. }
  19442. for (var index = 0; index < this._LODLevels.length; index++) {
  19443. var level = this._LODLevels[index];
  19444. if (level.distance < distanceToCamera) {
  19445. if (level.mesh) {
  19446. level.mesh._preActivate();
  19447. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19448. }
  19449. if (this.onLODLevelSelection) {
  19450. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19451. }
  19452. return level.mesh;
  19453. }
  19454. }
  19455. if (this.onLODLevelSelection) {
  19456. this.onLODLevelSelection(distanceToCamera, this, this);
  19457. }
  19458. return this;
  19459. };
  19460. Object.defineProperty(Mesh.prototype, "geometry", {
  19461. /**
  19462. * Returns the mesh internal Geometry object.
  19463. */
  19464. get: function () {
  19465. return this._geometry;
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. /**
  19471. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19472. */
  19473. Mesh.prototype.getTotalVertices = function () {
  19474. if (!this._geometry) {
  19475. return 0;
  19476. }
  19477. return this._geometry.getTotalVertices();
  19478. };
  19479. /**
  19480. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19481. * 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.
  19482. * Returns null if the mesh has no geometry or no vertex buffer.
  19483. * Possible `kind` values :
  19484. * - BABYLON.VertexBuffer.PositionKind
  19485. * - BABYLON.VertexBuffer.UVKind
  19486. * - BABYLON.VertexBuffer.UV2Kind
  19487. * - BABYLON.VertexBuffer.UV3Kind
  19488. * - BABYLON.VertexBuffer.UV4Kind
  19489. * - BABYLON.VertexBuffer.UV5Kind
  19490. * - BABYLON.VertexBuffer.UV6Kind
  19491. * - BABYLON.VertexBuffer.ColorKind
  19492. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19493. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19494. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19495. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19496. */
  19497. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19498. if (!this._geometry) {
  19499. return null;
  19500. }
  19501. return this._geometry.getVerticesData(kind, copyWhenShared);
  19502. };
  19503. /**
  19504. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19505. * Returns `undefined` if the mesh has no geometry.
  19506. * Possible `kind` values :
  19507. * - BABYLON.VertexBuffer.PositionKind
  19508. * - BABYLON.VertexBuffer.UVKind
  19509. * - BABYLON.VertexBuffer.UV2Kind
  19510. * - BABYLON.VertexBuffer.UV3Kind
  19511. * - BABYLON.VertexBuffer.UV4Kind
  19512. * - BABYLON.VertexBuffer.UV5Kind
  19513. * - BABYLON.VertexBuffer.UV6Kind
  19514. * - BABYLON.VertexBuffer.ColorKind
  19515. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19516. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19517. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19518. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19519. */
  19520. Mesh.prototype.getVertexBuffer = function (kind) {
  19521. if (!this._geometry) {
  19522. return undefined;
  19523. }
  19524. return this._geometry.getVertexBuffer(kind);
  19525. };
  19526. /**
  19527. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19528. * Possible `kind` values :
  19529. * - BABYLON.VertexBuffer.PositionKind
  19530. * - BABYLON.VertexBuffer.UVKind
  19531. * - BABYLON.VertexBuffer.UV2Kind
  19532. * - BABYLON.VertexBuffer.UV3Kind
  19533. * - BABYLON.VertexBuffer.UV4Kind
  19534. * - BABYLON.VertexBuffer.UV5Kind
  19535. * - BABYLON.VertexBuffer.UV6Kind
  19536. * - BABYLON.VertexBuffer.ColorKind
  19537. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19538. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19539. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19540. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19541. */
  19542. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19543. if (!this._geometry) {
  19544. if (this._delayInfo) {
  19545. return this._delayInfo.indexOf(kind) !== -1;
  19546. }
  19547. return false;
  19548. }
  19549. return this._geometry.isVerticesDataPresent(kind);
  19550. };
  19551. /**
  19552. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19553. * Possible `kind` values :
  19554. * - BABYLON.VertexBuffer.PositionKind
  19555. * - BABYLON.VertexBuffer.UVKind
  19556. * - BABYLON.VertexBuffer.UV2Kind
  19557. * - BABYLON.VertexBuffer.UV3Kind
  19558. * - BABYLON.VertexBuffer.UV4Kind
  19559. * - BABYLON.VertexBuffer.UV5Kind
  19560. * - BABYLON.VertexBuffer.UV6Kind
  19561. * - BABYLON.VertexBuffer.ColorKind
  19562. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19563. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19564. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19565. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19566. */
  19567. Mesh.prototype.getVerticesDataKinds = function () {
  19568. if (!this._geometry) {
  19569. var result = [];
  19570. if (this._delayInfo) {
  19571. this._delayInfo.forEach(function (kind, index, array) {
  19572. result.push(kind);
  19573. });
  19574. }
  19575. return result;
  19576. }
  19577. return this._geometry.getVerticesDataKinds();
  19578. };
  19579. /**
  19580. * Returns a positive integer : the total number of indices in this mesh geometry.
  19581. * Returns zero if the mesh has no geometry.
  19582. */
  19583. Mesh.prototype.getTotalIndices = function () {
  19584. if (!this._geometry) {
  19585. return 0;
  19586. }
  19587. return this._geometry.getTotalIndices();
  19588. };
  19589. /**
  19590. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19591. * 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.
  19592. * Returns an empty array if the mesh has no geometry.
  19593. */
  19594. Mesh.prototype.getIndices = function (copyWhenShared) {
  19595. if (!this._geometry) {
  19596. return [];
  19597. }
  19598. return this._geometry.getIndices(copyWhenShared);
  19599. };
  19600. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19601. get: function () {
  19602. return this._masterMesh !== null && this._masterMesh !== undefined;
  19603. },
  19604. enumerable: true,
  19605. configurable: true
  19606. });
  19607. /**
  19608. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19609. */
  19610. Mesh.prototype.isReady = function () {
  19611. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19612. return false;
  19613. }
  19614. return _super.prototype.isReady.call(this);
  19615. };
  19616. /**
  19617. * Boolean : true if the mesh has been disposed.
  19618. */
  19619. Mesh.prototype.isDisposed = function () {
  19620. return this._isDisposed;
  19621. };
  19622. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19623. get: function () {
  19624. return this._sideOrientation;
  19625. },
  19626. /**
  19627. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19628. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19629. */
  19630. set: function (sideO) {
  19631. this._sideOrientation = sideO;
  19632. },
  19633. enumerable: true,
  19634. configurable: true
  19635. });
  19636. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19637. /**
  19638. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19639. * This property is pertinent only for updatable parametric shapes.
  19640. */
  19641. get: function () {
  19642. return this._areNormalsFrozen;
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. /**
  19648. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19649. * It has no effect at all on other shapes.
  19650. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19651. */
  19652. Mesh.prototype.freezeNormals = function () {
  19653. this._areNormalsFrozen = true;
  19654. };
  19655. /**
  19656. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19657. * It has no effect at all on other shapes.
  19658. * It reactivates the mesh normals computation if it was previously frozen.
  19659. */
  19660. Mesh.prototype.unfreezeNormals = function () {
  19661. this._areNormalsFrozen = false;
  19662. };
  19663. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19664. /**
  19665. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19666. */
  19667. set: function (count) {
  19668. this._overridenInstanceCount = count;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. // Methods
  19674. Mesh.prototype._preActivate = function () {
  19675. var sceneRenderId = this.getScene().getRenderId();
  19676. if (this._preActivateId === sceneRenderId) {
  19677. return;
  19678. }
  19679. this._preActivateId = sceneRenderId;
  19680. this._visibleInstances = null;
  19681. };
  19682. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19683. if (this._visibleInstances) {
  19684. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19685. }
  19686. };
  19687. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19688. if (!this._visibleInstances) {
  19689. this._visibleInstances = {};
  19690. this._visibleInstances.defaultRenderId = renderId;
  19691. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19692. }
  19693. if (!this._visibleInstances[renderId]) {
  19694. this._visibleInstances[renderId] = new Array();
  19695. }
  19696. this._visibleInstances[renderId].push(instance);
  19697. };
  19698. /**
  19699. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19700. * This means the mesh underlying bounding box and sphere are recomputed.
  19701. */
  19702. Mesh.prototype.refreshBoundingInfo = function () {
  19703. if (this._boundingInfo.isLocked) {
  19704. return;
  19705. }
  19706. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19707. if (data) {
  19708. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19709. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19710. }
  19711. if (this.subMeshes) {
  19712. for (var index = 0; index < this.subMeshes.length; index++) {
  19713. this.subMeshes[index].refreshBoundingInfo();
  19714. }
  19715. }
  19716. this._updateBoundingInfo();
  19717. };
  19718. Mesh.prototype._createGlobalSubMesh = function () {
  19719. var totalVertices = this.getTotalVertices();
  19720. if (!totalVertices || !this.getIndices()) {
  19721. return null;
  19722. }
  19723. this.releaseSubMeshes();
  19724. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19725. };
  19726. Mesh.prototype.subdivide = function (count) {
  19727. if (count < 1) {
  19728. return;
  19729. }
  19730. var totalIndices = this.getTotalIndices();
  19731. var subdivisionSize = (totalIndices / count) | 0;
  19732. var offset = 0;
  19733. // Ensure that subdivisionSize is a multiple of 3
  19734. while (subdivisionSize % 3 !== 0) {
  19735. subdivisionSize++;
  19736. }
  19737. this.releaseSubMeshes();
  19738. for (var index = 0; index < count; index++) {
  19739. if (offset >= totalIndices) {
  19740. break;
  19741. }
  19742. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19743. offset += subdivisionSize;
  19744. }
  19745. this.synchronizeInstances();
  19746. };
  19747. /**
  19748. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19749. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19750. * The `data` are either a numeric array either a Float32Array.
  19751. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19752. * 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).
  19753. * Note that a new underlying VertexBuffer object is created each call.
  19754. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19755. *
  19756. * Possible `kind` values :
  19757. * - BABYLON.VertexBuffer.PositionKind
  19758. * - BABYLON.VertexBuffer.UVKind
  19759. * - BABYLON.VertexBuffer.UV2Kind
  19760. * - BABYLON.VertexBuffer.UV3Kind
  19761. * - BABYLON.VertexBuffer.UV4Kind
  19762. * - BABYLON.VertexBuffer.UV5Kind
  19763. * - BABYLON.VertexBuffer.UV6Kind
  19764. * - BABYLON.VertexBuffer.ColorKind
  19765. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19766. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19767. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19768. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19769. */
  19770. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19771. if (!this._geometry) {
  19772. var vertexData = new BABYLON.VertexData();
  19773. vertexData.set(data, kind);
  19774. var scene = this.getScene();
  19775. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19776. }
  19777. else {
  19778. this._geometry.setVerticesData(kind, data, updatable, stride);
  19779. }
  19780. };
  19781. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19782. if (!this._geometry) {
  19783. var scene = this.getScene();
  19784. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19785. }
  19786. this._geometry.setVerticesBuffer(buffer);
  19787. };
  19788. /**
  19789. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19790. * If the mesh has no geometry, it is simply returned as it is.
  19791. * The `data` are either a numeric array either a Float32Array.
  19792. * No new underlying VertexBuffer object is created.
  19793. * 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.
  19794. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19795. *
  19796. * Possible `kind` values :
  19797. * - BABYLON.VertexBuffer.PositionKind
  19798. * - BABYLON.VertexBuffer.UVKind
  19799. * - BABYLON.VertexBuffer.UV2Kind
  19800. * - BABYLON.VertexBuffer.UV3Kind
  19801. * - BABYLON.VertexBuffer.UV4Kind
  19802. * - BABYLON.VertexBuffer.UV5Kind
  19803. * - BABYLON.VertexBuffer.UV6Kind
  19804. * - BABYLON.VertexBuffer.ColorKind
  19805. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19806. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19807. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19808. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19809. */
  19810. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19811. if (!this._geometry) {
  19812. return;
  19813. }
  19814. if (!makeItUnique) {
  19815. this._geometry.updateVerticesData(kind, data, updateExtends);
  19816. }
  19817. else {
  19818. this.makeGeometryUnique();
  19819. this.updateVerticesData(kind, data, updateExtends, false);
  19820. }
  19821. };
  19822. /**
  19823. * Deprecated since BabylonJS v2.3
  19824. */
  19825. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19826. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19827. if (!this._geometry) {
  19828. return;
  19829. }
  19830. if (!makeItUnique) {
  19831. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19832. }
  19833. else {
  19834. this.makeGeometryUnique();
  19835. this.updateVerticesDataDirectly(kind, data, offset, false);
  19836. }
  19837. };
  19838. /**
  19839. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19840. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19841. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19842. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19843. */
  19844. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19845. if (computeNormals === void 0) { computeNormals = true; }
  19846. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19847. positionFunction(positions);
  19848. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19849. if (computeNormals) {
  19850. var indices = this.getIndices();
  19851. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19852. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19853. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19854. }
  19855. };
  19856. Mesh.prototype.makeGeometryUnique = function () {
  19857. if (!this._geometry) {
  19858. return;
  19859. }
  19860. var oldGeometry = this._geometry;
  19861. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19862. oldGeometry.releaseForMesh(this, true);
  19863. geometry.applyToMesh(this);
  19864. };
  19865. /**
  19866. * Sets the mesh indices.
  19867. * Expects an array populated with integers or a Int32Array.
  19868. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19869. * This method creates a new index buffer each call.
  19870. */
  19871. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19872. if (!this._geometry) {
  19873. var vertexData = new BABYLON.VertexData();
  19874. vertexData.indices = indices;
  19875. var scene = this.getScene();
  19876. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19877. }
  19878. else {
  19879. this._geometry.setIndices(indices, totalVertices);
  19880. }
  19881. };
  19882. /**
  19883. * Invert the geometry to move from a right handed system to a left handed one.
  19884. */
  19885. Mesh.prototype.toLeftHanded = function () {
  19886. if (!this._geometry) {
  19887. return;
  19888. }
  19889. this._geometry.toLeftHanded();
  19890. };
  19891. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19892. var engine = this.getScene().getEngine();
  19893. // Wireframe
  19894. var indexToBind;
  19895. if (this._unIndexed) {
  19896. indexToBind = null;
  19897. }
  19898. else {
  19899. switch (fillMode) {
  19900. case BABYLON.Material.PointFillMode:
  19901. indexToBind = null;
  19902. break;
  19903. case BABYLON.Material.WireFrameFillMode:
  19904. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19905. break;
  19906. default:
  19907. case BABYLON.Material.TriangleFillMode:
  19908. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19909. break;
  19910. }
  19911. }
  19912. // VBOs
  19913. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19914. };
  19915. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19916. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19917. return;
  19918. }
  19919. this.onBeforeDrawObservable.notifyObservers(this);
  19920. var engine = this.getScene().getEngine();
  19921. // Draw order
  19922. switch (fillMode) {
  19923. case BABYLON.Material.PointFillMode:
  19924. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19925. break;
  19926. case BABYLON.Material.WireFrameFillMode:
  19927. if (this._unIndexed) {
  19928. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19929. }
  19930. else {
  19931. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19932. }
  19933. break;
  19934. default:
  19935. if (this._unIndexed) {
  19936. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19937. }
  19938. else {
  19939. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19940. }
  19941. }
  19942. };
  19943. /**
  19944. * Registers for this mesh a javascript function called just before the rendering process.
  19945. * This function is passed the current mesh and doesn't return anything.
  19946. */
  19947. Mesh.prototype.registerBeforeRender = function (func) {
  19948. this.onBeforeRenderObservable.add(func);
  19949. };
  19950. /**
  19951. * Disposes a previously registered javascript function called before the rendering.
  19952. * This function is passed the current mesh and doesn't return anything.
  19953. */
  19954. Mesh.prototype.unregisterBeforeRender = function (func) {
  19955. this.onBeforeRenderObservable.removeCallback(func);
  19956. };
  19957. /**
  19958. * Registers for this mesh a javascript function called just after the rendering is complete.
  19959. * This function is passed the current mesh and doesn't return anything.
  19960. */
  19961. Mesh.prototype.registerAfterRender = function (func) {
  19962. this.onAfterRenderObservable.add(func);
  19963. };
  19964. /**
  19965. * Disposes a previously registered javascript function called after the rendering.
  19966. * This function is passed the current mesh and doesn't return anything.
  19967. */
  19968. Mesh.prototype.unregisterAfterRender = function (func) {
  19969. this.onAfterRenderObservable.removeCallback(func);
  19970. };
  19971. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19972. var scene = this.getScene();
  19973. this._batchCache.mustReturn = false;
  19974. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19975. this._batchCache.visibleInstances[subMeshId] = null;
  19976. if (this._visibleInstances) {
  19977. var currentRenderId = scene.getRenderId();
  19978. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19979. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19980. var selfRenderId = this._renderId;
  19981. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19982. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19983. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19984. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19985. }
  19986. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19987. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19988. this._batchCache.mustReturn = true;
  19989. return this._batchCache;
  19990. }
  19991. if (currentRenderId !== selfRenderId) {
  19992. this._batchCache.renderSelf[subMeshId] = false;
  19993. }
  19994. }
  19995. this._renderIdForInstances[subMeshId] = currentRenderId;
  19996. }
  19997. return this._batchCache;
  19998. };
  19999. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20000. var visibleInstances = batch.visibleInstances[subMesh._id];
  20001. var matricesCount = visibleInstances.length + 1;
  20002. var bufferSize = matricesCount * 16 * 4;
  20003. var currentInstancesBufferSize = this._instancesBufferSize;
  20004. var instancesBuffer = this._instancesBuffer;
  20005. while (this._instancesBufferSize < bufferSize) {
  20006. this._instancesBufferSize *= 2;
  20007. }
  20008. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20009. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20010. }
  20011. var offset = 0;
  20012. var instancesCount = 0;
  20013. var world = this.getWorldMatrix();
  20014. if (batch.renderSelf[subMesh._id]) {
  20015. world.copyToArray(this._instancesData, offset);
  20016. offset += 16;
  20017. instancesCount++;
  20018. }
  20019. if (visibleInstances) {
  20020. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20021. var instance = visibleInstances[instanceIndex];
  20022. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20023. offset += 16;
  20024. instancesCount++;
  20025. }
  20026. }
  20027. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20028. if (instancesBuffer) {
  20029. instancesBuffer.dispose();
  20030. }
  20031. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20032. this._instancesBuffer = instancesBuffer;
  20033. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20034. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20035. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20036. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20037. }
  20038. else {
  20039. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20040. }
  20041. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20042. this._draw(subMesh, fillMode, instancesCount);
  20043. engine.unbindInstanceAttributes();
  20044. };
  20045. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20046. var scene = this.getScene();
  20047. var engine = scene.getEngine();
  20048. if (hardwareInstancedRendering) {
  20049. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20050. }
  20051. else {
  20052. if (batch.renderSelf[subMesh._id]) {
  20053. // Draw
  20054. if (onBeforeDraw) {
  20055. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20056. }
  20057. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20058. }
  20059. if (batch.visibleInstances[subMesh._id]) {
  20060. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20061. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20062. // World
  20063. var world = instance.getWorldMatrix();
  20064. if (onBeforeDraw) {
  20065. onBeforeDraw(true, world, effectiveMaterial);
  20066. }
  20067. // Draw
  20068. this._draw(subMesh, fillMode);
  20069. }
  20070. }
  20071. }
  20072. };
  20073. /**
  20074. * Triggers the draw call for the mesh.
  20075. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20076. */
  20077. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20078. var scene = this.getScene();
  20079. // Managing instances
  20080. var batch = this._getInstancesRenderList(subMesh._id);
  20081. if (batch.mustReturn) {
  20082. return;
  20083. }
  20084. // Checking geometry state
  20085. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20086. return;
  20087. }
  20088. var callbackIndex;
  20089. this.onBeforeRenderObservable.notifyObservers(this);
  20090. var engine = scene.getEngine();
  20091. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20092. // Material
  20093. var effectiveMaterial = subMesh.getMaterial();
  20094. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20095. return;
  20096. }
  20097. // Outline - step 1
  20098. var savedDepthWrite = engine.getDepthWrite();
  20099. if (this.renderOutline) {
  20100. engine.setDepthWrite(false);
  20101. scene.getOutlineRenderer().render(subMesh, batch);
  20102. engine.setDepthWrite(savedDepthWrite);
  20103. }
  20104. effectiveMaterial._preBind();
  20105. var effect = effectiveMaterial.getEffect();
  20106. // Bind
  20107. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20108. this._bind(subMesh, effect, fillMode);
  20109. var world = this.getWorldMatrix();
  20110. effectiveMaterial.bind(world, this);
  20111. // Alpha mode
  20112. if (enableAlphaMode) {
  20113. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20114. }
  20115. // Draw
  20116. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20117. // Unbind
  20118. effectiveMaterial.unbind();
  20119. // Outline - step 2
  20120. if (this.renderOutline && savedDepthWrite) {
  20121. engine.setDepthWrite(true);
  20122. engine.setColorWrite(false);
  20123. scene.getOutlineRenderer().render(subMesh, batch);
  20124. engine.setColorWrite(true);
  20125. }
  20126. // Overlay
  20127. if (this.renderOverlay) {
  20128. var currentMode = engine.getAlphaMode();
  20129. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20130. scene.getOutlineRenderer().render(subMesh, batch, true);
  20131. engine.setAlphaMode(currentMode);
  20132. }
  20133. this.onAfterRenderObservable.notifyObservers(this);
  20134. };
  20135. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20136. if (isInstance) {
  20137. effectiveMaterial.bindOnlyWorldMatrix(world);
  20138. }
  20139. };
  20140. /**
  20141. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20142. */
  20143. Mesh.prototype.getEmittedParticleSystems = function () {
  20144. var results = new Array();
  20145. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20146. var particleSystem = this.getScene().particleSystems[index];
  20147. if (particleSystem.emitter === this) {
  20148. results.push(particleSystem);
  20149. }
  20150. }
  20151. return results;
  20152. };
  20153. /**
  20154. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20155. */
  20156. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20157. var results = new Array();
  20158. var descendants = this.getDescendants();
  20159. descendants.push(this);
  20160. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20161. var particleSystem = this.getScene().particleSystems[index];
  20162. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20163. results.push(particleSystem);
  20164. }
  20165. }
  20166. return results;
  20167. };
  20168. Mesh.prototype._checkDelayState = function () {
  20169. var scene = this.getScene();
  20170. if (this._geometry) {
  20171. this._geometry.load(scene);
  20172. }
  20173. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20175. this._queueLoad(this, scene);
  20176. }
  20177. };
  20178. Mesh.prototype._queueLoad = function (mesh, scene) {
  20179. var _this = this;
  20180. scene._addPendingData(mesh);
  20181. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20182. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20183. if (data instanceof ArrayBuffer) {
  20184. _this._delayLoadingFunction(data, _this);
  20185. }
  20186. else {
  20187. _this._delayLoadingFunction(JSON.parse(data), _this);
  20188. }
  20189. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20190. scene._removePendingData(_this);
  20191. }, function () { }, scene.database, getBinaryData);
  20192. };
  20193. /**
  20194. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20195. */
  20196. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20197. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20198. return false;
  20199. }
  20200. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20201. return false;
  20202. }
  20203. this._checkDelayState();
  20204. return true;
  20205. };
  20206. /**
  20207. * Sets the mesh material by the material or multiMaterial `id` property.
  20208. * The material `id` is a string identifying the material or the multiMaterial.
  20209. * This method returns nothing.
  20210. */
  20211. Mesh.prototype.setMaterialByID = function (id) {
  20212. var materials = this.getScene().materials;
  20213. var index;
  20214. for (index = 0; index < materials.length; index++) {
  20215. if (materials[index].id === id) {
  20216. this.material = materials[index];
  20217. return;
  20218. }
  20219. }
  20220. // Multi
  20221. var multiMaterials = this.getScene().multiMaterials;
  20222. for (index = 0; index < multiMaterials.length; index++) {
  20223. if (multiMaterials[index].id === id) {
  20224. this.material = multiMaterials[index];
  20225. return;
  20226. }
  20227. }
  20228. };
  20229. /**
  20230. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20231. */
  20232. Mesh.prototype.getAnimatables = function () {
  20233. var results = [];
  20234. if (this.material) {
  20235. results.push(this.material);
  20236. }
  20237. if (this.skeleton) {
  20238. results.push(this.skeleton);
  20239. }
  20240. return results;
  20241. };
  20242. /**
  20243. * Modifies the mesh geometry according to the passed transformation matrix.
  20244. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20245. * The mesh normals are modified accordingly the same transformation.
  20246. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20247. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20248. */
  20249. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20250. // Position
  20251. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20252. return;
  20253. }
  20254. var submeshes = this.subMeshes.splice(0);
  20255. this._resetPointsArrayCache();
  20256. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20257. var temp = [];
  20258. var index;
  20259. for (index = 0; index < data.length; index += 3) {
  20260. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20261. }
  20262. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20263. // Normals
  20264. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20265. return;
  20266. }
  20267. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20268. temp = [];
  20269. for (index = 0; index < data.length; index += 3) {
  20270. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20271. }
  20272. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20273. // flip faces?
  20274. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20275. this.flipFaces();
  20276. }
  20277. // Restore submeshes
  20278. this.releaseSubMeshes();
  20279. this.subMeshes = submeshes;
  20280. };
  20281. /**
  20282. * Modifies the mesh geometry according to its own current World Matrix.
  20283. * The mesh World Matrix is then reset.
  20284. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20285. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20286. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20287. */
  20288. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20289. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20290. this.scaling.copyFromFloats(1, 1, 1);
  20291. this.position.copyFromFloats(0, 0, 0);
  20292. this.rotation.copyFromFloats(0, 0, 0);
  20293. //only if quaternion is already set
  20294. if (this.rotationQuaternion) {
  20295. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20296. }
  20297. this._worldMatrix = BABYLON.Matrix.Identity();
  20298. };
  20299. // Cache
  20300. Mesh.prototype._resetPointsArrayCache = function () {
  20301. this._positions = null;
  20302. };
  20303. Mesh.prototype._generatePointsArray = function () {
  20304. if (this._positions)
  20305. return true;
  20306. this._positions = [];
  20307. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20308. if (!data) {
  20309. return false;
  20310. }
  20311. for (var index = 0; index < data.length; index += 3) {
  20312. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20313. }
  20314. return true;
  20315. };
  20316. /**
  20317. * Returns a new Mesh object generated from the current mesh properties.
  20318. * This method must not get confused with createInstance().
  20319. * The parameter `name` is a string, the name given to the new mesh.
  20320. * The optional parameter `newParent` can be any Node object (default `null`).
  20321. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20322. * 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.
  20323. */
  20324. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20325. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20326. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20327. };
  20328. /**
  20329. * Disposes the mesh.
  20330. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20331. */
  20332. Mesh.prototype.dispose = function (doNotRecurse) {
  20333. if (this._geometry) {
  20334. this._geometry.releaseForMesh(this, true);
  20335. }
  20336. // Instances
  20337. if (this._instancesBuffer) {
  20338. this._instancesBuffer.dispose();
  20339. this._instancesBuffer = null;
  20340. }
  20341. while (this.instances.length) {
  20342. this.instances[0].dispose();
  20343. }
  20344. // Highlight layers.
  20345. var highlightLayers = this.getScene().highlightLayers;
  20346. for (var i = 0; i < highlightLayers.length; i++) {
  20347. var highlightLayer = highlightLayers[i];
  20348. if (highlightLayer) {
  20349. highlightLayer.removeMesh(this);
  20350. highlightLayer.removeExcludedMesh(this);
  20351. }
  20352. }
  20353. _super.prototype.dispose.call(this, doNotRecurse);
  20354. };
  20355. /**
  20356. * Modifies the mesh geometry according to a displacement map.
  20357. * 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.
  20358. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20359. * This method returns nothing.
  20360. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20361. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20362. * 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.
  20363. */
  20364. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20365. var _this = this;
  20366. var scene = this.getScene();
  20367. var onload = function (img) {
  20368. // Getting height map data
  20369. var canvas = document.createElement("canvas");
  20370. var context = canvas.getContext("2d");
  20371. var heightMapWidth = img.width;
  20372. var heightMapHeight = img.height;
  20373. canvas.width = heightMapWidth;
  20374. canvas.height = heightMapHeight;
  20375. context.drawImage(img, 0, 0);
  20376. // Create VertexData from map data
  20377. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20378. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20379. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20380. //execute success callback, if set
  20381. if (onSuccess) {
  20382. onSuccess(_this);
  20383. }
  20384. };
  20385. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20386. };
  20387. /**
  20388. * Modifies the mesh geometry according to a displacementMap buffer.
  20389. * 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.
  20390. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20391. * This method returns nothing.
  20392. * 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.
  20393. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20394. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20395. */
  20396. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20397. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20398. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20399. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20400. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20401. return;
  20402. }
  20403. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20404. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20405. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20406. var position = BABYLON.Vector3.Zero();
  20407. var normal = BABYLON.Vector3.Zero();
  20408. var uv = BABYLON.Vector2.Zero();
  20409. for (var index = 0; index < positions.length; index += 3) {
  20410. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20411. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20412. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20413. // Compute height
  20414. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20415. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20416. var pos = (u + v * heightMapWidth) * 4;
  20417. var r = buffer[pos] / 255.0;
  20418. var g = buffer[pos + 1] / 255.0;
  20419. var b = buffer[pos + 2] / 255.0;
  20420. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20421. normal.normalize();
  20422. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20423. position = position.add(normal);
  20424. position.toArray(positions, index);
  20425. }
  20426. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20427. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20428. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20429. };
  20430. /**
  20431. * Modify the mesh to get a flat shading rendering.
  20432. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20433. * This method returns nothing.
  20434. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20435. */
  20436. Mesh.prototype.convertToFlatShadedMesh = function () {
  20437. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20438. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20439. var kinds = this.getVerticesDataKinds();
  20440. var vbs = [];
  20441. var data = [];
  20442. var newdata = [];
  20443. var updatableNormals = false;
  20444. var kindIndex;
  20445. var kind;
  20446. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20447. kind = kinds[kindIndex];
  20448. var vertexBuffer = this.getVertexBuffer(kind);
  20449. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20450. updatableNormals = vertexBuffer.isUpdatable();
  20451. kinds.splice(kindIndex, 1);
  20452. kindIndex--;
  20453. continue;
  20454. }
  20455. vbs[kind] = vertexBuffer;
  20456. data[kind] = vbs[kind].getData();
  20457. newdata[kind] = [];
  20458. }
  20459. // Save previous submeshes
  20460. var previousSubmeshes = this.subMeshes.slice(0);
  20461. var indices = this.getIndices();
  20462. var totalIndices = this.getTotalIndices();
  20463. // Generating unique vertices per face
  20464. var index;
  20465. for (index = 0; index < totalIndices; index++) {
  20466. var vertexIndex = indices[index];
  20467. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20468. kind = kinds[kindIndex];
  20469. var stride = vbs[kind].getStrideSize();
  20470. for (var offset = 0; offset < stride; offset++) {
  20471. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20472. }
  20473. }
  20474. }
  20475. // Updating faces & normal
  20476. var normals = [];
  20477. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20478. for (index = 0; index < totalIndices; index += 3) {
  20479. indices[index] = index;
  20480. indices[index + 1] = index + 1;
  20481. indices[index + 2] = index + 2;
  20482. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20483. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20484. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20485. var p1p2 = p1.subtract(p2);
  20486. var p3p2 = p3.subtract(p2);
  20487. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20488. // Store same normals for every vertex
  20489. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20490. normals.push(normal.x);
  20491. normals.push(normal.y);
  20492. normals.push(normal.z);
  20493. }
  20494. }
  20495. this.setIndices(indices);
  20496. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20497. // Updating vertex buffers
  20498. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20499. kind = kinds[kindIndex];
  20500. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20501. }
  20502. // Updating submeshes
  20503. this.releaseSubMeshes();
  20504. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20505. var previousOne = previousSubmeshes[submeshIndex];
  20506. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20507. }
  20508. this.synchronizeInstances();
  20509. };
  20510. /**
  20511. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20512. * In other words, more vertices, no more indices and a single bigger VBO.
  20513. * This method returns nothing.
  20514. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20515. *
  20516. */
  20517. Mesh.prototype.convertToUnIndexedMesh = function () {
  20518. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20519. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20520. var kinds = this.getVerticesDataKinds();
  20521. var vbs = [];
  20522. var data = [];
  20523. var newdata = [];
  20524. var updatableNormals = false;
  20525. var kindIndex;
  20526. var kind;
  20527. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20528. kind = kinds[kindIndex];
  20529. var vertexBuffer = this.getVertexBuffer(kind);
  20530. vbs[kind] = vertexBuffer;
  20531. data[kind] = vbs[kind].getData();
  20532. newdata[kind] = [];
  20533. }
  20534. // Save previous submeshes
  20535. var previousSubmeshes = this.subMeshes.slice(0);
  20536. var indices = this.getIndices();
  20537. var totalIndices = this.getTotalIndices();
  20538. // Generating unique vertices per face
  20539. var index;
  20540. for (index = 0; index < totalIndices; index++) {
  20541. var vertexIndex = indices[index];
  20542. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20543. kind = kinds[kindIndex];
  20544. var stride = vbs[kind].getStrideSize();
  20545. for (var offset = 0; offset < stride; offset++) {
  20546. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20547. }
  20548. }
  20549. }
  20550. // Updating indices
  20551. for (index = 0; index < totalIndices; index += 3) {
  20552. indices[index] = index;
  20553. indices[index + 1] = index + 1;
  20554. indices[index + 2] = index + 2;
  20555. }
  20556. this.setIndices(indices);
  20557. // Updating vertex buffers
  20558. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20559. kind = kinds[kindIndex];
  20560. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20561. }
  20562. // Updating submeshes
  20563. this.releaseSubMeshes();
  20564. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20565. var previousOne = previousSubmeshes[submeshIndex];
  20566. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20567. }
  20568. this._unIndexed = true;
  20569. this.synchronizeInstances();
  20570. };
  20571. /**
  20572. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20573. * This method returns nothing.
  20574. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20575. */
  20576. Mesh.prototype.flipFaces = function (flipNormals) {
  20577. if (flipNormals === void 0) { flipNormals = false; }
  20578. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20579. var i;
  20580. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20581. for (i = 0; i < vertex_data.normals.length; i++) {
  20582. vertex_data.normals[i] *= -1;
  20583. }
  20584. }
  20585. var temp;
  20586. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20587. // reassign indices
  20588. temp = vertex_data.indices[i + 1];
  20589. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20590. vertex_data.indices[i + 2] = temp;
  20591. }
  20592. vertex_data.applyToMesh(this);
  20593. };
  20594. // Instances
  20595. /**
  20596. * Creates a new InstancedMesh object from the mesh model.
  20597. * An instance shares the same properties and the same material than its model.
  20598. * Only these properties of each instance can then be set individually :
  20599. * - position
  20600. * - rotation
  20601. * - rotationQuaternion
  20602. * - setPivotMatrix
  20603. * - scaling
  20604. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20605. * Warning : this method is not supported for Line mesh and LineSystem
  20606. */
  20607. Mesh.prototype.createInstance = function (name) {
  20608. return new BABYLON.InstancedMesh(name, this);
  20609. };
  20610. /**
  20611. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20612. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20613. * This method returns nothing.
  20614. */
  20615. Mesh.prototype.synchronizeInstances = function () {
  20616. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20617. var instance = this.instances[instanceIndex];
  20618. instance._syncSubMeshes();
  20619. }
  20620. };
  20621. /**
  20622. * Simplify the mesh according to the given array of settings.
  20623. * Function will return immediately and will simplify async. It returns nothing.
  20624. * @param settings a collection of simplification settings.
  20625. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20626. * @param type the type of simplification to run.
  20627. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20628. */
  20629. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20630. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20631. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20632. this.getScene().simplificationQueue.addTask({
  20633. settings: settings,
  20634. parallelProcessing: parallelProcessing,
  20635. mesh: this,
  20636. simplificationType: simplificationType,
  20637. successCallback: successCallback
  20638. });
  20639. };
  20640. /**
  20641. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20642. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20643. * This should be used together with the simplification to avoid disappearing triangles.
  20644. * @param successCallback an optional success callback to be called after the optimization finished.
  20645. */
  20646. Mesh.prototype.optimizeIndices = function (successCallback) {
  20647. var _this = this;
  20648. var indices = this.getIndices();
  20649. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20650. var vectorPositions = [];
  20651. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20652. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20653. }
  20654. var dupes = [];
  20655. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20656. var realPos = vectorPositions.length - 1 - iteration;
  20657. var testedPosition = vectorPositions[realPos];
  20658. for (var j = 0; j < realPos; ++j) {
  20659. var againstPosition = vectorPositions[j];
  20660. if (testedPosition.equals(againstPosition)) {
  20661. dupes[realPos] = j;
  20662. break;
  20663. }
  20664. }
  20665. }, function () {
  20666. for (var i = 0; i < indices.length; ++i) {
  20667. indices[i] = dupes[indices[i]] || indices[i];
  20668. }
  20669. //indices are now reordered
  20670. var originalSubMeshes = _this.subMeshes.slice(0);
  20671. _this.setIndices(indices);
  20672. _this.subMeshes = originalSubMeshes;
  20673. if (successCallback) {
  20674. successCallback(_this);
  20675. }
  20676. });
  20677. };
  20678. // Statics
  20679. /**
  20680. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20681. * The parameter `parsedMesh` is the mesh to be copied.
  20682. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20683. */
  20684. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20685. var mesh = new Mesh(parsedMesh.name, scene);
  20686. mesh.id = parsedMesh.id;
  20687. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20688. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20689. if (parsedMesh.metadata !== undefined) {
  20690. mesh.metadata = parsedMesh.metadata;
  20691. }
  20692. if (parsedMesh.rotationQuaternion) {
  20693. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20694. }
  20695. else if (parsedMesh.rotation) {
  20696. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20697. }
  20698. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20699. if (parsedMesh.localMatrix) {
  20700. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20701. }
  20702. else if (parsedMesh.pivotMatrix) {
  20703. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20704. }
  20705. mesh.setEnabled(parsedMesh.isEnabled);
  20706. mesh.isVisible = parsedMesh.isVisible;
  20707. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20708. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20709. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20710. if (parsedMesh.applyFog !== undefined) {
  20711. mesh.applyFog = parsedMesh.applyFog;
  20712. }
  20713. if (parsedMesh.pickable !== undefined) {
  20714. mesh.isPickable = parsedMesh.pickable;
  20715. }
  20716. if (parsedMesh.alphaIndex !== undefined) {
  20717. mesh.alphaIndex = parsedMesh.alphaIndex;
  20718. }
  20719. mesh.receiveShadows = parsedMesh.receiveShadows;
  20720. mesh.billboardMode = parsedMesh.billboardMode;
  20721. if (parsedMesh.visibility !== undefined) {
  20722. mesh.visibility = parsedMesh.visibility;
  20723. }
  20724. mesh.checkCollisions = parsedMesh.checkCollisions;
  20725. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20726. // freezeWorldMatrix
  20727. if (parsedMesh.freezeWorldMatrix) {
  20728. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20729. }
  20730. // Parent
  20731. if (parsedMesh.parentId) {
  20732. mesh._waitingParentId = parsedMesh.parentId;
  20733. }
  20734. // Actions
  20735. if (parsedMesh.actions !== undefined) {
  20736. mesh._waitingActions = parsedMesh.actions;
  20737. }
  20738. // Geometry
  20739. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20740. if (parsedMesh.delayLoadingFile) {
  20741. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20742. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20743. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20744. if (parsedMesh._binaryInfo) {
  20745. mesh._binaryInfo = parsedMesh._binaryInfo;
  20746. }
  20747. mesh._delayInfo = [];
  20748. if (parsedMesh.hasUVs) {
  20749. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20750. }
  20751. if (parsedMesh.hasUVs2) {
  20752. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20753. }
  20754. if (parsedMesh.hasUVs3) {
  20755. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20756. }
  20757. if (parsedMesh.hasUVs4) {
  20758. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20759. }
  20760. if (parsedMesh.hasUVs5) {
  20761. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20762. }
  20763. if (parsedMesh.hasUVs6) {
  20764. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20765. }
  20766. if (parsedMesh.hasColors) {
  20767. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20768. }
  20769. if (parsedMesh.hasMatricesIndices) {
  20770. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20771. }
  20772. if (parsedMesh.hasMatricesWeights) {
  20773. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20774. }
  20775. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20776. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20777. mesh._checkDelayState();
  20778. }
  20779. }
  20780. else {
  20781. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20782. }
  20783. // Material
  20784. if (parsedMesh.materialId) {
  20785. mesh.setMaterialByID(parsedMesh.materialId);
  20786. }
  20787. else {
  20788. mesh.material = null;
  20789. }
  20790. // Skeleton
  20791. if (parsedMesh.skeletonId > -1) {
  20792. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20793. if (parsedMesh.numBoneInfluencers) {
  20794. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20795. }
  20796. }
  20797. // Animations
  20798. if (parsedMesh.animations) {
  20799. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20800. var parsedAnimation = parsedMesh.animations[animationIndex];
  20801. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20802. }
  20803. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20804. }
  20805. if (parsedMesh.autoAnimate) {
  20806. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20807. }
  20808. // Layer Mask
  20809. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20810. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20811. }
  20812. else {
  20813. mesh.layerMask = 0x0FFFFFFF;
  20814. }
  20815. //(Deprecated) physics
  20816. if (parsedMesh.physicsImpostor) {
  20817. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20818. mass: parsedMesh.physicsMass,
  20819. friction: parsedMesh.physicsFriction,
  20820. restitution: parsedMesh.physicsRestitution
  20821. }, scene);
  20822. }
  20823. // Instances
  20824. if (parsedMesh.instances) {
  20825. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20826. var parsedInstance = parsedMesh.instances[index];
  20827. var instance = mesh.createInstance(parsedInstance.name);
  20828. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20829. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20830. if (parsedInstance.parentId) {
  20831. instance._waitingParentId = parsedInstance.parentId;
  20832. }
  20833. if (parsedInstance.rotationQuaternion) {
  20834. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20835. }
  20836. else if (parsedInstance.rotation) {
  20837. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20838. }
  20839. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20840. instance.checkCollisions = mesh.checkCollisions;
  20841. if (parsedMesh.animations) {
  20842. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20843. parsedAnimation = parsedMesh.animations[animationIndex];
  20844. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20845. }
  20846. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20847. }
  20848. }
  20849. }
  20850. return mesh;
  20851. };
  20852. /**
  20853. * Creates a ribbon mesh.
  20854. * Please consider using the same method from the MeshBuilder class instead.
  20855. * 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.
  20856. *
  20857. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20858. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20859. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20860. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20861. * 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.
  20862. * 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.
  20863. * 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
  20864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20867. */
  20868. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20869. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20870. pathArray: pathArray,
  20871. closeArray: closeArray,
  20872. closePath: closePath,
  20873. offset: offset,
  20874. updatable: updatable,
  20875. sideOrientation: sideOrientation,
  20876. instance: instance
  20877. }, scene);
  20878. };
  20879. /**
  20880. * Creates a plane polygonal mesh. By default, this is a disc.
  20881. * Please consider using the same method from the MeshBuilder class instead.
  20882. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20883. * 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.
  20884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20887. */
  20888. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20889. var options = {
  20890. radius: radius,
  20891. tessellation: tessellation,
  20892. sideOrientation: sideOrientation,
  20893. updatable: updatable
  20894. };
  20895. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20896. };
  20897. /**
  20898. * Creates a box mesh.
  20899. * Please consider using the same method from the MeshBuilder class instead.
  20900. * The parameter `size` sets the size (float) of each box side (default 1).
  20901. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20902. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20903. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20904. */
  20905. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20906. var options = {
  20907. size: size,
  20908. sideOrientation: sideOrientation,
  20909. updatable: updatable
  20910. };
  20911. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20912. };
  20913. /**
  20914. * Creates a sphere mesh.
  20915. * Please consider using the same method from the MeshBuilder class instead.
  20916. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20917. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20918. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20921. */
  20922. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20923. var options = {
  20924. segments: segments,
  20925. diameterX: diameter,
  20926. diameterY: diameter,
  20927. diameterZ: diameter,
  20928. sideOrientation: sideOrientation,
  20929. updatable: updatable
  20930. };
  20931. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20932. };
  20933. /**
  20934. * Creates a cylinder or a cone mesh.
  20935. * Please consider using the same method from the MeshBuilder class instead.
  20936. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20937. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20938. * 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.
  20939. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20940. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20944. */
  20945. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20946. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20947. if (scene !== undefined) {
  20948. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20949. updatable = scene;
  20950. }
  20951. scene = subdivisions;
  20952. subdivisions = 1;
  20953. }
  20954. var options = {
  20955. height: height,
  20956. diameterTop: diameterTop,
  20957. diameterBottom: diameterBottom,
  20958. tessellation: tessellation,
  20959. subdivisions: subdivisions,
  20960. sideOrientation: sideOrientation,
  20961. updatable: updatable
  20962. };
  20963. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20964. };
  20965. // Torus (Code from SharpDX.org)
  20966. /**
  20967. * Creates a torus mesh.
  20968. * Please consider using the same method from the MeshBuilder class instead.
  20969. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20970. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20971. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20972. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20973. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20975. */
  20976. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20977. var options = {
  20978. diameter: diameter,
  20979. thickness: thickness,
  20980. tessellation: tessellation,
  20981. sideOrientation: sideOrientation,
  20982. updatable: updatable
  20983. };
  20984. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20985. };
  20986. /**
  20987. * Creates a torus knot mesh.
  20988. * Please consider using the same method from the MeshBuilder class instead.
  20989. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20990. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20991. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20992. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20994. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20996. */
  20997. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20998. var options = {
  20999. radius: radius,
  21000. tube: tube,
  21001. radialSegments: radialSegments,
  21002. tubularSegments: tubularSegments,
  21003. p: p,
  21004. q: q,
  21005. sideOrientation: sideOrientation,
  21006. updatable: updatable
  21007. };
  21008. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21009. };
  21010. /**
  21011. * Creates a line mesh.
  21012. * Please consider using the same method from the MeshBuilder class instead.
  21013. * 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.
  21014. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21015. * The parameter `points` is an array successive Vector3.
  21016. * 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
  21017. * When updating an instance, remember that only point positions can change, not the number of points.
  21018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21019. */
  21020. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21021. var options = {
  21022. points: points,
  21023. updatable: updatable,
  21024. instance: instance
  21025. };
  21026. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21027. };
  21028. /**
  21029. * Creates a dashed line mesh.
  21030. * Please consider using the same method from the MeshBuilder class instead.
  21031. * 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.
  21032. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21033. * The parameter `points` is an array successive Vector3.
  21034. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21035. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21036. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21037. * 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
  21038. * When updating an instance, remember that only point positions can change, not the number of points.
  21039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21040. */
  21041. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21042. var options = {
  21043. points: points,
  21044. dashSize: dashSize,
  21045. gapSize: gapSize,
  21046. dashNb: dashNb,
  21047. updatable: updatable,
  21048. instance: instance
  21049. };
  21050. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21051. };
  21052. /**
  21053. * Creates an extruded shape mesh.
  21054. * 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.
  21055. * Please consider using the same method from the MeshBuilder class instead.
  21056. *
  21057. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21058. * 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
  21059. * extruded along the Z axis.
  21060. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21061. * 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.
  21062. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21063. * 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
  21064. * 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
  21065. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21066. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21067. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21069. */
  21070. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21071. var options = {
  21072. shape: shape,
  21073. path: path,
  21074. scale: scale,
  21075. rotation: rotation,
  21076. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21077. sideOrientation: sideOrientation,
  21078. instance: instance,
  21079. updatable: updatable
  21080. };
  21081. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21082. };
  21083. /**
  21084. * Creates an custom extruded shape mesh.
  21085. * 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.
  21086. * Please consider using the same method from the MeshBuilder class instead.
  21087. *
  21088. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21089. * 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
  21090. * extruded along the Z axis.
  21091. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21092. * 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
  21093. * and the distance of this point from the begining of the path :
  21094. * ```javascript
  21095. * var rotationFunction = function(i, distance) {
  21096. * // do things
  21097. * return rotationValue; }
  21098. * ```
  21099. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21100. * 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
  21101. * and the distance of this point from the begining of the path :
  21102. * ```javascript
  21103. * var scaleFunction = function(i, distance) {
  21104. * // do things
  21105. * return scaleValue;}
  21106. * ```
  21107. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21108. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21109. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21110. * 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
  21111. * 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
  21112. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21113. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21114. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21115. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21116. */
  21117. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21118. var options = {
  21119. shape: shape,
  21120. path: path,
  21121. scaleFunction: scaleFunction,
  21122. rotationFunction: rotationFunction,
  21123. ribbonCloseArray: ribbonCloseArray,
  21124. ribbonClosePath: ribbonClosePath,
  21125. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21126. sideOrientation: sideOrientation,
  21127. instance: instance,
  21128. updatable: updatable
  21129. };
  21130. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21131. };
  21132. /**
  21133. * Creates lathe mesh.
  21134. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21135. * Please consider using the same method from the MeshBuilder class instead.
  21136. * 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
  21137. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21138. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21139. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21140. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21141. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21142. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21143. */
  21144. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21145. var options = {
  21146. shape: shape,
  21147. radius: radius,
  21148. tessellation: tessellation,
  21149. sideOrientation: sideOrientation,
  21150. updatable: updatable
  21151. };
  21152. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21153. };
  21154. /**
  21155. * Creates a plane mesh.
  21156. * Please consider using the same method from the MeshBuilder class instead.
  21157. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21158. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21161. */
  21162. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21163. var options = {
  21164. size: size,
  21165. width: size,
  21166. height: size,
  21167. sideOrientation: sideOrientation,
  21168. updatable: updatable
  21169. };
  21170. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21171. };
  21172. /**
  21173. * Creates a ground mesh.
  21174. * Please consider using the same method from the MeshBuilder class instead.
  21175. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21176. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21178. */
  21179. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21180. var options = {
  21181. width: width,
  21182. height: height,
  21183. subdivisions: subdivisions,
  21184. updatable: updatable
  21185. };
  21186. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21187. };
  21188. /**
  21189. * Creates a tiled ground mesh.
  21190. * Please consider using the same method from the MeshBuilder class instead.
  21191. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21192. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21193. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21194. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21195. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21196. * numbers of subdivisions on the ground width and height of each tile.
  21197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21198. */
  21199. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21200. var options = {
  21201. xmin: xmin,
  21202. zmin: zmin,
  21203. xmax: xmax,
  21204. zmax: zmax,
  21205. subdivisions: subdivisions,
  21206. precision: precision,
  21207. updatable: updatable
  21208. };
  21209. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21210. };
  21211. /**
  21212. * Creates a ground mesh from a height map.
  21213. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21214. * Please consider using the same method from the MeshBuilder class instead.
  21215. * The parameter `url` sets the URL of the height map image resource.
  21216. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21217. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21218. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21219. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21220. * 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).
  21221. * This function is passed the newly built mesh :
  21222. * ```javascript
  21223. * function(mesh) { // do things
  21224. * return; }
  21225. * ```
  21226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21227. */
  21228. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21229. var options = {
  21230. width: width,
  21231. height: height,
  21232. subdivisions: subdivisions,
  21233. minHeight: minHeight,
  21234. maxHeight: maxHeight,
  21235. updatable: updatable,
  21236. onReady: onReady
  21237. };
  21238. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21239. };
  21240. /**
  21241. * Creates a tube mesh.
  21242. * 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.
  21243. * Please consider using the same method from the MeshBuilder class instead.
  21244. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21245. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21246. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21247. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21248. * 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.
  21249. * It must return a radius value (positive float) :
  21250. * ```javascript
  21251. * var radiusFunction = function(i, distance) {
  21252. * // do things
  21253. * return radius; }
  21254. * ```
  21255. * 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
  21256. * 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
  21257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21260. */
  21261. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21262. var options = {
  21263. path: path,
  21264. radius: radius,
  21265. tessellation: tessellation,
  21266. radiusFunction: radiusFunction,
  21267. arc: 1,
  21268. cap: cap,
  21269. updatable: updatable,
  21270. sideOrientation: sideOrientation,
  21271. instance: instance
  21272. };
  21273. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21274. };
  21275. /**
  21276. * Creates a polyhedron mesh.
  21277. * Please consider using the same method from the MeshBuilder class instead.
  21278. * 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
  21279. * to choose the wanted type.
  21280. * The parameter `size` (positive float, default 1) sets the polygon size.
  21281. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21282. * 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`.
  21283. * 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
  21284. * 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)`).
  21285. * 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
  21286. * 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.
  21287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21290. */
  21291. Mesh.CreatePolyhedron = function (name, options, scene) {
  21292. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21293. };
  21294. /**
  21295. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21296. * Please consider using the same method from the MeshBuilder class instead.
  21297. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21298. * 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`).
  21299. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21300. * 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.
  21301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21304. */
  21305. Mesh.CreateIcoSphere = function (name, options, scene) {
  21306. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21307. };
  21308. /**
  21309. * Creates a decal mesh.
  21310. * Please consider using the same method from the MeshBuilder class instead.
  21311. * 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.
  21312. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21313. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21314. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21315. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21316. */
  21317. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21318. var options = {
  21319. position: position,
  21320. normal: normal,
  21321. size: size,
  21322. angle: angle
  21323. };
  21324. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21325. };
  21326. // Skeletons
  21327. /**
  21328. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21329. */
  21330. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21331. var source;
  21332. if (!this._sourcePositions) {
  21333. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21334. this._sourcePositions = new Float32Array(source);
  21335. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21336. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21337. }
  21338. }
  21339. return this._sourcePositions;
  21340. };
  21341. /**
  21342. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21343. */
  21344. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21345. var source;
  21346. if (!this._sourceNormals) {
  21347. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21348. this._sourceNormals = new Float32Array(source);
  21349. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21350. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21351. }
  21352. }
  21353. return this._sourceNormals;
  21354. };
  21355. /**
  21356. * Update the vertex buffers by applying transformation from the bones
  21357. * @param {skeleton} skeleton to apply
  21358. */
  21359. Mesh.prototype.applySkeleton = function (skeleton) {
  21360. if (!this.geometry) {
  21361. return;
  21362. }
  21363. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21364. return;
  21365. }
  21366. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21367. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21368. return this;
  21369. }
  21370. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21371. return this;
  21372. }
  21373. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21374. return this;
  21375. }
  21376. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21377. return this;
  21378. }
  21379. if (!this._sourcePositions) {
  21380. this.setPositionsForCPUSkinning();
  21381. }
  21382. if (!this._sourceNormals) {
  21383. this.setNormalsForCPUSkinning();
  21384. }
  21385. // positionsData checks for not being Float32Array will only pass at most once
  21386. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21387. if (!(positionsData instanceof Float32Array)) {
  21388. positionsData = new Float32Array(positionsData);
  21389. }
  21390. // normalsData checks for not being Float32Array will only pass at most once
  21391. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21392. if (!(normalsData instanceof Float32Array)) {
  21393. normalsData = new Float32Array(normalsData);
  21394. }
  21395. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21396. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21397. var needExtras = this.numBoneInfluencers > 4;
  21398. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21399. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21400. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21401. var tempVector3 = BABYLON.Vector3.Zero();
  21402. var finalMatrix = new BABYLON.Matrix();
  21403. var tempMatrix = new BABYLON.Matrix();
  21404. var matWeightIdx = 0;
  21405. var inf;
  21406. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21407. var weight;
  21408. for (inf = 0; inf < 4; inf++) {
  21409. weight = matricesWeightsData[matWeightIdx + inf];
  21410. if (weight > 0) {
  21411. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21412. finalMatrix.addToSelf(tempMatrix);
  21413. }
  21414. else
  21415. break;
  21416. }
  21417. if (needExtras) {
  21418. for (inf = 0; inf < 4; inf++) {
  21419. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21420. if (weight > 0) {
  21421. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21422. finalMatrix.addToSelf(tempMatrix);
  21423. }
  21424. else
  21425. break;
  21426. }
  21427. }
  21428. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21429. tempVector3.toArray(positionsData, index);
  21430. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21431. tempVector3.toArray(normalsData, index);
  21432. finalMatrix.reset();
  21433. }
  21434. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21435. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21436. return this;
  21437. };
  21438. // Tools
  21439. /**
  21440. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21441. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21442. */
  21443. Mesh.MinMax = function (meshes) {
  21444. var minVector = null;
  21445. var maxVector = null;
  21446. meshes.forEach(function (mesh, index, array) {
  21447. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21448. if (!minVector) {
  21449. minVector = boundingBox.minimumWorld;
  21450. maxVector = boundingBox.maximumWorld;
  21451. }
  21452. else {
  21453. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21454. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21455. }
  21456. });
  21457. return {
  21458. min: minVector,
  21459. max: maxVector
  21460. };
  21461. };
  21462. /**
  21463. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21464. */
  21465. Mesh.Center = function (meshesOrMinMaxVector) {
  21466. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21467. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21468. };
  21469. /**
  21470. * Merge the array of meshes into a single mesh for performance reasons.
  21471. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21472. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21473. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21474. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21475. */
  21476. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21477. if (disposeSource === void 0) { disposeSource = true; }
  21478. var index;
  21479. if (!allow32BitsIndices) {
  21480. var totalVertices = 0;
  21481. // Counting vertices
  21482. for (index = 0; index < meshes.length; index++) {
  21483. if (meshes[index]) {
  21484. totalVertices += meshes[index].getTotalVertices();
  21485. if (totalVertices > 65536) {
  21486. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21487. return null;
  21488. }
  21489. }
  21490. }
  21491. }
  21492. // Merge
  21493. var vertexData;
  21494. var otherVertexData;
  21495. var source;
  21496. for (index = 0; index < meshes.length; index++) {
  21497. if (meshes[index]) {
  21498. meshes[index].computeWorldMatrix(true);
  21499. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21500. otherVertexData.transform(meshes[index].getWorldMatrix());
  21501. if (vertexData) {
  21502. vertexData.merge(otherVertexData);
  21503. }
  21504. else {
  21505. vertexData = otherVertexData;
  21506. source = meshes[index];
  21507. }
  21508. }
  21509. }
  21510. if (!meshSubclass) {
  21511. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21512. }
  21513. vertexData.applyToMesh(meshSubclass);
  21514. // Setting properties
  21515. meshSubclass.material = source.material;
  21516. meshSubclass.checkCollisions = source.checkCollisions;
  21517. // Cleaning
  21518. if (disposeSource) {
  21519. for (index = 0; index < meshes.length; index++) {
  21520. if (meshes[index]) {
  21521. meshes[index].dispose();
  21522. }
  21523. }
  21524. }
  21525. return meshSubclass;
  21526. };
  21527. // Consts
  21528. Mesh._FRONTSIDE = 0;
  21529. Mesh._BACKSIDE = 1;
  21530. Mesh._DOUBLESIDE = 2;
  21531. Mesh._DEFAULTSIDE = 0;
  21532. Mesh._NO_CAP = 0;
  21533. Mesh._CAP_START = 1;
  21534. Mesh._CAP_END = 2;
  21535. Mesh._CAP_ALL = 3;
  21536. return Mesh;
  21537. }(BABYLON.AbstractMesh));
  21538. BABYLON.Mesh = Mesh;
  21539. })(BABYLON || (BABYLON = {}));
  21540. var BABYLON;
  21541. (function (BABYLON) {
  21542. var SubMesh = (function () {
  21543. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21544. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21545. this.materialIndex = materialIndex;
  21546. this.verticesStart = verticesStart;
  21547. this.verticesCount = verticesCount;
  21548. this.indexStart = indexStart;
  21549. this.indexCount = indexCount;
  21550. this._renderId = 0;
  21551. this._mesh = mesh;
  21552. this._renderingMesh = renderingMesh || mesh;
  21553. mesh.subMeshes.push(this);
  21554. this._trianglePlanes = [];
  21555. this._id = mesh.subMeshes.length - 1;
  21556. if (createBoundingBox) {
  21557. this.refreshBoundingInfo();
  21558. mesh.computeWorldMatrix(true);
  21559. }
  21560. }
  21561. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21562. get: function () {
  21563. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21564. },
  21565. enumerable: true,
  21566. configurable: true
  21567. });
  21568. SubMesh.prototype.getBoundingInfo = function () {
  21569. if (this.IsGlobal) {
  21570. return this._mesh.getBoundingInfo();
  21571. }
  21572. return this._boundingInfo;
  21573. };
  21574. SubMesh.prototype.getMesh = function () {
  21575. return this._mesh;
  21576. };
  21577. SubMesh.prototype.getRenderingMesh = function () {
  21578. return this._renderingMesh;
  21579. };
  21580. SubMesh.prototype.getMaterial = function () {
  21581. var rootMaterial = this._renderingMesh.material;
  21582. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21583. var multiMaterial = rootMaterial;
  21584. return multiMaterial.getSubMaterial(this.materialIndex);
  21585. }
  21586. if (!rootMaterial) {
  21587. return this._mesh.getScene().defaultMaterial;
  21588. }
  21589. return rootMaterial;
  21590. };
  21591. // Methods
  21592. SubMesh.prototype.refreshBoundingInfo = function () {
  21593. this._lastColliderWorldVertices = null;
  21594. if (this.IsGlobal) {
  21595. return;
  21596. }
  21597. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21598. if (!data) {
  21599. this._boundingInfo = this._mesh._boundingInfo;
  21600. return;
  21601. }
  21602. var indices = this._renderingMesh.getIndices();
  21603. var extend;
  21604. //is this the only submesh?
  21605. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21606. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21607. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21608. }
  21609. else {
  21610. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21611. }
  21612. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21613. };
  21614. SubMesh.prototype._checkCollision = function (collider) {
  21615. return this.getBoundingInfo()._checkCollision(collider);
  21616. };
  21617. SubMesh.prototype.updateBoundingInfo = function (world) {
  21618. if (!this.getBoundingInfo()) {
  21619. this.refreshBoundingInfo();
  21620. }
  21621. this.getBoundingInfo().update(world);
  21622. };
  21623. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21624. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21625. };
  21626. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21627. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21628. };
  21629. SubMesh.prototype.render = function (enableAlphaMode) {
  21630. this._renderingMesh.render(this, enableAlphaMode);
  21631. };
  21632. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21633. if (!this._linesIndexBuffer) {
  21634. var linesIndices = [];
  21635. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21636. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21637. }
  21638. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21639. this.linesIndexCount = linesIndices.length;
  21640. }
  21641. return this._linesIndexBuffer;
  21642. };
  21643. SubMesh.prototype.canIntersects = function (ray) {
  21644. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21645. };
  21646. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21647. var intersectInfo = null;
  21648. // LineMesh first as it's also a Mesh...
  21649. if (this._mesh instanceof BABYLON.LinesMesh) {
  21650. var lineMesh = this._mesh;
  21651. // Line test
  21652. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21653. var p0 = positions[indices[index]];
  21654. var p1 = positions[indices[index + 1]];
  21655. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21656. if (length < 0) {
  21657. continue;
  21658. }
  21659. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21660. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21661. if (fastCheck) {
  21662. break;
  21663. }
  21664. }
  21665. }
  21666. }
  21667. else {
  21668. // Triangles test
  21669. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21670. var p0 = positions[indices[index]];
  21671. var p1 = positions[indices[index + 1]];
  21672. var p2 = positions[indices[index + 2]];
  21673. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21674. if (currentIntersectInfo) {
  21675. if (currentIntersectInfo.distance < 0) {
  21676. continue;
  21677. }
  21678. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21679. intersectInfo = currentIntersectInfo;
  21680. intersectInfo.faceId = index / 3;
  21681. if (fastCheck) {
  21682. break;
  21683. }
  21684. }
  21685. }
  21686. }
  21687. }
  21688. return intersectInfo;
  21689. };
  21690. // Clone
  21691. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21692. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21693. if (!this.IsGlobal) {
  21694. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21695. }
  21696. return result;
  21697. };
  21698. // Dispose
  21699. SubMesh.prototype.dispose = function () {
  21700. if (this._linesIndexBuffer) {
  21701. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21702. this._linesIndexBuffer = null;
  21703. }
  21704. // Remove from mesh
  21705. var index = this._mesh.subMeshes.indexOf(this);
  21706. this._mesh.subMeshes.splice(index, 1);
  21707. };
  21708. // Statics
  21709. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21710. var minVertexIndex = Number.MAX_VALUE;
  21711. var maxVertexIndex = -Number.MAX_VALUE;
  21712. renderingMesh = renderingMesh || mesh;
  21713. var indices = renderingMesh.getIndices();
  21714. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21715. var vertexIndex = indices[index];
  21716. if (vertexIndex < minVertexIndex)
  21717. minVertexIndex = vertexIndex;
  21718. if (vertexIndex > maxVertexIndex)
  21719. maxVertexIndex = vertexIndex;
  21720. }
  21721. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21722. };
  21723. return SubMesh;
  21724. }());
  21725. BABYLON.SubMesh = SubMesh;
  21726. })(BABYLON || (BABYLON = {}));
  21727. var BABYLON;
  21728. (function (BABYLON) {
  21729. var MeshBuilder = (function () {
  21730. function MeshBuilder() {
  21731. }
  21732. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21733. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21734. return BABYLON.Mesh.DOUBLESIDE;
  21735. }
  21736. if (orientation === undefined || orientation === null) {
  21737. return BABYLON.Mesh.FRONTSIDE;
  21738. }
  21739. return orientation;
  21740. };
  21741. /**
  21742. * Creates a box mesh.
  21743. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21744. * The parameter `size` sets the size (float) of each box side (default 1).
  21745. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21746. * 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).
  21747. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21749. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21751. */
  21752. MeshBuilder.CreateBox = function (name, options, scene) {
  21753. var box = new BABYLON.Mesh(name, scene);
  21754. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21755. var vertexData = BABYLON.VertexData.CreateBox(options);
  21756. vertexData.applyToMesh(box, options.updatable);
  21757. return box;
  21758. };
  21759. /**
  21760. * Creates a sphere mesh.
  21761. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21762. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21763. * 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`).
  21764. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21765. * 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
  21766. * 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).
  21767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21770. */
  21771. MeshBuilder.CreateSphere = function (name, options, scene) {
  21772. var sphere = new BABYLON.Mesh(name, scene);
  21773. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21774. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21775. vertexData.applyToMesh(sphere, options.updatable);
  21776. return sphere;
  21777. };
  21778. /**
  21779. * Creates a plane polygonal mesh. By default, this is a disc.
  21780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21781. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21782. * 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.
  21783. * 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
  21784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21787. */
  21788. MeshBuilder.CreateDisc = function (name, options, scene) {
  21789. var disc = new BABYLON.Mesh(name, scene);
  21790. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21791. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21792. vertexData.applyToMesh(disc, options.updatable);
  21793. return disc;
  21794. };
  21795. /**
  21796. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21797. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21798. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21799. * 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`).
  21800. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21801. * 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.
  21802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21803. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21805. */
  21806. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21807. var sphere = new BABYLON.Mesh(name, scene);
  21808. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21809. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21810. vertexData.applyToMesh(sphere, options.updatable);
  21811. return sphere;
  21812. };
  21813. ;
  21814. /**
  21815. * Creates a ribbon mesh.
  21816. * 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.
  21817. *
  21818. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21819. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21820. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21821. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21822. * 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.
  21823. * 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.
  21824. * 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
  21825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21827. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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.CreateRibbon = function (name, options, scene) {
  21831. var pathArray = options.pathArray;
  21832. var closeArray = options.closeArray;
  21833. var closePath = options.closePath;
  21834. var offset = options.offset;
  21835. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21836. var instance = options.instance;
  21837. var updatable = options.updatable;
  21838. if (instance) {
  21839. // positionFunction : ribbon case
  21840. // only pathArray and sideOrientation parameters are taken into account for positions update
  21841. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21842. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21843. var positionFunction = function (positions) {
  21844. var minlg = pathArray[0].length;
  21845. var i = 0;
  21846. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21847. for (var si = 1; si <= ns; si++) {
  21848. for (var p = 0; p < pathArray.length; p++) {
  21849. var path = pathArray[p];
  21850. var l = path.length;
  21851. minlg = (minlg < l) ? minlg : l;
  21852. var j = 0;
  21853. while (j < minlg) {
  21854. positions[i] = path[j].x;
  21855. positions[i + 1] = path[j].y;
  21856. positions[i + 2] = path[j].z;
  21857. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21858. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21859. }
  21860. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21861. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21862. }
  21863. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21864. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21865. }
  21866. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21867. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21868. }
  21869. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21870. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21871. }
  21872. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21873. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21874. }
  21875. j++;
  21876. i += 3;
  21877. }
  21878. if (instance._closePath) {
  21879. positions[i] = path[0].x;
  21880. positions[i + 1] = path[0].y;
  21881. positions[i + 2] = path[0].z;
  21882. i += 3;
  21883. }
  21884. }
  21885. }
  21886. };
  21887. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21888. positionFunction(positions);
  21889. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21890. instance._boundingInfo.update(instance._worldMatrix);
  21891. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21892. if (!(instance.areNormalsFrozen)) {
  21893. var indices = instance.getIndices();
  21894. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21895. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21896. if (instance._closePath) {
  21897. var indexFirst = 0;
  21898. var indexLast = 0;
  21899. for (var p = 0; p < pathArray.length; p++) {
  21900. indexFirst = instance._idx[p] * 3;
  21901. if (p + 1 < pathArray.length) {
  21902. indexLast = (instance._idx[p + 1] - 1) * 3;
  21903. }
  21904. else {
  21905. indexLast = normals.length - 3;
  21906. }
  21907. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21908. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21909. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21910. normals[indexLast] = normals[indexFirst];
  21911. normals[indexLast + 1] = normals[indexFirst + 1];
  21912. normals[indexLast + 2] = normals[indexFirst + 2];
  21913. }
  21914. }
  21915. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21916. }
  21917. return instance;
  21918. }
  21919. else {
  21920. var ribbon = new BABYLON.Mesh(name, scene);
  21921. ribbon.sideOrientation = sideOrientation;
  21922. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21923. if (closePath) {
  21924. ribbon._idx = vertexData._idx;
  21925. }
  21926. ribbon._closePath = closePath;
  21927. ribbon._closeArray = closeArray;
  21928. vertexData.applyToMesh(ribbon, updatable);
  21929. return ribbon;
  21930. }
  21931. };
  21932. /**
  21933. * Creates a cylinder or a cone mesh.
  21934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21935. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21936. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21937. * 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.
  21938. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21939. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21940. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21941. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21942. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21943. * 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).
  21944. * 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
  21945. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21946. * 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
  21947. * 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.
  21948. * If `enclose` is false, a ring surface is one element.
  21949. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21950. * 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
  21951. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21952. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21954. */
  21955. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21956. var cylinder = new BABYLON.Mesh(name, scene);
  21957. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21958. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21959. vertexData.applyToMesh(cylinder, options.updatable);
  21960. return cylinder;
  21961. };
  21962. /**
  21963. * Creates a torus mesh.
  21964. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21965. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21966. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21967. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21968. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21969. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateTorus = function (name, options, scene) {
  21973. var torus = new BABYLON.Mesh(name, scene);
  21974. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21975. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21976. vertexData.applyToMesh(torus, options.updatable);
  21977. return torus;
  21978. };
  21979. /**
  21980. * Creates a torus knot mesh.
  21981. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21982. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21983. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21984. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21985. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21987. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21989. */
  21990. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21991. var torusKnot = new BABYLON.Mesh(name, scene);
  21992. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21993. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21994. vertexData.applyToMesh(torusKnot, options.updatable);
  21995. return torusKnot;
  21996. };
  21997. /**
  21998. * Creates a line system mesh.
  21999. * A line system is a pool of many lines gathered in a single mesh.
  22000. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22001. * 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.
  22002. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22003. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22004. * 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
  22005. * 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
  22006. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22007. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22008. */
  22009. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22010. var instance = options.instance;
  22011. var lines = options.lines;
  22012. if (instance) {
  22013. var positionFunction = function (positions) {
  22014. var i = 0;
  22015. for (var l = 0; l < lines.length; l++) {
  22016. var points = lines[l];
  22017. for (var p = 0; p < points.length; p++) {
  22018. positions[i] = points[p].x;
  22019. positions[i + 1] = points[p].y;
  22020. positions[i + 2] = points[p].z;
  22021. i += 3;
  22022. }
  22023. }
  22024. };
  22025. instance.updateMeshPositions(positionFunction, false);
  22026. return instance;
  22027. }
  22028. // line system creation
  22029. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22030. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22031. vertexData.applyToMesh(lineSystem, options.updatable);
  22032. return lineSystem;
  22033. };
  22034. /**
  22035. * Creates a line mesh.
  22036. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22037. * 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.
  22038. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22039. * The parameter `points` is an array successive Vector3.
  22040. * 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
  22041. * When updating an instance, remember that only point positions can change, not the number of points.
  22042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22043. */
  22044. MeshBuilder.CreateLines = function (name, options, scene) {
  22045. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22046. return lines;
  22047. };
  22048. /**
  22049. * Creates a dashed line mesh.
  22050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22051. * 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.
  22052. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22053. * The parameter `points` is an array successive Vector3.
  22054. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22055. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22056. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22057. * 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
  22058. * When updating an instance, remember that only point positions can change, not the number of points.
  22059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22060. */
  22061. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22062. var points = options.points;
  22063. var instance = options.instance;
  22064. var gapSize = options.gapSize;
  22065. var dashNb = options.dashNb;
  22066. var dashSize = options.dashSize;
  22067. if (instance) {
  22068. var positionFunction = function (positions) {
  22069. var curvect = BABYLON.Vector3.Zero();
  22070. var nbSeg = positions.length / 6;
  22071. var lg = 0;
  22072. var nb = 0;
  22073. var shft = 0;
  22074. var dashshft = 0;
  22075. var curshft = 0;
  22076. var p = 0;
  22077. var i = 0;
  22078. var j = 0;
  22079. for (i = 0; i < points.length - 1; i++) {
  22080. points[i + 1].subtractToRef(points[i], curvect);
  22081. lg += curvect.length();
  22082. }
  22083. shft = lg / nbSeg;
  22084. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22085. for (i = 0; i < points.length - 1; i++) {
  22086. points[i + 1].subtractToRef(points[i], curvect);
  22087. nb = Math.floor(curvect.length() / shft);
  22088. curvect.normalize();
  22089. j = 0;
  22090. while (j < nb && p < positions.length) {
  22091. curshft = shft * j;
  22092. positions[p] = points[i].x + curshft * curvect.x;
  22093. positions[p + 1] = points[i].y + curshft * curvect.y;
  22094. positions[p + 2] = points[i].z + curshft * curvect.z;
  22095. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22096. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22097. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22098. p += 6;
  22099. j++;
  22100. }
  22101. }
  22102. while (p < positions.length) {
  22103. positions[p] = points[i].x;
  22104. positions[p + 1] = points[i].y;
  22105. positions[p + 2] = points[i].z;
  22106. p += 3;
  22107. }
  22108. };
  22109. instance.updateMeshPositions(positionFunction, false);
  22110. return instance;
  22111. }
  22112. // dashed lines creation
  22113. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22114. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22115. vertexData.applyToMesh(dashedLines, options.updatable);
  22116. dashedLines.dashSize = dashSize;
  22117. dashedLines.gapSize = gapSize;
  22118. return dashedLines;
  22119. };
  22120. /**
  22121. * Creates an extruded shape mesh.
  22122. * 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.
  22123. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22124. *
  22125. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22126. * 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
  22127. * extruded along the Z axis.
  22128. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22129. * 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.
  22130. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22131. * 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
  22132. * 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
  22133. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22134. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22135. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22136. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22138. */
  22139. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22140. var path = options.path;
  22141. var shape = options.shape;
  22142. var scale = options.scale || 1;
  22143. var rotation = options.rotation || 0;
  22144. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22145. var updatable = options.updatable;
  22146. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22147. var instance = options.instance;
  22148. var invertUV = options.invertUV || false;
  22149. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22150. };
  22151. /**
  22152. * Creates an custom extruded shape mesh.
  22153. * 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.
  22154. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22155. *
  22156. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22157. * 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
  22158. * extruded along the Z axis.
  22159. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22160. * 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
  22161. * and the distance of this point from the begining of the path :
  22162. * ```javascript
  22163. * var rotationFunction = function(i, distance) {
  22164. * // do things
  22165. * return rotationValue; }
  22166. * ```
  22167. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22168. * 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
  22169. * and the distance of this point from the begining of the path :
  22170. * ```javascript
  22171. * var scaleFunction = function(i, distance) {
  22172. * // do things
  22173. * return scaleValue;}
  22174. * ```
  22175. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22176. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22177. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22178. * 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
  22179. * 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
  22180. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22182. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22183. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22185. */
  22186. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22187. var path = options.path;
  22188. var shape = options.shape;
  22189. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22190. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22191. var ribbonCloseArray = options.ribbonCloseArray || false;
  22192. var ribbonClosePath = options.ribbonClosePath || false;
  22193. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22194. var updatable = options.updatable;
  22195. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22196. var instance = options.instance;
  22197. var invertUV = options.invertUV || false;
  22198. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22199. };
  22200. /**
  22201. * Creates lathe mesh.
  22202. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22203. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22204. *
  22205. * 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
  22206. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22207. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22208. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22209. * 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.
  22210. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22211. * 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
  22212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22214. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22216. */
  22217. MeshBuilder.CreateLathe = function (name, options, scene) {
  22218. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22219. var closed = (options.closed === undefined) ? true : options.closed;
  22220. var shape = options.shape;
  22221. var radius = options.radius || 1;
  22222. var tessellation = options.tessellation || 64;
  22223. var updatable = options.updatable;
  22224. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22225. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22226. var pi2 = Math.PI * 2;
  22227. var paths = new Array();
  22228. var invertUV = options.invertUV || false;
  22229. var i = 0;
  22230. var p = 0;
  22231. var step = pi2 / tessellation * arc;
  22232. var rotated;
  22233. var path = new Array();
  22234. ;
  22235. for (i = 0; i <= tessellation; i++) {
  22236. var path = [];
  22237. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22238. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22239. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22240. }
  22241. for (p = 0; p < shape.length; p++) {
  22242. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22243. path.push(rotated);
  22244. }
  22245. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22246. 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));
  22247. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22248. }
  22249. paths.push(path);
  22250. }
  22251. // lathe ribbon
  22252. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22253. return lathe;
  22254. };
  22255. /**
  22256. * Creates a plane mesh.
  22257. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22258. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22259. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22260. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22262. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22264. */
  22265. MeshBuilder.CreatePlane = function (name, options, scene) {
  22266. var plane = new BABYLON.Mesh(name, scene);
  22267. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22268. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22269. vertexData.applyToMesh(plane, options.updatable);
  22270. if (options.sourcePlane) {
  22271. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22272. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22273. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22274. plane.rotate(vectorProduct, product);
  22275. }
  22276. return plane;
  22277. };
  22278. /**
  22279. * Creates a ground mesh.
  22280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22281. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22282. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22284. */
  22285. MeshBuilder.CreateGround = function (name, options, scene) {
  22286. var ground = new BABYLON.GroundMesh(name, scene);
  22287. ground._setReady(false);
  22288. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22289. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22290. ground._width = options.width || 1;
  22291. ground._height = options.height || 1;
  22292. ground._maxX = ground._width / 2;
  22293. ground._maxZ = ground._height / 2;
  22294. ground._minX = -ground._maxX;
  22295. ground._minZ = -ground._maxZ;
  22296. var vertexData = BABYLON.VertexData.CreateGround(options);
  22297. vertexData.applyToMesh(ground, options.updatable);
  22298. ground._setReady(true);
  22299. return ground;
  22300. };
  22301. /**
  22302. * Creates a tiled ground mesh.
  22303. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22304. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22305. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22306. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22307. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22308. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22309. * numbers of subdivisions on the ground width and height of each tile.
  22310. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22311. */
  22312. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22313. var tiledGround = new BABYLON.Mesh(name, scene);
  22314. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22315. vertexData.applyToMesh(tiledGround, options.updatable);
  22316. return tiledGround;
  22317. };
  22318. /**
  22319. * Creates a ground mesh from a height map.
  22320. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22321. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22322. * The parameter `url` sets the URL of the height map image resource.
  22323. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22324. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22325. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22326. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22327. * 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).
  22328. * This function is passed the newly built mesh :
  22329. * ```javascript
  22330. * function(mesh) { // do things
  22331. * return; }
  22332. * ```
  22333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22334. */
  22335. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22336. var width = options.width || 10.0;
  22337. var height = options.height || 10.0;
  22338. var subdivisions = options.subdivisions || 1 | 0;
  22339. var minHeight = options.minHeight || 0.0;
  22340. var maxHeight = options.maxHeight || 10.0;
  22341. var updatable = options.updatable;
  22342. var onReady = options.onReady;
  22343. var ground = new BABYLON.GroundMesh(name, scene);
  22344. ground._subdivisionsX = subdivisions;
  22345. ground._subdivisionsY = subdivisions;
  22346. ground._width = width;
  22347. ground._height = height;
  22348. ground._maxX = ground._width / 2.0;
  22349. ground._maxZ = ground._height / 2.0;
  22350. ground._minX = -ground._maxX;
  22351. ground._minZ = -ground._maxZ;
  22352. ground._setReady(false);
  22353. var onload = function (img) {
  22354. // Getting height map data
  22355. var canvas = document.createElement("canvas");
  22356. var context = canvas.getContext("2d");
  22357. var bufferWidth = img.width;
  22358. var bufferHeight = img.height;
  22359. canvas.width = bufferWidth;
  22360. canvas.height = bufferHeight;
  22361. context.drawImage(img, 0, 0);
  22362. // Create VertexData from map data
  22363. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22364. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22365. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22366. width: width, height: height,
  22367. subdivisions: subdivisions,
  22368. minHeight: minHeight, maxHeight: maxHeight,
  22369. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22370. });
  22371. vertexData.applyToMesh(ground, updatable);
  22372. ground._setReady(true);
  22373. //execute ready callback, if set
  22374. if (onReady) {
  22375. onReady(ground);
  22376. }
  22377. };
  22378. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22379. return ground;
  22380. };
  22381. /**
  22382. * Creates a tube mesh.
  22383. * 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.
  22384. *
  22385. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22386. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22387. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22388. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22389. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22390. * 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.
  22391. * It must return a radius value (positive float) :
  22392. * ```javascript
  22393. * var radiusFunction = function(i, distance) {
  22394. * // do things
  22395. * return radius; }
  22396. * ```
  22397. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22398. * 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
  22399. * 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
  22400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22402. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22404. */
  22405. MeshBuilder.CreateTube = function (name, options, scene) {
  22406. var path = options.path;
  22407. var radius = options.radius || 1.0;
  22408. var tessellation = options.tessellation || 64 | 0;
  22409. var radiusFunction = options.radiusFunction;
  22410. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22411. var invertUV = options.invertUV || false;
  22412. var updatable = options.updatable;
  22413. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22414. var instance = options.instance;
  22415. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22416. // tube geometry
  22417. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22418. var tangents = path3D.getTangents();
  22419. var normals = path3D.getNormals();
  22420. var distances = path3D.getDistances();
  22421. var pi2 = Math.PI * 2;
  22422. var step = pi2 / tessellation * arc;
  22423. var returnRadius = function () { return radius; };
  22424. var radiusFunctionFinal = radiusFunction || returnRadius;
  22425. var circlePath;
  22426. var rad;
  22427. var normal;
  22428. var rotated;
  22429. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22430. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22431. for (var i = 0; i < path.length; i++) {
  22432. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22433. circlePath = Array(); // current circle array
  22434. normal = normals[i]; // current normal
  22435. for (var t = 0; t < tessellation; t++) {
  22436. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22437. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22438. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22439. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22440. circlePath[t] = rotated;
  22441. }
  22442. circlePaths[index] = circlePath;
  22443. index++;
  22444. }
  22445. // cap
  22446. var capPath = function (nbPoints, pathIndex) {
  22447. var pointCap = Array();
  22448. for (var i = 0; i < nbPoints; i++) {
  22449. pointCap.push(path[pathIndex]);
  22450. }
  22451. return pointCap;
  22452. };
  22453. switch (cap) {
  22454. case BABYLON.Mesh.NO_CAP:
  22455. break;
  22456. case BABYLON.Mesh.CAP_START:
  22457. circlePaths[0] = capPath(tessellation, 0);
  22458. circlePaths[1] = circlePaths[2].slice(0);
  22459. break;
  22460. case BABYLON.Mesh.CAP_END:
  22461. circlePaths[index] = circlePaths[index - 1].slice(0);
  22462. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22463. break;
  22464. case BABYLON.Mesh.CAP_ALL:
  22465. circlePaths[0] = capPath(tessellation, 0);
  22466. circlePaths[1] = circlePaths[2].slice(0);
  22467. circlePaths[index] = circlePaths[index - 1].slice(0);
  22468. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22469. break;
  22470. default:
  22471. break;
  22472. }
  22473. return circlePaths;
  22474. };
  22475. var path3D;
  22476. var pathArray;
  22477. if (instance) {
  22478. var arc = options.arc || instance.arc;
  22479. path3D = (instance.path3D).update(path);
  22480. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22481. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22482. instance.path3D = path3D;
  22483. instance.pathArray = pathArray;
  22484. instance.arc = arc;
  22485. return instance;
  22486. }
  22487. // tube creation
  22488. path3D = new BABYLON.Path3D(path);
  22489. var newPathArray = new Array();
  22490. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22491. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22492. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22493. tube.pathArray = pathArray;
  22494. tube.path3D = path3D;
  22495. tube.tessellation = tessellation;
  22496. tube.cap = cap;
  22497. tube.arc = options.arc;
  22498. return tube;
  22499. };
  22500. /**
  22501. * Creates a polyhedron mesh.
  22502. *
  22503. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22504. * 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
  22505. * to choose the wanted type.
  22506. * The parameter `size` (positive float, default 1) sets the polygon size.
  22507. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22508. * 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`.
  22509. * 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
  22510. * 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)`).
  22511. * 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
  22512. * 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.
  22513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22514. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22516. */
  22517. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22518. var polyhedron = new BABYLON.Mesh(name, scene);
  22519. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22520. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22521. vertexData.applyToMesh(polyhedron, options.updatable);
  22522. return polyhedron;
  22523. };
  22524. /**
  22525. * Creates a decal mesh.
  22526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22527. * 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.
  22528. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22529. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22530. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22531. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22532. */
  22533. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22534. var indices = sourceMesh.getIndices();
  22535. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22536. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22537. var position = options.position || BABYLON.Vector3.Zero();
  22538. var normal = options.normal || BABYLON.Vector3.Up();
  22539. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22540. var angle = options.angle || 0;
  22541. // Getting correct rotation
  22542. if (!normal) {
  22543. var target = new BABYLON.Vector3(0, 0, 1);
  22544. var camera = sourceMesh.getScene().activeCamera;
  22545. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22546. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22547. }
  22548. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22549. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22550. var pitch = Math.atan2(normal.y, len);
  22551. // Matrix
  22552. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22553. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22554. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22555. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22556. var vertexData = new BABYLON.VertexData();
  22557. vertexData.indices = [];
  22558. vertexData.positions = [];
  22559. vertexData.normals = [];
  22560. vertexData.uvs = [];
  22561. var currentVertexDataIndex = 0;
  22562. var extractDecalVector3 = function (indexId) {
  22563. var vertexId = indices[indexId];
  22564. var result = new BABYLON.PositionNormalVertex();
  22565. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22566. // Send vector to decal local world
  22567. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22568. // Get normal
  22569. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22570. return result;
  22571. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22572. var clip = function (vertices, axis) {
  22573. if (vertices.length === 0) {
  22574. return vertices;
  22575. }
  22576. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22577. var clipVertices = function (v0, v1) {
  22578. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22579. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22580. };
  22581. var result = new Array();
  22582. for (var index = 0; index < vertices.length; index += 3) {
  22583. var v1Out;
  22584. var v2Out;
  22585. var v3Out;
  22586. var total = 0;
  22587. var nV1, nV2, nV3, nV4;
  22588. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22589. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22590. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22591. v1Out = d1 > 0;
  22592. v2Out = d2 > 0;
  22593. v3Out = d3 > 0;
  22594. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22595. switch (total) {
  22596. case 0:
  22597. result.push(vertices[index]);
  22598. result.push(vertices[index + 1]);
  22599. result.push(vertices[index + 2]);
  22600. break;
  22601. case 1:
  22602. if (v1Out) {
  22603. nV1 = vertices[index + 1];
  22604. nV2 = vertices[index + 2];
  22605. nV3 = clipVertices(vertices[index], nV1);
  22606. nV4 = clipVertices(vertices[index], nV2);
  22607. }
  22608. if (v2Out) {
  22609. nV1 = vertices[index];
  22610. nV2 = vertices[index + 2];
  22611. nV3 = clipVertices(vertices[index + 1], nV1);
  22612. nV4 = clipVertices(vertices[index + 1], nV2);
  22613. result.push(nV3);
  22614. result.push(nV2.clone());
  22615. result.push(nV1.clone());
  22616. result.push(nV2.clone());
  22617. result.push(nV3.clone());
  22618. result.push(nV4);
  22619. break;
  22620. }
  22621. if (v3Out) {
  22622. nV1 = vertices[index];
  22623. nV2 = vertices[index + 1];
  22624. nV3 = clipVertices(vertices[index + 2], nV1);
  22625. nV4 = clipVertices(vertices[index + 2], nV2);
  22626. }
  22627. result.push(nV1.clone());
  22628. result.push(nV2.clone());
  22629. result.push(nV3);
  22630. result.push(nV4);
  22631. result.push(nV3.clone());
  22632. result.push(nV2.clone());
  22633. break;
  22634. case 2:
  22635. if (!v1Out) {
  22636. nV1 = vertices[index].clone();
  22637. nV2 = clipVertices(nV1, vertices[index + 1]);
  22638. nV3 = clipVertices(nV1, vertices[index + 2]);
  22639. result.push(nV1);
  22640. result.push(nV2);
  22641. result.push(nV3);
  22642. }
  22643. if (!v2Out) {
  22644. nV1 = vertices[index + 1].clone();
  22645. nV2 = clipVertices(nV1, vertices[index + 2]);
  22646. nV3 = clipVertices(nV1, vertices[index]);
  22647. result.push(nV1);
  22648. result.push(nV2);
  22649. result.push(nV3);
  22650. }
  22651. if (!v3Out) {
  22652. nV1 = vertices[index + 2].clone();
  22653. nV2 = clipVertices(nV1, vertices[index]);
  22654. nV3 = clipVertices(nV1, vertices[index + 1]);
  22655. result.push(nV1);
  22656. result.push(nV2);
  22657. result.push(nV3);
  22658. }
  22659. break;
  22660. case 3:
  22661. break;
  22662. }
  22663. }
  22664. return result;
  22665. };
  22666. for (var index = 0; index < indices.length; index += 3) {
  22667. var faceVertices = new Array();
  22668. faceVertices.push(extractDecalVector3(index));
  22669. faceVertices.push(extractDecalVector3(index + 1));
  22670. faceVertices.push(extractDecalVector3(index + 2));
  22671. // Clip
  22672. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22673. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22674. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22675. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22676. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22677. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22678. if (faceVertices.length === 0) {
  22679. continue;
  22680. }
  22681. // Add UVs and get back to world
  22682. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22683. var vertex = faceVertices[vIndex];
  22684. //TODO check for Int32Array
  22685. vertexData.indices.push(currentVertexDataIndex);
  22686. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22687. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22688. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22689. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22690. currentVertexDataIndex++;
  22691. }
  22692. }
  22693. // Return mesh
  22694. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22695. vertexData.applyToMesh(decal);
  22696. decal.position = position.clone();
  22697. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22698. return decal;
  22699. };
  22700. // Privates
  22701. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22702. // extrusion geometry
  22703. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22704. var tangents = path3D.getTangents();
  22705. var normals = path3D.getNormals();
  22706. var binormals = path3D.getBinormals();
  22707. var distances = path3D.getDistances();
  22708. var angle = 0;
  22709. var returnScale = function () { return scale; };
  22710. var returnRotation = function () { return rotation; };
  22711. var rotate = custom ? rotateFunction : returnRotation;
  22712. var scl = custom ? scaleFunction : returnScale;
  22713. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22714. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22715. for (var i = 0; i < curve.length; i++) {
  22716. var shapePath = new Array();
  22717. var angleStep = rotate(i, distances[i]);
  22718. var scaleRatio = scl(i, distances[i]);
  22719. for (var p = 0; p < shape.length; p++) {
  22720. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22721. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22722. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22723. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22724. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22725. shapePath[p] = rotated;
  22726. }
  22727. shapePaths[index] = shapePath;
  22728. angle += angleStep;
  22729. index++;
  22730. }
  22731. // cap
  22732. var capPath = function (shapePath) {
  22733. var pointCap = Array();
  22734. var barycenter = BABYLON.Vector3.Zero();
  22735. var i;
  22736. for (i = 0; i < shapePath.length; i++) {
  22737. barycenter.addInPlace(shapePath[i]);
  22738. }
  22739. barycenter.scaleInPlace(1 / shapePath.length);
  22740. for (i = 0; i < shapePath.length; i++) {
  22741. pointCap.push(barycenter);
  22742. }
  22743. return pointCap;
  22744. };
  22745. switch (cap) {
  22746. case BABYLON.Mesh.NO_CAP:
  22747. break;
  22748. case BABYLON.Mesh.CAP_START:
  22749. shapePaths[0] = capPath(shapePaths[2]);
  22750. shapePaths[1] = shapePaths[2].slice(0);
  22751. break;
  22752. case BABYLON.Mesh.CAP_END:
  22753. shapePaths[index] = shapePaths[index - 1];
  22754. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22755. break;
  22756. case BABYLON.Mesh.CAP_ALL:
  22757. shapePaths[0] = capPath(shapePaths[2]);
  22758. shapePaths[1] = shapePaths[2].slice(0);
  22759. shapePaths[index] = shapePaths[index - 1];
  22760. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22761. break;
  22762. default:
  22763. break;
  22764. }
  22765. return shapePaths;
  22766. };
  22767. var path3D;
  22768. var pathArray;
  22769. if (instance) {
  22770. path3D = (instance.path3D).update(curve);
  22771. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22772. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  22773. return instance;
  22774. }
  22775. // extruded shape creation
  22776. path3D = new BABYLON.Path3D(curve);
  22777. var newShapePaths = new Array();
  22778. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22779. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22780. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22781. extrudedGeneric.pathArray = pathArray;
  22782. extrudedGeneric.path3D = path3D;
  22783. extrudedGeneric.cap = cap;
  22784. return extrudedGeneric;
  22785. };
  22786. return MeshBuilder;
  22787. }());
  22788. BABYLON.MeshBuilder = MeshBuilder;
  22789. })(BABYLON || (BABYLON = {}));
  22790. var BABYLON;
  22791. (function (BABYLON) {
  22792. var BaseTexture = (function () {
  22793. function BaseTexture(scene) {
  22794. this.hasAlpha = false;
  22795. this.getAlphaFromRGB = false;
  22796. this.level = 1;
  22797. this.coordinatesIndex = 0;
  22798. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22799. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22800. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22801. this.anisotropicFilteringLevel = 4;
  22802. this.isCube = false;
  22803. this.isRenderTarget = false;
  22804. this.animations = new Array();
  22805. /**
  22806. * An event triggered when the texture is disposed.
  22807. * @type {BABYLON.Observable}
  22808. */
  22809. this.onDisposeObservable = new BABYLON.Observable();
  22810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22811. this._scene = scene;
  22812. this._scene.textures.push(this);
  22813. this._uid = null;
  22814. }
  22815. Object.defineProperty(BaseTexture.prototype, "uid", {
  22816. get: function () {
  22817. if (!this._uid) {
  22818. this._uid = BABYLON.Tools.RandomId();
  22819. }
  22820. return this._uid;
  22821. },
  22822. enumerable: true,
  22823. configurable: true
  22824. });
  22825. BaseTexture.prototype.toString = function () {
  22826. return this.name;
  22827. };
  22828. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22829. set: function (callback) {
  22830. if (this._onDisposeObserver) {
  22831. this.onDisposeObservable.remove(this._onDisposeObserver);
  22832. }
  22833. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22834. },
  22835. enumerable: true,
  22836. configurable: true
  22837. });
  22838. BaseTexture.prototype.getScene = function () {
  22839. return this._scene;
  22840. };
  22841. BaseTexture.prototype.getTextureMatrix = function () {
  22842. return null;
  22843. };
  22844. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22845. return null;
  22846. };
  22847. BaseTexture.prototype.getInternalTexture = function () {
  22848. return this._texture;
  22849. };
  22850. BaseTexture.prototype.isReady = function () {
  22851. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22852. return true;
  22853. }
  22854. if (this._texture) {
  22855. return this._texture.isReady;
  22856. }
  22857. return false;
  22858. };
  22859. BaseTexture.prototype.getSize = function () {
  22860. if (this._texture._width) {
  22861. return new BABYLON.Size(this._texture._width, this._texture._height);
  22862. }
  22863. if (this._texture._size) {
  22864. return new BABYLON.Size(this._texture._size, this._texture._size);
  22865. }
  22866. return BABYLON.Size.Zero();
  22867. };
  22868. BaseTexture.prototype.getBaseSize = function () {
  22869. if (!this.isReady() || !this._texture)
  22870. return BABYLON.Size.Zero();
  22871. if (this._texture._size) {
  22872. return new BABYLON.Size(this._texture._size, this._texture._size);
  22873. }
  22874. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22875. };
  22876. BaseTexture.prototype.scale = function (ratio) {
  22877. };
  22878. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22879. get: function () {
  22880. return false;
  22881. },
  22882. enumerable: true,
  22883. configurable: true
  22884. });
  22885. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22886. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22887. for (var index = 0; index < texturesCache.length; index++) {
  22888. var texturesCacheEntry = texturesCache[index];
  22889. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22890. texturesCache.splice(index, 1);
  22891. return;
  22892. }
  22893. }
  22894. };
  22895. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22896. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22897. for (var index = 0; index < texturesCache.length; index++) {
  22898. var texturesCacheEntry = texturesCache[index];
  22899. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22900. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22901. texturesCacheEntry.references++;
  22902. return texturesCacheEntry;
  22903. }
  22904. }
  22905. }
  22906. return null;
  22907. };
  22908. BaseTexture.prototype.delayLoad = function () {
  22909. };
  22910. BaseTexture.prototype.clone = function () {
  22911. return null;
  22912. };
  22913. BaseTexture.prototype.releaseInternalTexture = function () {
  22914. if (this._texture) {
  22915. this._scene.getEngine().releaseInternalTexture(this._texture);
  22916. delete this._texture;
  22917. }
  22918. };
  22919. BaseTexture.prototype.dispose = function () {
  22920. // Animations
  22921. this.getScene().stopAnimation(this);
  22922. // Remove from scene
  22923. var index = this._scene.textures.indexOf(this);
  22924. if (index >= 0) {
  22925. this._scene.textures.splice(index, 1);
  22926. }
  22927. if (this._texture === undefined) {
  22928. return;
  22929. }
  22930. // Release
  22931. this.releaseInternalTexture();
  22932. // Callback
  22933. this.onDisposeObservable.notifyObservers(this);
  22934. this.onDisposeObservable.clear();
  22935. };
  22936. BaseTexture.prototype.serialize = function () {
  22937. if (!this.name) {
  22938. return null;
  22939. }
  22940. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22941. // Animations
  22942. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22943. return serializationObject;
  22944. };
  22945. __decorate([
  22946. BABYLON.serialize()
  22947. ], BaseTexture.prototype, "name", void 0);
  22948. __decorate([
  22949. BABYLON.serialize()
  22950. ], BaseTexture.prototype, "hasAlpha", void 0);
  22951. __decorate([
  22952. BABYLON.serialize()
  22953. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22954. __decorate([
  22955. BABYLON.serialize()
  22956. ], BaseTexture.prototype, "level", void 0);
  22957. __decorate([
  22958. BABYLON.serialize()
  22959. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22960. __decorate([
  22961. BABYLON.serialize()
  22962. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22963. __decorate([
  22964. BABYLON.serialize()
  22965. ], BaseTexture.prototype, "wrapU", void 0);
  22966. __decorate([
  22967. BABYLON.serialize()
  22968. ], BaseTexture.prototype, "wrapV", void 0);
  22969. __decorate([
  22970. BABYLON.serialize()
  22971. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22972. __decorate([
  22973. BABYLON.serialize()
  22974. ], BaseTexture.prototype, "isCube", void 0);
  22975. __decorate([
  22976. BABYLON.serialize()
  22977. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22978. return BaseTexture;
  22979. }());
  22980. BABYLON.BaseTexture = BaseTexture;
  22981. })(BABYLON || (BABYLON = {}));
  22982. var BABYLON;
  22983. (function (BABYLON) {
  22984. var Texture = (function (_super) {
  22985. __extends(Texture, _super);
  22986. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22987. var _this = this;
  22988. if (noMipmap === void 0) { noMipmap = false; }
  22989. if (invertY === void 0) { invertY = true; }
  22990. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22991. if (onLoad === void 0) { onLoad = null; }
  22992. if (onError === void 0) { onError = null; }
  22993. if (buffer === void 0) { buffer = null; }
  22994. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22995. _super.call(this, scene);
  22996. this.uOffset = 0;
  22997. this.vOffset = 0;
  22998. this.uScale = 1.0;
  22999. this.vScale = 1.0;
  23000. this.uAng = 0;
  23001. this.vAng = 0;
  23002. this.wAng = 0;
  23003. this.name = url;
  23004. this.url = url;
  23005. this._noMipmap = noMipmap;
  23006. this._invertY = invertY;
  23007. this._samplingMode = samplingMode;
  23008. this._buffer = buffer;
  23009. this._deleteBuffer = deleteBuffer;
  23010. if (!url) {
  23011. return;
  23012. }
  23013. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23014. var load = function () {
  23015. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23016. _this.onLoadObservable.notifyObservers(true);
  23017. }
  23018. if (onLoad) {
  23019. onLoad();
  23020. }
  23021. };
  23022. if (!this._texture) {
  23023. if (!scene.useDelayedTextureLoading) {
  23024. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23025. if (deleteBuffer) {
  23026. delete this._buffer;
  23027. }
  23028. }
  23029. else {
  23030. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23031. this._delayedOnLoad = load;
  23032. this._delayedOnError = onError;
  23033. }
  23034. }
  23035. else {
  23036. if (this._texture.isReady) {
  23037. BABYLON.Tools.SetImmediate(function () { return load(); });
  23038. }
  23039. else {
  23040. this._texture.onLoadedCallbacks.push(load);
  23041. }
  23042. }
  23043. }
  23044. Object.defineProperty(Texture.prototype, "noMipmap", {
  23045. get: function () {
  23046. return this._noMipmap;
  23047. },
  23048. enumerable: true,
  23049. configurable: true
  23050. });
  23051. Texture.prototype.delayLoad = function () {
  23052. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23053. return;
  23054. }
  23055. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23056. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23057. if (!this._texture) {
  23058. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23059. if (this._deleteBuffer) {
  23060. delete this._buffer;
  23061. }
  23062. }
  23063. };
  23064. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23065. if (!this._texture) {
  23066. return;
  23067. }
  23068. this._samplingMode = samplingMode;
  23069. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23070. };
  23071. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23072. x *= this.uScale;
  23073. y *= this.vScale;
  23074. x -= 0.5 * this.uScale;
  23075. y -= 0.5 * this.vScale;
  23076. z -= 0.5;
  23077. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23078. t.x += 0.5 * this.uScale + this.uOffset;
  23079. t.y += 0.5 * this.vScale + this.vOffset;
  23080. t.z += 0.5;
  23081. };
  23082. Texture.prototype.getTextureMatrix = function () {
  23083. if (this.uOffset === this._cachedUOffset &&
  23084. this.vOffset === this._cachedVOffset &&
  23085. this.uScale === this._cachedUScale &&
  23086. this.vScale === this._cachedVScale &&
  23087. this.uAng === this._cachedUAng &&
  23088. this.vAng === this._cachedVAng &&
  23089. this.wAng === this._cachedWAng) {
  23090. return this._cachedTextureMatrix;
  23091. }
  23092. this._cachedUOffset = this.uOffset;
  23093. this._cachedVOffset = this.vOffset;
  23094. this._cachedUScale = this.uScale;
  23095. this._cachedVScale = this.vScale;
  23096. this._cachedUAng = this.uAng;
  23097. this._cachedVAng = this.vAng;
  23098. this._cachedWAng = this.wAng;
  23099. if (!this._cachedTextureMatrix) {
  23100. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23101. this._rowGenerationMatrix = new BABYLON.Matrix();
  23102. this._t0 = BABYLON.Vector3.Zero();
  23103. this._t1 = BABYLON.Vector3.Zero();
  23104. this._t2 = BABYLON.Vector3.Zero();
  23105. }
  23106. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23107. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23108. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23109. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23110. this._t1.subtractInPlace(this._t0);
  23111. this._t2.subtractInPlace(this._t0);
  23112. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23113. this._cachedTextureMatrix.m[0] = this._t1.x;
  23114. this._cachedTextureMatrix.m[1] = this._t1.y;
  23115. this._cachedTextureMatrix.m[2] = this._t1.z;
  23116. this._cachedTextureMatrix.m[4] = this._t2.x;
  23117. this._cachedTextureMatrix.m[5] = this._t2.y;
  23118. this._cachedTextureMatrix.m[6] = this._t2.z;
  23119. this._cachedTextureMatrix.m[8] = this._t0.x;
  23120. this._cachedTextureMatrix.m[9] = this._t0.y;
  23121. this._cachedTextureMatrix.m[10] = this._t0.z;
  23122. return this._cachedTextureMatrix;
  23123. };
  23124. Texture.prototype.getReflectionTextureMatrix = function () {
  23125. if (this.uOffset === this._cachedUOffset &&
  23126. this.vOffset === this._cachedVOffset &&
  23127. this.uScale === this._cachedUScale &&
  23128. this.vScale === this._cachedVScale &&
  23129. this.coordinatesMode === this._cachedCoordinatesMode) {
  23130. return this._cachedTextureMatrix;
  23131. }
  23132. if (!this._cachedTextureMatrix) {
  23133. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23134. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23135. }
  23136. this._cachedCoordinatesMode = this.coordinatesMode;
  23137. switch (this.coordinatesMode) {
  23138. case Texture.PLANAR_MODE:
  23139. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23140. this._cachedTextureMatrix[0] = this.uScale;
  23141. this._cachedTextureMatrix[5] = this.vScale;
  23142. this._cachedTextureMatrix[12] = this.uOffset;
  23143. this._cachedTextureMatrix[13] = this.vOffset;
  23144. break;
  23145. case Texture.PROJECTION_MODE:
  23146. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23147. this._projectionModeMatrix.m[0] = 0.5;
  23148. this._projectionModeMatrix.m[5] = -0.5;
  23149. this._projectionModeMatrix.m[10] = 0.0;
  23150. this._projectionModeMatrix.m[12] = 0.5;
  23151. this._projectionModeMatrix.m[13] = 0.5;
  23152. this._projectionModeMatrix.m[14] = 1.0;
  23153. this._projectionModeMatrix.m[15] = 1.0;
  23154. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23155. break;
  23156. default:
  23157. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23158. break;
  23159. }
  23160. return this._cachedTextureMatrix;
  23161. };
  23162. Texture.prototype.clone = function () {
  23163. var _this = this;
  23164. return BABYLON.SerializationHelper.Clone(function () {
  23165. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23166. }, this);
  23167. };
  23168. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23169. get: function () {
  23170. if (!this._onLoadObservarble) {
  23171. this._onLoadObservarble = new BABYLON.Observable();
  23172. }
  23173. return this._onLoadObservarble;
  23174. },
  23175. enumerable: true,
  23176. configurable: true
  23177. });
  23178. // Statics
  23179. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23180. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23181. if (onLoad === void 0) { onLoad = null; }
  23182. if (onError === void 0) { onError = null; }
  23183. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23184. };
  23185. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23186. if (parsedTexture.customType) {
  23187. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23188. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23189. }
  23190. if (parsedTexture.isCube) {
  23191. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23192. }
  23193. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23194. return null;
  23195. }
  23196. var texture = BABYLON.SerializationHelper.Parse(function () {
  23197. if (parsedTexture.mirrorPlane) {
  23198. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23199. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23200. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23201. return mirrorTexture;
  23202. }
  23203. else if (parsedTexture.isRenderTarget) {
  23204. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23205. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23206. return renderTargetTexture;
  23207. }
  23208. else {
  23209. var texture;
  23210. if (parsedTexture.base64String) {
  23211. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23212. }
  23213. else {
  23214. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23215. }
  23216. return texture;
  23217. }
  23218. }, parsedTexture, scene);
  23219. // Animations
  23220. if (parsedTexture.animations) {
  23221. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23222. var parsedAnimation = parsedTexture.animations[animationIndex];
  23223. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23224. }
  23225. }
  23226. return texture;
  23227. };
  23228. // Constants
  23229. Texture.NEAREST_SAMPLINGMODE = 1;
  23230. Texture.BILINEAR_SAMPLINGMODE = 2;
  23231. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23232. Texture.EXPLICIT_MODE = 0;
  23233. Texture.SPHERICAL_MODE = 1;
  23234. Texture.PLANAR_MODE = 2;
  23235. Texture.CUBIC_MODE = 3;
  23236. Texture.PROJECTION_MODE = 4;
  23237. Texture.SKYBOX_MODE = 5;
  23238. Texture.INVCUBIC_MODE = 6;
  23239. Texture.EQUIRECTANGULAR_MODE = 7;
  23240. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23241. Texture.CLAMP_ADDRESSMODE = 0;
  23242. Texture.WRAP_ADDRESSMODE = 1;
  23243. Texture.MIRROR_ADDRESSMODE = 2;
  23244. __decorate([
  23245. BABYLON.serialize()
  23246. ], Texture.prototype, "url", void 0);
  23247. __decorate([
  23248. BABYLON.serialize()
  23249. ], Texture.prototype, "uOffset", void 0);
  23250. __decorate([
  23251. BABYLON.serialize()
  23252. ], Texture.prototype, "vOffset", void 0);
  23253. __decorate([
  23254. BABYLON.serialize()
  23255. ], Texture.prototype, "uScale", void 0);
  23256. __decorate([
  23257. BABYLON.serialize()
  23258. ], Texture.prototype, "vScale", void 0);
  23259. __decorate([
  23260. BABYLON.serialize()
  23261. ], Texture.prototype, "uAng", void 0);
  23262. __decorate([
  23263. BABYLON.serialize()
  23264. ], Texture.prototype, "vAng", void 0);
  23265. __decorate([
  23266. BABYLON.serialize()
  23267. ], Texture.prototype, "wAng", void 0);
  23268. return Texture;
  23269. }(BABYLON.BaseTexture));
  23270. BABYLON.Texture = Texture;
  23271. })(BABYLON || (BABYLON = {}));
  23272. var BABYLON;
  23273. (function (BABYLON) {
  23274. var CubeTexture = (function (_super) {
  23275. __extends(CubeTexture, _super);
  23276. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23277. if (onLoad === void 0) { onLoad = null; }
  23278. if (onError === void 0) { onError = null; }
  23279. _super.call(this, scene);
  23280. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23281. this.name = rootUrl;
  23282. this.url = rootUrl;
  23283. this._noMipmap = noMipmap;
  23284. this.hasAlpha = false;
  23285. if (!rootUrl && !files) {
  23286. return;
  23287. }
  23288. this._texture = this._getFromCache(rootUrl, noMipmap);
  23289. if (!files) {
  23290. if (!extensions) {
  23291. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23292. }
  23293. files = [];
  23294. for (var index = 0; index < extensions.length; index++) {
  23295. files.push(rootUrl + extensions[index]);
  23296. }
  23297. this._extensions = extensions;
  23298. }
  23299. this._files = files;
  23300. if (!this._texture) {
  23301. if (!scene.useDelayedTextureLoading) {
  23302. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23303. }
  23304. else {
  23305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23306. }
  23307. }
  23308. else {
  23309. if (this._texture.isReady) {
  23310. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23311. }
  23312. else if (onLoad) {
  23313. this._texture.onLoadedCallbacks.push(onLoad);
  23314. }
  23315. }
  23316. this.isCube = true;
  23317. this._textureMatrix = BABYLON.Matrix.Identity();
  23318. }
  23319. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23320. return new CubeTexture("", scene, null, noMipmap, files);
  23321. };
  23322. // Methods
  23323. CubeTexture.prototype.delayLoad = function () {
  23324. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23325. return;
  23326. }
  23327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23328. this._texture = this._getFromCache(this.url, this._noMipmap);
  23329. if (!this._texture) {
  23330. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23331. }
  23332. };
  23333. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23334. return this._textureMatrix;
  23335. };
  23336. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23337. var texture = BABYLON.SerializationHelper.Parse(function () {
  23338. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23339. }, parsedTexture, scene);
  23340. // Animations
  23341. if (parsedTexture.animations) {
  23342. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23343. var parsedAnimation = parsedTexture.animations[animationIndex];
  23344. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23345. }
  23346. }
  23347. return texture;
  23348. };
  23349. CubeTexture.prototype.clone = function () {
  23350. var _this = this;
  23351. return BABYLON.SerializationHelper.Clone(function () {
  23352. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23353. }, this);
  23354. };
  23355. return CubeTexture;
  23356. }(BABYLON.BaseTexture));
  23357. BABYLON.CubeTexture = CubeTexture;
  23358. })(BABYLON || (BABYLON = {}));
  23359. var BABYLON;
  23360. (function (BABYLON) {
  23361. var RenderTargetTexture = (function (_super) {
  23362. __extends(RenderTargetTexture, _super);
  23363. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23364. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23365. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23366. if (isCube === void 0) { isCube = false; }
  23367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23368. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23369. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23370. _super.call(this, null, scene, !generateMipMaps);
  23371. this.isCube = isCube;
  23372. /**
  23373. * Use this list to define the list of mesh you want to render.
  23374. */
  23375. this.renderList = new Array();
  23376. this.renderParticles = true;
  23377. this.renderSprites = false;
  23378. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23379. // Events
  23380. /**
  23381. * An event triggered when the texture is unbind.
  23382. * @type {BABYLON.Observable}
  23383. */
  23384. this.onAfterUnbindObservable = new BABYLON.Observable();
  23385. /**
  23386. * An event triggered before rendering the texture
  23387. * @type {BABYLON.Observable}
  23388. */
  23389. this.onBeforeRenderObservable = new BABYLON.Observable();
  23390. /**
  23391. * An event triggered after rendering the texture
  23392. * @type {BABYLON.Observable}
  23393. */
  23394. this.onAfterRenderObservable = new BABYLON.Observable();
  23395. /**
  23396. * An event triggered after the texture clear
  23397. * @type {BABYLON.Observable}
  23398. */
  23399. this.onClearObservable = new BABYLON.Observable();
  23400. this._currentRefreshId = -1;
  23401. this._refreshRate = 1;
  23402. this.name = name;
  23403. this.isRenderTarget = true;
  23404. this._size = size;
  23405. this._generateMipMaps = generateMipMaps;
  23406. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23407. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23408. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23409. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23410. }
  23411. if (isCube) {
  23412. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23413. generateMipMaps: generateMipMaps,
  23414. samplingMode: samplingMode,
  23415. generateDepthBuffer: generateDepthBuffer,
  23416. generateStencilBuffer: generateStencilBuffer
  23417. });
  23418. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23419. this._textureMatrix = BABYLON.Matrix.Identity();
  23420. }
  23421. else {
  23422. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23423. generateMipMaps: generateMipMaps,
  23424. type: type,
  23425. samplingMode: samplingMode,
  23426. generateDepthBuffer: generateDepthBuffer,
  23427. generateStencilBuffer: generateStencilBuffer
  23428. });
  23429. }
  23430. // Rendering groups
  23431. this._renderingManager = new BABYLON.RenderingManager(scene);
  23432. }
  23433. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23434. get: function () {
  23435. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23436. },
  23437. enumerable: true,
  23438. configurable: true
  23439. });
  23440. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23441. get: function () {
  23442. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23443. },
  23444. enumerable: true,
  23445. configurable: true
  23446. });
  23447. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23448. get: function () {
  23449. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23450. },
  23451. enumerable: true,
  23452. configurable: true
  23453. });
  23454. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23455. set: function (callback) {
  23456. if (this._onAfterUnbindObserver) {
  23457. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23458. }
  23459. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23465. set: function (callback) {
  23466. if (this._onBeforeRenderObserver) {
  23467. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23468. }
  23469. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23470. },
  23471. enumerable: true,
  23472. configurable: true
  23473. });
  23474. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23475. set: function (callback) {
  23476. if (this._onAfterRenderObserver) {
  23477. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23478. }
  23479. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23485. set: function (callback) {
  23486. if (this._onClearObserver) {
  23487. this.onClearObservable.remove(this._onClearObserver);
  23488. }
  23489. this._onClearObserver = this.onClearObservable.add(callback);
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23495. this._currentRefreshId = -1;
  23496. };
  23497. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23498. get: function () {
  23499. return this._refreshRate;
  23500. },
  23501. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23502. set: function (value) {
  23503. this._refreshRate = value;
  23504. this.resetRefreshCounter();
  23505. },
  23506. enumerable: true,
  23507. configurable: true
  23508. });
  23509. RenderTargetTexture.prototype._shouldRender = function () {
  23510. if (this._currentRefreshId === -1) {
  23511. this._currentRefreshId = 1;
  23512. return true;
  23513. }
  23514. if (this.refreshRate === this._currentRefreshId) {
  23515. this._currentRefreshId = 1;
  23516. return true;
  23517. }
  23518. this._currentRefreshId++;
  23519. return false;
  23520. };
  23521. RenderTargetTexture.prototype.isReady = function () {
  23522. if (!this.getScene().renderTargetsEnabled) {
  23523. return false;
  23524. }
  23525. return _super.prototype.isReady.call(this);
  23526. };
  23527. RenderTargetTexture.prototype.getRenderSize = function () {
  23528. return this._size;
  23529. };
  23530. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23531. get: function () {
  23532. return true;
  23533. },
  23534. enumerable: true,
  23535. configurable: true
  23536. });
  23537. RenderTargetTexture.prototype.scale = function (ratio) {
  23538. var newSize = this._size * ratio;
  23539. this.resize(newSize, this._generateMipMaps);
  23540. };
  23541. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23542. if (this.isCube) {
  23543. return this._textureMatrix;
  23544. }
  23545. return _super.prototype.getReflectionTextureMatrix.call(this);
  23546. };
  23547. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23548. this.releaseInternalTexture();
  23549. if (this.isCube) {
  23550. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23551. }
  23552. else {
  23553. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23554. }
  23555. };
  23556. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23557. var scene = this.getScene();
  23558. if (this.useCameraPostProcesses !== undefined) {
  23559. useCameraPostProcess = this.useCameraPostProcesses;
  23560. }
  23561. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23562. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23563. }
  23564. if (this._waitingRenderList) {
  23565. this.renderList = [];
  23566. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23567. var id = this._waitingRenderList[index];
  23568. this.renderList.push(scene.getMeshByID(id));
  23569. }
  23570. delete this._waitingRenderList;
  23571. }
  23572. // Is predicate defined?
  23573. if (this.renderListPredicate) {
  23574. this.renderList.splice(0); // Clear previous renderList
  23575. var sceneMeshes = this.getScene().meshes;
  23576. for (var index = 0; index < sceneMeshes.length; index++) {
  23577. var mesh = sceneMeshes[index];
  23578. if (this.renderListPredicate(mesh)) {
  23579. this.renderList.push(mesh);
  23580. }
  23581. }
  23582. }
  23583. if (this.renderList && this.renderList.length === 0) {
  23584. return;
  23585. }
  23586. // Prepare renderingManager
  23587. this._renderingManager.reset();
  23588. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23589. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23590. var sceneRenderId = scene.getRenderId();
  23591. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23592. var mesh = currentRenderList[meshIndex];
  23593. if (mesh) {
  23594. if (!mesh.isReady()) {
  23595. // Reset _currentRefreshId
  23596. this.resetRefreshCounter();
  23597. continue;
  23598. }
  23599. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23600. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23601. mesh._activate(sceneRenderId);
  23602. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23603. var subMesh = mesh.subMeshes[subIndex];
  23604. scene._activeIndices.addCount(subMesh.indexCount, false);
  23605. this._renderingManager.dispatch(subMesh);
  23606. }
  23607. }
  23608. }
  23609. }
  23610. if (this.isCube) {
  23611. for (var face = 0; face < 6; face++) {
  23612. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23613. scene.incrementRenderId();
  23614. scene.resetCachedMaterial();
  23615. }
  23616. }
  23617. else {
  23618. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23619. }
  23620. this.onAfterUnbindObservable.notifyObservers(this);
  23621. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23622. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23623. }
  23624. scene.resetCachedMaterial();
  23625. };
  23626. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23627. var scene = this.getScene();
  23628. var engine = scene.getEngine();
  23629. // Bind
  23630. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23631. if (this.isCube) {
  23632. engine.bindFramebuffer(this._texture, faceIndex);
  23633. }
  23634. else {
  23635. engine.bindFramebuffer(this._texture);
  23636. }
  23637. }
  23638. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23639. // Clear
  23640. if (this.onClearObservable.hasObservers()) {
  23641. this.onClearObservable.notifyObservers(engine);
  23642. }
  23643. else {
  23644. engine.clear(scene.clearColor, true, true, true);
  23645. }
  23646. if (!this._doNotChangeAspectRatio) {
  23647. scene.updateTransformMatrix(true);
  23648. }
  23649. // Render
  23650. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23651. if (useCameraPostProcess) {
  23652. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23653. }
  23654. if (!this._doNotChangeAspectRatio) {
  23655. scene.updateTransformMatrix(true);
  23656. }
  23657. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23658. // Dump ?
  23659. if (dumpForDebug) {
  23660. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23661. }
  23662. // Unbind
  23663. if (!this.isCube || faceIndex === 5) {
  23664. if (this.isCube) {
  23665. if (faceIndex === 5) {
  23666. engine.generateMipMapsForCubemap(this._texture);
  23667. }
  23668. }
  23669. engine.unBindFramebuffer(this._texture, this.isCube);
  23670. }
  23671. };
  23672. /**
  23673. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23674. * This allowed control for front to back rendering or reversly depending of the special needs.
  23675. *
  23676. * @param renderingGroupId The rendering group id corresponding to its index
  23677. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23678. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23679. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23680. */
  23681. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23682. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23683. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23684. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23685. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23686. };
  23687. /**
  23688. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23689. *
  23690. * @param renderingGroupId The rendering group id corresponding to its index
  23691. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23692. */
  23693. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23694. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23695. };
  23696. RenderTargetTexture.prototype.clone = function () {
  23697. var textureSize = this.getSize();
  23698. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23699. // Base texture
  23700. newTexture.hasAlpha = this.hasAlpha;
  23701. newTexture.level = this.level;
  23702. // RenderTarget Texture
  23703. newTexture.coordinatesMode = this.coordinatesMode;
  23704. newTexture.renderList = this.renderList.slice(0);
  23705. return newTexture;
  23706. };
  23707. RenderTargetTexture.prototype.serialize = function () {
  23708. if (!this.name) {
  23709. return null;
  23710. }
  23711. var serializationObject = _super.prototype.serialize.call(this);
  23712. serializationObject.renderTargetSize = this.getRenderSize();
  23713. serializationObject.renderList = [];
  23714. for (var index = 0; index < this.renderList.length; index++) {
  23715. serializationObject.renderList.push(this.renderList[index].id);
  23716. }
  23717. return serializationObject;
  23718. };
  23719. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23720. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23721. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23722. return RenderTargetTexture;
  23723. }(BABYLON.Texture));
  23724. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23725. })(BABYLON || (BABYLON = {}));
  23726. var BABYLON;
  23727. (function (BABYLON) {
  23728. var ProceduralTexture = (function (_super) {
  23729. __extends(ProceduralTexture, _super);
  23730. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23731. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23732. if (isCube === void 0) { isCube = false; }
  23733. _super.call(this, null, scene, !generateMipMaps);
  23734. this.isCube = isCube;
  23735. this.isEnabled = true;
  23736. this._currentRefreshId = -1;
  23737. this._refreshRate = 1;
  23738. this._vertexBuffers = {};
  23739. this._uniforms = new Array();
  23740. this._samplers = new Array();
  23741. this._textures = new Array();
  23742. this._floats = new Array();
  23743. this._floatsArrays = {};
  23744. this._colors3 = new Array();
  23745. this._colors4 = new Array();
  23746. this._vectors2 = new Array();
  23747. this._vectors3 = new Array();
  23748. this._matrices = new Array();
  23749. this._fallbackTextureUsed = false;
  23750. scene._proceduralTextures.push(this);
  23751. this.name = name;
  23752. this.isRenderTarget = true;
  23753. this._size = size;
  23754. this._generateMipMaps = generateMipMaps;
  23755. this.setFragment(fragment);
  23756. this._fallbackTexture = fallbackTexture;
  23757. var engine = scene.getEngine();
  23758. if (isCube) {
  23759. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23760. this.setFloat("face", 0);
  23761. }
  23762. else {
  23763. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23764. }
  23765. // VBO
  23766. var vertices = [];
  23767. vertices.push(1, 1);
  23768. vertices.push(-1, 1);
  23769. vertices.push(-1, -1);
  23770. vertices.push(1, -1);
  23771. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23772. // Indices
  23773. var indices = [];
  23774. indices.push(0);
  23775. indices.push(1);
  23776. indices.push(2);
  23777. indices.push(0);
  23778. indices.push(2);
  23779. indices.push(3);
  23780. this._indexBuffer = engine.createIndexBuffer(indices);
  23781. }
  23782. ProceduralTexture.prototype.reset = function () {
  23783. if (this._effect === undefined) {
  23784. return;
  23785. }
  23786. var engine = this.getScene().getEngine();
  23787. engine._releaseEffect(this._effect);
  23788. };
  23789. ProceduralTexture.prototype.isReady = function () {
  23790. var _this = this;
  23791. var engine = this.getScene().getEngine();
  23792. var shaders;
  23793. if (!this._fragment) {
  23794. return false;
  23795. }
  23796. if (this._fallbackTextureUsed) {
  23797. return true;
  23798. }
  23799. if (this._fragment.fragmentElement !== undefined) {
  23800. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23801. }
  23802. else {
  23803. shaders = { vertex: "procedural", fragment: this._fragment };
  23804. }
  23805. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23806. _this.releaseInternalTexture();
  23807. if (_this._fallbackTexture) {
  23808. _this._texture = _this._fallbackTexture._texture;
  23809. _this._texture.references++;
  23810. }
  23811. _this._fallbackTextureUsed = true;
  23812. });
  23813. return this._effect.isReady();
  23814. };
  23815. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23816. this._currentRefreshId = -1;
  23817. };
  23818. ProceduralTexture.prototype.setFragment = function (fragment) {
  23819. this._fragment = fragment;
  23820. };
  23821. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23822. get: function () {
  23823. return this._refreshRate;
  23824. },
  23825. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23826. set: function (value) {
  23827. this._refreshRate = value;
  23828. this.resetRefreshCounter();
  23829. },
  23830. enumerable: true,
  23831. configurable: true
  23832. });
  23833. ProceduralTexture.prototype._shouldRender = function () {
  23834. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23835. return false;
  23836. }
  23837. if (this._fallbackTextureUsed) {
  23838. return false;
  23839. }
  23840. if (this._currentRefreshId === -1) {
  23841. this._currentRefreshId = 1;
  23842. return true;
  23843. }
  23844. if (this.refreshRate === this._currentRefreshId) {
  23845. this._currentRefreshId = 1;
  23846. return true;
  23847. }
  23848. this._currentRefreshId++;
  23849. return false;
  23850. };
  23851. ProceduralTexture.prototype.getRenderSize = function () {
  23852. return this._size;
  23853. };
  23854. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23855. if (this._fallbackTextureUsed) {
  23856. return;
  23857. }
  23858. this.releaseInternalTexture();
  23859. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23860. };
  23861. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23862. if (this._uniforms.indexOf(uniformName) === -1) {
  23863. this._uniforms.push(uniformName);
  23864. }
  23865. };
  23866. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23867. if (this._samplers.indexOf(name) === -1) {
  23868. this._samplers.push(name);
  23869. }
  23870. this._textures[name] = texture;
  23871. return this;
  23872. };
  23873. ProceduralTexture.prototype.setFloat = function (name, value) {
  23874. this._checkUniform(name);
  23875. this._floats[name] = value;
  23876. return this;
  23877. };
  23878. ProceduralTexture.prototype.setFloats = function (name, value) {
  23879. this._checkUniform(name);
  23880. this._floatsArrays[name] = value;
  23881. return this;
  23882. };
  23883. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23884. this._checkUniform(name);
  23885. this._colors3[name] = value;
  23886. return this;
  23887. };
  23888. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23889. this._checkUniform(name);
  23890. this._colors4[name] = value;
  23891. return this;
  23892. };
  23893. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23894. this._checkUniform(name);
  23895. this._vectors2[name] = value;
  23896. return this;
  23897. };
  23898. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23899. this._checkUniform(name);
  23900. this._vectors3[name] = value;
  23901. return this;
  23902. };
  23903. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23904. this._checkUniform(name);
  23905. this._matrices[name] = value;
  23906. return this;
  23907. };
  23908. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23909. var scene = this.getScene();
  23910. var engine = scene.getEngine();
  23911. // Render
  23912. engine.enableEffect(this._effect);
  23913. engine.setState(false);
  23914. // Texture
  23915. for (var name in this._textures) {
  23916. this._effect.setTexture(name, this._textures[name]);
  23917. }
  23918. // Float
  23919. for (name in this._floats) {
  23920. this._effect.setFloat(name, this._floats[name]);
  23921. }
  23922. // Floats
  23923. for (name in this._floatsArrays) {
  23924. this._effect.setArray(name, this._floatsArrays[name]);
  23925. }
  23926. // Color3
  23927. for (name in this._colors3) {
  23928. this._effect.setColor3(name, this._colors3[name]);
  23929. }
  23930. // Color4
  23931. for (name in this._colors4) {
  23932. var color = this._colors4[name];
  23933. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23934. }
  23935. // Vector2
  23936. for (name in this._vectors2) {
  23937. this._effect.setVector2(name, this._vectors2[name]);
  23938. }
  23939. // Vector3
  23940. for (name in this._vectors3) {
  23941. this._effect.setVector3(name, this._vectors3[name]);
  23942. }
  23943. // Matrix
  23944. for (name in this._matrices) {
  23945. this._effect.setMatrix(name, this._matrices[name]);
  23946. }
  23947. // VBOs
  23948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23949. if (this.isCube) {
  23950. for (var face = 0; face < 6; face++) {
  23951. engine.bindFramebuffer(this._texture, face);
  23952. this._effect.setFloat("face", face);
  23953. // Clear
  23954. engine.clear(scene.clearColor, true, true, true);
  23955. // Draw order
  23956. engine.draw(true, 0, 6);
  23957. // Mipmaps
  23958. if (face === 5) {
  23959. engine.generateMipMapsForCubemap(this._texture);
  23960. }
  23961. }
  23962. }
  23963. else {
  23964. engine.bindFramebuffer(this._texture);
  23965. // Clear
  23966. engine.clear(scene.clearColor, true, true, true);
  23967. // Draw order
  23968. engine.draw(true, 0, 6);
  23969. }
  23970. // Unbind
  23971. engine.unBindFramebuffer(this._texture, this.isCube);
  23972. if (this.onGenerated) {
  23973. this.onGenerated();
  23974. }
  23975. };
  23976. ProceduralTexture.prototype.clone = function () {
  23977. var textureSize = this.getSize();
  23978. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23979. // Base texture
  23980. newTexture.hasAlpha = this.hasAlpha;
  23981. newTexture.level = this.level;
  23982. // RenderTarget Texture
  23983. newTexture.coordinatesMode = this.coordinatesMode;
  23984. return newTexture;
  23985. };
  23986. ProceduralTexture.prototype.dispose = function () {
  23987. var index = this.getScene()._proceduralTextures.indexOf(this);
  23988. if (index >= 0) {
  23989. this.getScene()._proceduralTextures.splice(index, 1);
  23990. }
  23991. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23992. if (vertexBuffer) {
  23993. vertexBuffer.dispose();
  23994. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23995. }
  23996. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23997. this._indexBuffer = null;
  23998. }
  23999. _super.prototype.dispose.call(this);
  24000. };
  24001. return ProceduralTexture;
  24002. }(BABYLON.Texture));
  24003. BABYLON.ProceduralTexture = ProceduralTexture;
  24004. })(BABYLON || (BABYLON = {}));
  24005. var BABYLON;
  24006. (function (BABYLON) {
  24007. var MirrorTexture = (function (_super) {
  24008. __extends(MirrorTexture, _super);
  24009. function MirrorTexture(name, size, scene, generateMipMaps) {
  24010. var _this = this;
  24011. _super.call(this, name, size, scene, generateMipMaps, true);
  24012. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24013. this._transformMatrix = BABYLON.Matrix.Zero();
  24014. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24015. this.onBeforeRenderObservable.add(function () {
  24016. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24017. _this._savedViewMatrix = scene.getViewMatrix();
  24018. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24019. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24020. scene.clipPlane = _this.mirrorPlane;
  24021. scene.getEngine().cullBackFaces = false;
  24022. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24023. });
  24024. this.onAfterRenderObservable.add(function () {
  24025. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24026. scene.getEngine().cullBackFaces = true;
  24027. scene._mirroredCameraPosition = null;
  24028. delete scene.clipPlane;
  24029. });
  24030. }
  24031. MirrorTexture.prototype.clone = function () {
  24032. var textureSize = this.getSize();
  24033. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24034. // Base texture
  24035. newTexture.hasAlpha = this.hasAlpha;
  24036. newTexture.level = this.level;
  24037. // Mirror Texture
  24038. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24039. newTexture.renderList = this.renderList.slice(0);
  24040. return newTexture;
  24041. };
  24042. MirrorTexture.prototype.serialize = function () {
  24043. if (!this.name) {
  24044. return null;
  24045. }
  24046. var serializationObject = _super.prototype.serialize.call(this);
  24047. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24048. return serializationObject;
  24049. };
  24050. return MirrorTexture;
  24051. }(BABYLON.RenderTargetTexture));
  24052. BABYLON.MirrorTexture = MirrorTexture;
  24053. })(BABYLON || (BABYLON = {}));
  24054. var BABYLON;
  24055. (function (BABYLON) {
  24056. /**
  24057. * Creates a refraction texture used by refraction channel of the standard material.
  24058. * @param name the texture name
  24059. * @param size size of the underlying texture
  24060. * @param scene root scene
  24061. */
  24062. var RefractionTexture = (function (_super) {
  24063. __extends(RefractionTexture, _super);
  24064. function RefractionTexture(name, size, scene, generateMipMaps) {
  24065. var _this = this;
  24066. _super.call(this, name, size, scene, generateMipMaps, true);
  24067. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24068. this.depth = 2.0;
  24069. this.onBeforeRenderObservable.add(function () {
  24070. scene.clipPlane = _this.refractionPlane;
  24071. });
  24072. this.onAfterRenderObservable.add(function () {
  24073. delete scene.clipPlane;
  24074. });
  24075. }
  24076. RefractionTexture.prototype.clone = function () {
  24077. var textureSize = this.getSize();
  24078. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24079. // Base texture
  24080. newTexture.hasAlpha = this.hasAlpha;
  24081. newTexture.level = this.level;
  24082. // Refraction Texture
  24083. newTexture.refractionPlane = this.refractionPlane.clone();
  24084. newTexture.renderList = this.renderList.slice(0);
  24085. newTexture.depth = this.depth;
  24086. return newTexture;
  24087. };
  24088. RefractionTexture.prototype.serialize = function () {
  24089. if (!this.name) {
  24090. return null;
  24091. }
  24092. var serializationObject = _super.prototype.serialize.call(this);
  24093. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24094. serializationObject.depth = this.depth;
  24095. return serializationObject;
  24096. };
  24097. return RefractionTexture;
  24098. }(BABYLON.RenderTargetTexture));
  24099. BABYLON.RefractionTexture = RefractionTexture;
  24100. })(BABYLON || (BABYLON = {}));
  24101. var BABYLON;
  24102. (function (BABYLON) {
  24103. var DynamicTexture = (function (_super) {
  24104. __extends(DynamicTexture, _super);
  24105. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24107. _super.call(this, null, scene, !generateMipMaps);
  24108. this.name = name;
  24109. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24110. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24111. this._generateMipMaps = generateMipMaps;
  24112. if (options.getContext) {
  24113. this._canvas = options;
  24114. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24115. }
  24116. else {
  24117. this._canvas = document.createElement("canvas");
  24118. if (options.width) {
  24119. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24120. }
  24121. else {
  24122. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24123. }
  24124. }
  24125. var textureSize = this.getSize();
  24126. this._canvas.width = textureSize.width;
  24127. this._canvas.height = textureSize.height;
  24128. this._context = this._canvas.getContext("2d");
  24129. }
  24130. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24131. get: function () {
  24132. return true;
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. DynamicTexture.prototype.scale = function (ratio) {
  24138. var textureSize = this.getSize();
  24139. textureSize.width *= ratio;
  24140. textureSize.height *= ratio;
  24141. this._canvas.width = textureSize.width;
  24142. this._canvas.height = textureSize.height;
  24143. this.releaseInternalTexture();
  24144. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24145. };
  24146. DynamicTexture.prototype.getContext = function () {
  24147. return this._context;
  24148. };
  24149. DynamicTexture.prototype.clear = function () {
  24150. var size = this.getSize();
  24151. this._context.fillRect(0, 0, size.width, size.height);
  24152. };
  24153. DynamicTexture.prototype.update = function (invertY) {
  24154. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24155. };
  24156. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24157. if (update === void 0) { update = true; }
  24158. var size = this.getSize();
  24159. if (clearColor) {
  24160. this._context.fillStyle = clearColor;
  24161. this._context.fillRect(0, 0, size.width, size.height);
  24162. }
  24163. this._context.font = font;
  24164. if (x === null) {
  24165. var textSize = this._context.measureText(text);
  24166. x = (size.width - textSize.width) / 2;
  24167. }
  24168. this._context.fillStyle = color;
  24169. this._context.fillText(text, x, y);
  24170. if (update) {
  24171. this.update(invertY);
  24172. }
  24173. };
  24174. DynamicTexture.prototype.clone = function () {
  24175. var textureSize = this.getSize();
  24176. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24177. // Base texture
  24178. newTexture.hasAlpha = this.hasAlpha;
  24179. newTexture.level = this.level;
  24180. // Dynamic Texture
  24181. newTexture.wrapU = this.wrapU;
  24182. newTexture.wrapV = this.wrapV;
  24183. return newTexture;
  24184. };
  24185. return DynamicTexture;
  24186. }(BABYLON.Texture));
  24187. BABYLON.DynamicTexture = DynamicTexture;
  24188. })(BABYLON || (BABYLON = {}));
  24189. var BABYLON;
  24190. (function (BABYLON) {
  24191. var VideoTexture = (function (_super) {
  24192. __extends(VideoTexture, _super);
  24193. /**
  24194. * Creates a video texture.
  24195. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24196. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24197. * @param {BABYLON.Scene} scene is obviously the current scene.
  24198. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24199. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24200. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24201. */
  24202. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24203. var _this = this;
  24204. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24205. if (invertY === void 0) { invertY = false; }
  24206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24207. _super.call(this, null, scene, !generateMipMaps, invertY);
  24208. this._autoLaunch = true;
  24209. var urls;
  24210. this.name = name;
  24211. if (urlsOrVideo instanceof HTMLVideoElement) {
  24212. this.video = urlsOrVideo;
  24213. }
  24214. else {
  24215. urls = urlsOrVideo;
  24216. this.video = document.createElement("video");
  24217. this.video.autoplay = false;
  24218. this.video.loop = true;
  24219. }
  24220. this._generateMipMaps = generateMipMaps;
  24221. this._samplingMode = samplingMode;
  24222. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24223. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24224. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24225. }
  24226. else {
  24227. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24228. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24229. this._generateMipMaps = false;
  24230. }
  24231. if (urls) {
  24232. this.video.addEventListener("canplaythrough", function () {
  24233. _this._createTexture();
  24234. });
  24235. urls.forEach(function (url) {
  24236. var source = document.createElement("source");
  24237. source.src = url;
  24238. _this.video.appendChild(source);
  24239. });
  24240. }
  24241. else {
  24242. this._createTexture();
  24243. }
  24244. this._lastUpdate = BABYLON.Tools.Now;
  24245. }
  24246. VideoTexture.prototype._createTexture = function () {
  24247. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24248. this._texture.isReady = true;
  24249. };
  24250. VideoTexture.prototype.update = function () {
  24251. if (this._autoLaunch) {
  24252. this._autoLaunch = false;
  24253. this.video.play();
  24254. }
  24255. var now = BABYLON.Tools.Now;
  24256. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24257. return false;
  24258. }
  24259. this._lastUpdate = now;
  24260. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24261. return true;
  24262. };
  24263. return VideoTexture;
  24264. }(BABYLON.Texture));
  24265. BABYLON.VideoTexture = VideoTexture;
  24266. })(BABYLON || (BABYLON = {}));
  24267. var BABYLON;
  24268. (function (BABYLON) {
  24269. var CustomProceduralTexture = (function (_super) {
  24270. __extends(CustomProceduralTexture, _super);
  24271. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24272. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24273. this._animate = true;
  24274. this._time = 0;
  24275. this._texturePath = texturePath;
  24276. //Try to load json
  24277. this.loadJson(texturePath);
  24278. this.refreshRate = 1;
  24279. }
  24280. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24281. var _this = this;
  24282. var that = this;
  24283. function noConfigFile() {
  24284. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24285. try {
  24286. that.setFragment(that._texturePath);
  24287. }
  24288. catch (ex) {
  24289. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24290. }
  24291. }
  24292. var configFileUrl = jsonUrl + "/config.json";
  24293. var xhr = new XMLHttpRequest();
  24294. xhr.open("GET", configFileUrl, true);
  24295. xhr.addEventListener("load", function () {
  24296. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24297. try {
  24298. _this._config = JSON.parse(xhr.response);
  24299. _this.updateShaderUniforms();
  24300. _this.updateTextures();
  24301. _this.setFragment(_this._texturePath + "/custom");
  24302. _this._animate = _this._config.animate;
  24303. _this.refreshRate = _this._config.refreshrate;
  24304. }
  24305. catch (ex) {
  24306. noConfigFile();
  24307. }
  24308. }
  24309. else {
  24310. noConfigFile();
  24311. }
  24312. }, false);
  24313. xhr.addEventListener("error", function () {
  24314. noConfigFile();
  24315. }, false);
  24316. try {
  24317. xhr.send();
  24318. }
  24319. catch (ex) {
  24320. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24321. }
  24322. };
  24323. CustomProceduralTexture.prototype.isReady = function () {
  24324. if (!_super.prototype.isReady.call(this)) {
  24325. return false;
  24326. }
  24327. for (var name in this._textures) {
  24328. var texture = this._textures[name];
  24329. if (!texture.isReady()) {
  24330. return false;
  24331. }
  24332. }
  24333. return true;
  24334. };
  24335. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24336. if (this._animate) {
  24337. this._time += this.getScene().getAnimationRatio() * 0.03;
  24338. this.updateShaderUniforms();
  24339. }
  24340. _super.prototype.render.call(this, useCameraPostProcess);
  24341. };
  24342. CustomProceduralTexture.prototype.updateTextures = function () {
  24343. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24344. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24345. }
  24346. };
  24347. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24348. if (this._config) {
  24349. for (var j = 0; j < this._config.uniforms.length; j++) {
  24350. var uniform = this._config.uniforms[j];
  24351. switch (uniform.type) {
  24352. case "float":
  24353. this.setFloat(uniform.name, uniform.value);
  24354. break;
  24355. case "color3":
  24356. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24357. break;
  24358. case "color4":
  24359. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24360. break;
  24361. case "vector2":
  24362. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24363. break;
  24364. case "vector3":
  24365. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24366. break;
  24367. }
  24368. }
  24369. }
  24370. this.setFloat("time", this._time);
  24371. };
  24372. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24373. get: function () {
  24374. return this._animate;
  24375. },
  24376. set: function (value) {
  24377. this._animate = value;
  24378. },
  24379. enumerable: true,
  24380. configurable: true
  24381. });
  24382. return CustomProceduralTexture;
  24383. }(BABYLON.ProceduralTexture));
  24384. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24385. })(BABYLON || (BABYLON = {}));
  24386. var BABYLON;
  24387. (function (BABYLON) {
  24388. var EffectFallbacks = (function () {
  24389. function EffectFallbacks() {
  24390. this._defines = {};
  24391. this._currentRank = 32;
  24392. this._maxRank = -1;
  24393. }
  24394. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24395. if (!this._defines[rank]) {
  24396. if (rank < this._currentRank) {
  24397. this._currentRank = rank;
  24398. }
  24399. if (rank > this._maxRank) {
  24400. this._maxRank = rank;
  24401. }
  24402. this._defines[rank] = new Array();
  24403. }
  24404. this._defines[rank].push(define);
  24405. };
  24406. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24407. this._meshRank = rank;
  24408. this._mesh = mesh;
  24409. if (rank > this._maxRank) {
  24410. this._maxRank = rank;
  24411. }
  24412. };
  24413. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24414. get: function () {
  24415. return this._currentRank <= this._maxRank;
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24421. var currentFallbacks = this._defines[this._currentRank];
  24422. for (var index = 0; index < currentFallbacks.length; index++) {
  24423. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24424. }
  24425. if (this._mesh && this._currentRank === this._meshRank) {
  24426. this._mesh.computeBonesUsingShaders = false;
  24427. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24428. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24429. }
  24430. this._currentRank++;
  24431. return currentDefines;
  24432. };
  24433. return EffectFallbacks;
  24434. }());
  24435. BABYLON.EffectFallbacks = EffectFallbacks;
  24436. var Effect = (function () {
  24437. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24438. var _this = this;
  24439. this._isReady = false;
  24440. this._compilationError = "";
  24441. this._valueCache = {};
  24442. this._engine = engine;
  24443. this.name = baseName;
  24444. this.defines = defines;
  24445. this._uniformsNames = uniformsNames.concat(samplers);
  24446. this._samplers = samplers;
  24447. this._attributesNames = attributesNames;
  24448. this.onError = onError;
  24449. this.onCompiled = onCompiled;
  24450. this._indexParameters = indexParameters;
  24451. var vertexSource;
  24452. var fragmentSource;
  24453. if (baseName.vertexElement) {
  24454. vertexSource = document.getElementById(baseName.vertexElement);
  24455. if (!vertexSource) {
  24456. vertexSource = baseName.vertexElement;
  24457. }
  24458. }
  24459. else {
  24460. vertexSource = baseName.vertex || baseName;
  24461. }
  24462. if (baseName.fragmentElement) {
  24463. fragmentSource = document.getElementById(baseName.fragmentElement);
  24464. if (!fragmentSource) {
  24465. fragmentSource = baseName.fragmentElement;
  24466. }
  24467. }
  24468. else {
  24469. fragmentSource = baseName.fragment || baseName;
  24470. }
  24471. this._loadVertexShader(vertexSource, function (vertexCode) {
  24472. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24473. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24474. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24475. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24476. });
  24477. });
  24478. });
  24479. });
  24480. }
  24481. // Properties
  24482. Effect.prototype.isReady = function () {
  24483. return this._isReady;
  24484. };
  24485. Effect.prototype.getProgram = function () {
  24486. return this._program;
  24487. };
  24488. Effect.prototype.getAttributesNames = function () {
  24489. return this._attributesNames;
  24490. };
  24491. Effect.prototype.getAttributeLocation = function (index) {
  24492. return this._attributes[index];
  24493. };
  24494. Effect.prototype.getAttributeLocationByName = function (name) {
  24495. var index = this._attributesNames.indexOf(name);
  24496. return this._attributes[index];
  24497. };
  24498. Effect.prototype.getAttributesCount = function () {
  24499. return this._attributes.length;
  24500. };
  24501. Effect.prototype.getUniformIndex = function (uniformName) {
  24502. return this._uniformsNames.indexOf(uniformName);
  24503. };
  24504. Effect.prototype.getUniform = function (uniformName) {
  24505. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24506. };
  24507. Effect.prototype.getSamplers = function () {
  24508. return this._samplers;
  24509. };
  24510. Effect.prototype.getCompilationError = function () {
  24511. return this._compilationError;
  24512. };
  24513. // Methods
  24514. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24515. // DOM element ?
  24516. if (vertex instanceof HTMLElement) {
  24517. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24518. callback(vertexCode);
  24519. return;
  24520. }
  24521. // Base64 encoded ?
  24522. if (vertex.substr(0, 7) === "base64:") {
  24523. var vertexBinary = window.atob(vertex.substr(7));
  24524. callback(vertexBinary);
  24525. return;
  24526. }
  24527. // Is in local store ?
  24528. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24529. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24530. return;
  24531. }
  24532. var vertexShaderUrl;
  24533. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24534. vertexShaderUrl = vertex;
  24535. }
  24536. else {
  24537. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24538. }
  24539. // Vertex shader
  24540. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24541. };
  24542. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24543. // DOM element ?
  24544. if (fragment instanceof HTMLElement) {
  24545. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24546. callback(fragmentCode);
  24547. return;
  24548. }
  24549. // Base64 encoded ?
  24550. if (fragment.substr(0, 7) === "base64:") {
  24551. var fragmentBinary = window.atob(fragment.substr(7));
  24552. callback(fragmentBinary);
  24553. return;
  24554. }
  24555. // Is in local store ?
  24556. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24557. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24558. return;
  24559. }
  24560. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24561. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24562. return;
  24563. }
  24564. var fragmentShaderUrl;
  24565. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24566. fragmentShaderUrl = fragment;
  24567. }
  24568. else {
  24569. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24570. }
  24571. // Fragment shader
  24572. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24573. };
  24574. Effect.prototype._dumpShadersName = function () {
  24575. if (this.name.vertexElement) {
  24576. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24577. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24578. }
  24579. else if (this.name.vertex) {
  24580. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24581. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24582. }
  24583. else {
  24584. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24585. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24586. }
  24587. };
  24588. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24589. var _this = this;
  24590. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24591. var match = regex.exec(sourceCode);
  24592. var returnValue = new String(sourceCode);
  24593. while (match != null) {
  24594. var includeFile = match[1];
  24595. if (Effect.IncludesShadersStore[includeFile]) {
  24596. // Substitution
  24597. var includeContent = Effect.IncludesShadersStore[includeFile];
  24598. if (match[2]) {
  24599. var splits = match[3].split(",");
  24600. for (var index = 0; index < splits.length; index += 2) {
  24601. var source = new RegExp(splits[index], "g");
  24602. var dest = splits[index + 1];
  24603. includeContent = includeContent.replace(source, dest);
  24604. }
  24605. }
  24606. if (match[4]) {
  24607. var indexString = match[5];
  24608. if (indexString.indexOf("..") !== -1) {
  24609. var indexSplits = indexString.split("..");
  24610. var minIndex = parseInt(indexSplits[0]);
  24611. var maxIndex = parseInt(indexSplits[1]);
  24612. var sourceIncludeContent = includeContent.slice(0);
  24613. includeContent = "";
  24614. if (isNaN(maxIndex)) {
  24615. maxIndex = this._indexParameters[indexSplits[1]];
  24616. }
  24617. for (var i = minIndex; i <= maxIndex; i++) {
  24618. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24619. }
  24620. }
  24621. else {
  24622. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24623. }
  24624. }
  24625. // Replace
  24626. returnValue = returnValue.replace(match[0], includeContent);
  24627. }
  24628. else {
  24629. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24630. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24631. Effect.IncludesShadersStore[includeFile] = fileContent;
  24632. _this._processIncludes(returnValue, callback);
  24633. });
  24634. return;
  24635. }
  24636. match = regex.exec(sourceCode);
  24637. }
  24638. callback(returnValue);
  24639. };
  24640. Effect.prototype._processPrecision = function (source) {
  24641. if (source.indexOf("precision highp float") === -1) {
  24642. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24643. source = "precision mediump float;\n" + source;
  24644. }
  24645. else {
  24646. source = "precision highp float;\n" + source;
  24647. }
  24648. }
  24649. else {
  24650. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24651. source = source.replace("precision highp float", "precision mediump float");
  24652. }
  24653. }
  24654. return source;
  24655. };
  24656. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24657. try {
  24658. var engine = this._engine;
  24659. // Precision
  24660. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24661. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24662. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24663. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24664. this._attributes = engine.getAttributes(this._program, attributesNames);
  24665. var index;
  24666. for (index = 0; index < this._samplers.length; index++) {
  24667. var sampler = this.getUniform(this._samplers[index]);
  24668. if (sampler == null) {
  24669. this._samplers.splice(index, 1);
  24670. index--;
  24671. }
  24672. }
  24673. engine.bindSamplers(this);
  24674. this._isReady = true;
  24675. if (this.onCompiled) {
  24676. this.onCompiled(this);
  24677. }
  24678. }
  24679. catch (e) {
  24680. // Let's go through fallbacks then
  24681. if (fallbacks && fallbacks.isMoreFallbacks) {
  24682. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24683. this._dumpShadersName();
  24684. defines = fallbacks.reduce(defines);
  24685. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24686. }
  24687. else {
  24688. BABYLON.Tools.Error("Unable to compile effect: ");
  24689. this._dumpShadersName();
  24690. BABYLON.Tools.Error("Defines: " + defines);
  24691. BABYLON.Tools.Error("Error: " + e.message);
  24692. this._compilationError = e.message;
  24693. if (this.onError) {
  24694. this.onError(this, this._compilationError);
  24695. }
  24696. }
  24697. }
  24698. };
  24699. Object.defineProperty(Effect.prototype, "isSupported", {
  24700. get: function () {
  24701. return this._compilationError === "";
  24702. },
  24703. enumerable: true,
  24704. configurable: true
  24705. });
  24706. Effect.prototype._bindTexture = function (channel, texture) {
  24707. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24708. };
  24709. Effect.prototype.setTexture = function (channel, texture) {
  24710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24711. };
  24712. Effect.prototype.setTextureArray = function (channel, textures) {
  24713. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24714. var initialPos = this._samplers.indexOf(channel);
  24715. for (var index = 1; index < textures.length; index++) {
  24716. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24717. }
  24718. }
  24719. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24720. };
  24721. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24722. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24723. };
  24724. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24725. var changed = false;
  24726. var cache = this._valueCache[uniformName];
  24727. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24728. changed = true;
  24729. cache = new BABYLON.Matrix();
  24730. }
  24731. var tm = cache.m;
  24732. var om = matrix.m;
  24733. for (var index = 0; index < 16; index++) {
  24734. if (tm[index] !== om[index]) {
  24735. tm[index] = om[index];
  24736. changed = true;
  24737. }
  24738. }
  24739. this._valueCache[uniformName] = cache;
  24740. return changed;
  24741. };
  24742. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24743. var cache = this._valueCache[uniformName];
  24744. if (!cache) {
  24745. cache = [x, y];
  24746. this._valueCache[uniformName] = cache;
  24747. return true;
  24748. }
  24749. var changed = false;
  24750. if (cache[0] !== x) {
  24751. cache[0] = x;
  24752. changed = true;
  24753. }
  24754. if (cache[1] !== y) {
  24755. cache[1] = y;
  24756. changed = true;
  24757. }
  24758. return changed;
  24759. };
  24760. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24761. var cache = this._valueCache[uniformName];
  24762. if (!cache) {
  24763. cache = [x, y, z];
  24764. this._valueCache[uniformName] = cache;
  24765. return true;
  24766. }
  24767. var changed = false;
  24768. if (cache[0] !== x) {
  24769. cache[0] = x;
  24770. changed = true;
  24771. }
  24772. if (cache[1] !== y) {
  24773. cache[1] = y;
  24774. changed = true;
  24775. }
  24776. if (cache[2] !== z) {
  24777. cache[2] = z;
  24778. changed = true;
  24779. }
  24780. return changed;
  24781. };
  24782. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24783. var cache = this._valueCache[uniformName];
  24784. if (!cache) {
  24785. cache = [x, y, z, w];
  24786. this._valueCache[uniformName] = cache;
  24787. return true;
  24788. }
  24789. var changed = false;
  24790. if (cache[0] !== x) {
  24791. cache[0] = x;
  24792. changed = true;
  24793. }
  24794. if (cache[1] !== y) {
  24795. cache[1] = y;
  24796. changed = true;
  24797. }
  24798. if (cache[2] !== z) {
  24799. cache[2] = z;
  24800. changed = true;
  24801. }
  24802. if (cache[3] !== w) {
  24803. cache[3] = w;
  24804. changed = true;
  24805. }
  24806. return changed;
  24807. };
  24808. Effect.prototype.setIntArray = function (uniformName, array) {
  24809. this._valueCache[uniformName] = null;
  24810. this._engine.setIntArray(this.getUniform(uniformName), array);
  24811. return this;
  24812. };
  24813. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24814. this._valueCache[uniformName] = null;
  24815. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24816. return this;
  24817. };
  24818. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24819. this._valueCache[uniformName] = null;
  24820. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24821. return this;
  24822. };
  24823. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24824. this._valueCache[uniformName] = null;
  24825. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24826. return this;
  24827. };
  24828. Effect.prototype.setFloatArray = function (uniformName, array) {
  24829. this._valueCache[uniformName] = null;
  24830. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24831. return this;
  24832. };
  24833. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24834. this._valueCache[uniformName] = null;
  24835. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24836. return this;
  24837. };
  24838. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24839. this._valueCache[uniformName] = null;
  24840. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24841. return this;
  24842. };
  24843. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24844. this._valueCache[uniformName] = null;
  24845. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24846. return this;
  24847. };
  24848. Effect.prototype.setArray = function (uniformName, array) {
  24849. this._valueCache[uniformName] = null;
  24850. this._engine.setArray(this.getUniform(uniformName), array);
  24851. return this;
  24852. };
  24853. Effect.prototype.setArray2 = function (uniformName, array) {
  24854. this._valueCache[uniformName] = null;
  24855. this._engine.setArray2(this.getUniform(uniformName), array);
  24856. return this;
  24857. };
  24858. Effect.prototype.setArray3 = function (uniformName, array) {
  24859. this._valueCache[uniformName] = null;
  24860. this._engine.setArray3(this.getUniform(uniformName), array);
  24861. return this;
  24862. };
  24863. Effect.prototype.setArray4 = function (uniformName, array) {
  24864. this._valueCache[uniformName] = null;
  24865. this._engine.setArray4(this.getUniform(uniformName), array);
  24866. return this;
  24867. };
  24868. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24869. this._valueCache[uniformName] = null;
  24870. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24871. return this;
  24872. };
  24873. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24874. if (this._cacheMatrix(uniformName, matrix)) {
  24875. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24876. }
  24877. return this;
  24878. };
  24879. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24880. this._valueCache[uniformName] = null;
  24881. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24882. return this;
  24883. };
  24884. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24885. this._valueCache[uniformName] = null;
  24886. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24887. return this;
  24888. };
  24889. Effect.prototype.setFloat = function (uniformName, value) {
  24890. var cache = this._valueCache[uniformName];
  24891. if (cache !== undefined && cache === value)
  24892. return this;
  24893. this._valueCache[uniformName] = value;
  24894. this._engine.setFloat(this.getUniform(uniformName), value);
  24895. return this;
  24896. };
  24897. Effect.prototype.setBool = function (uniformName, bool) {
  24898. var cache = this._valueCache[uniformName];
  24899. if (cache !== undefined && cache === bool)
  24900. return this;
  24901. this._valueCache[uniformName] = bool;
  24902. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24903. return this;
  24904. };
  24905. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24906. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24907. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24908. }
  24909. return this;
  24910. };
  24911. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24912. if (this._cacheFloat2(uniformName, x, y)) {
  24913. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24914. }
  24915. return this;
  24916. };
  24917. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24918. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24919. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24920. }
  24921. return this;
  24922. };
  24923. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24924. if (this._cacheFloat3(uniformName, x, y, z)) {
  24925. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24926. }
  24927. return this;
  24928. };
  24929. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24930. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24931. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24932. }
  24933. return this;
  24934. };
  24935. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24936. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24937. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24938. }
  24939. return this;
  24940. };
  24941. Effect.prototype.setColor3 = function (uniformName, color3) {
  24942. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24943. this._engine.setColor3(this.getUniform(uniformName), color3);
  24944. }
  24945. return this;
  24946. };
  24947. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24948. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24949. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24950. }
  24951. return this;
  24952. };
  24953. // Statics
  24954. Effect.ShadersStore = {};
  24955. Effect.IncludesShadersStore = {};
  24956. return Effect;
  24957. }());
  24958. BABYLON.Effect = Effect;
  24959. })(BABYLON || (BABYLON = {}));
  24960. var BABYLON;
  24961. (function (BABYLON) {
  24962. var MaterialHelper = (function () {
  24963. function MaterialHelper() {
  24964. }
  24965. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24966. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24967. var lightIndex = 0;
  24968. var needNormals = false;
  24969. var needRebuild = false;
  24970. var needShadows = false;
  24971. var lightmapMode = false;
  24972. for (var index = 0; index < scene.lights.length; index++) {
  24973. var light = scene.lights[index];
  24974. if (!light.isEnabled()) {
  24975. continue;
  24976. }
  24977. // Excluded check
  24978. if (light._excludedMeshesIds.length > 0) {
  24979. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24980. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24981. if (excludedMesh) {
  24982. light.excludedMeshes.push(excludedMesh);
  24983. }
  24984. }
  24985. light._excludedMeshesIds = [];
  24986. }
  24987. // Included check
  24988. if (light._includedOnlyMeshesIds.length > 0) {
  24989. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24990. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24991. if (includedOnlyMesh) {
  24992. light.includedOnlyMeshes.push(includedOnlyMesh);
  24993. }
  24994. }
  24995. light._includedOnlyMeshesIds = [];
  24996. }
  24997. if (!light.canAffectMesh(mesh)) {
  24998. continue;
  24999. }
  25000. needNormals = true;
  25001. if (defines["LIGHT" + lightIndex] === undefined) {
  25002. needRebuild = true;
  25003. }
  25004. defines["LIGHT" + lightIndex] = true;
  25005. var type;
  25006. if (light instanceof BABYLON.SpotLight) {
  25007. type = "SPOTLIGHT" + lightIndex;
  25008. }
  25009. else if (light instanceof BABYLON.HemisphericLight) {
  25010. type = "HEMILIGHT" + lightIndex;
  25011. }
  25012. else if (light instanceof BABYLON.PointLight) {
  25013. type = "POINTLIGHT" + lightIndex;
  25014. }
  25015. else {
  25016. type = "DIRLIGHT" + lightIndex;
  25017. }
  25018. if (defines[type] === undefined) {
  25019. needRebuild = true;
  25020. }
  25021. defines[type] = true;
  25022. // Specular
  25023. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25024. defines["SPECULARTERM"] = true;
  25025. }
  25026. // Shadows
  25027. if (scene.shadowsEnabled) {
  25028. var shadowGenerator = light.getShadowGenerator();
  25029. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25030. if (defines["SHADOW" + lightIndex] === undefined) {
  25031. needRebuild = true;
  25032. }
  25033. defines["SHADOW" + lightIndex] = true;
  25034. defines["SHADOWS"] = true;
  25035. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25036. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25037. needRebuild = true;
  25038. }
  25039. defines["SHADOWVSM" + lightIndex] = true;
  25040. }
  25041. if (shadowGenerator.usePoissonSampling) {
  25042. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25043. needRebuild = true;
  25044. }
  25045. defines["SHADOWPCF" + lightIndex] = true;
  25046. }
  25047. needShadows = true;
  25048. }
  25049. }
  25050. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25051. lightmapMode = true;
  25052. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25053. needRebuild = true;
  25054. }
  25055. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25056. needRebuild = true;
  25057. }
  25058. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25059. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25060. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25061. }
  25062. }
  25063. lightIndex++;
  25064. if (lightIndex === maxSimultaneousLights)
  25065. break;
  25066. }
  25067. var caps = scene.getEngine().getCaps();
  25068. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25069. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25070. needRebuild = true;
  25071. }
  25072. defines["SHADOWFULLFLOAT"] = true;
  25073. }
  25074. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25075. needRebuild = true;
  25076. }
  25077. if (lightmapMode) {
  25078. defines["LIGHTMAPEXCLUDED"] = true;
  25079. }
  25080. if (needRebuild) {
  25081. defines.rebuild();
  25082. }
  25083. return needNormals;
  25084. };
  25085. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25086. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25087. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25088. if (!defines["LIGHT" + lightIndex]) {
  25089. break;
  25090. }
  25091. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25092. samplersList.push("shadowSampler" + lightIndex);
  25093. }
  25094. };
  25095. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25096. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25097. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25098. if (!defines["LIGHT" + lightIndex]) {
  25099. break;
  25100. }
  25101. if (lightIndex > 0) {
  25102. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25103. }
  25104. if (defines["SHADOW" + lightIndex]) {
  25105. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25106. }
  25107. if (defines["SHADOWPCF" + lightIndex]) {
  25108. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25109. }
  25110. if (defines["SHADOWVSM" + lightIndex]) {
  25111. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25112. }
  25113. }
  25114. };
  25115. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25116. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25117. fallbacks.addCPUSkinningFallback(0, mesh);
  25118. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25119. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25120. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25121. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25122. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25123. }
  25124. }
  25125. };
  25126. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25127. if (defines["INSTANCES"]) {
  25128. attribs.push("world0");
  25129. attribs.push("world1");
  25130. attribs.push("world2");
  25131. attribs.push("world3");
  25132. }
  25133. };
  25134. // Bindings
  25135. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25136. var shadowGenerator = light.getShadowGenerator();
  25137. if (mesh.receiveShadows && shadowGenerator) {
  25138. if (!light.needCube()) {
  25139. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25140. }
  25141. else {
  25142. if (!depthValuesAlreadySet) {
  25143. depthValuesAlreadySet = true;
  25144. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25145. }
  25146. }
  25147. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25148. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25149. }
  25150. return depthValuesAlreadySet;
  25151. };
  25152. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25153. if (light instanceof BABYLON.PointLight) {
  25154. // Point Light
  25155. light.transferToEffect(effect, "vLightData" + lightIndex);
  25156. }
  25157. else if (light instanceof BABYLON.DirectionalLight) {
  25158. // Directional Light
  25159. light.transferToEffect(effect, "vLightData" + lightIndex);
  25160. }
  25161. else if (light instanceof BABYLON.SpotLight) {
  25162. // Spot Light
  25163. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25164. }
  25165. else if (light instanceof BABYLON.HemisphericLight) {
  25166. // Hemispheric Light
  25167. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25168. }
  25169. };
  25170. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25171. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25172. var lightIndex = 0;
  25173. var depthValuesAlreadySet = false;
  25174. for (var index = 0; index < scene.lights.length; index++) {
  25175. var light = scene.lights[index];
  25176. if (!light.isEnabled()) {
  25177. continue;
  25178. }
  25179. if (!light.canAffectMesh(mesh)) {
  25180. continue;
  25181. }
  25182. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25183. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25184. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25185. if (defines["SPECULARTERM"]) {
  25186. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25187. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25188. }
  25189. // Shadows
  25190. if (scene.shadowsEnabled) {
  25191. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25192. }
  25193. lightIndex++;
  25194. if (lightIndex === maxSimultaneousLights)
  25195. break;
  25196. }
  25197. };
  25198. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25199. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25200. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25201. effect.setColor3("vFogColor", scene.fogColor);
  25202. }
  25203. };
  25204. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25205. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25206. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25207. if (matrices) {
  25208. effect.setMatrices("mBones", matrices);
  25209. }
  25210. }
  25211. };
  25212. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25213. if (defines["LOGARITHMICDEPTH"]) {
  25214. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25215. }
  25216. };
  25217. MaterialHelper.BindClipPlane = function (effect, scene) {
  25218. if (scene.clipPlane) {
  25219. var clipPlane = scene.clipPlane;
  25220. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25221. }
  25222. };
  25223. return MaterialHelper;
  25224. }());
  25225. BABYLON.MaterialHelper = MaterialHelper;
  25226. })(BABYLON || (BABYLON = {}));
  25227. var BABYLON;
  25228. (function (BABYLON) {
  25229. var FresnelParameters = (function () {
  25230. function FresnelParameters() {
  25231. this.isEnabled = true;
  25232. this.leftColor = BABYLON.Color3.White();
  25233. this.rightColor = BABYLON.Color3.Black();
  25234. this.bias = 0;
  25235. this.power = 1;
  25236. }
  25237. FresnelParameters.prototype.clone = function () {
  25238. var newFresnelParameters = new FresnelParameters();
  25239. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25240. return newFresnelParameters;
  25241. };
  25242. FresnelParameters.prototype.serialize = function () {
  25243. var serializationObject = {};
  25244. serializationObject.isEnabled = this.isEnabled;
  25245. serializationObject.leftColor = this.leftColor;
  25246. serializationObject.rightColor = this.rightColor;
  25247. serializationObject.bias = this.bias;
  25248. serializationObject.power = this.power;
  25249. return serializationObject;
  25250. };
  25251. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25252. var fresnelParameters = new FresnelParameters();
  25253. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25254. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25255. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25256. fresnelParameters.bias = parsedFresnelParameters.bias;
  25257. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25258. return fresnelParameters;
  25259. };
  25260. return FresnelParameters;
  25261. }());
  25262. BABYLON.FresnelParameters = FresnelParameters;
  25263. })(BABYLON || (BABYLON = {}));
  25264. var BABYLON;
  25265. (function (BABYLON) {
  25266. var MaterialDefines = (function () {
  25267. function MaterialDefines() {
  25268. }
  25269. MaterialDefines.prototype.rebuild = function () {
  25270. if (this._keys) {
  25271. delete this._keys;
  25272. }
  25273. this._keys = Object.keys(this);
  25274. };
  25275. MaterialDefines.prototype.isEqual = function (other) {
  25276. if (this._keys.length !== other._keys.length) {
  25277. return false;
  25278. }
  25279. for (var index = 0; index < this._keys.length; index++) {
  25280. var prop = this._keys[index];
  25281. if (this[prop] !== other[prop]) {
  25282. return false;
  25283. }
  25284. }
  25285. return true;
  25286. };
  25287. MaterialDefines.prototype.cloneTo = function (other) {
  25288. if (this._keys.length !== other._keys.length) {
  25289. other._keys = this._keys.slice(0);
  25290. }
  25291. for (var index = 0; index < this._keys.length; index++) {
  25292. var prop = this._keys[index];
  25293. other[prop] = this[prop];
  25294. }
  25295. };
  25296. MaterialDefines.prototype.reset = function () {
  25297. for (var index = 0; index < this._keys.length; index++) {
  25298. var prop = this._keys[index];
  25299. if (typeof (this[prop]) === "number") {
  25300. this[prop] = 0;
  25301. }
  25302. else {
  25303. this[prop] = false;
  25304. }
  25305. }
  25306. };
  25307. MaterialDefines.prototype.toString = function () {
  25308. var result = "";
  25309. for (var index = 0; index < this._keys.length; index++) {
  25310. var prop = this._keys[index];
  25311. if (typeof (this[prop]) === "number") {
  25312. result += "#define " + prop + " " + this[prop] + "\n";
  25313. }
  25314. else if (this[prop]) {
  25315. result += "#define " + prop + "\n";
  25316. }
  25317. }
  25318. return result;
  25319. };
  25320. return MaterialDefines;
  25321. }());
  25322. BABYLON.MaterialDefines = MaterialDefines;
  25323. var Material = (function () {
  25324. function Material(name, scene, doNotAdd) {
  25325. this.name = name;
  25326. this.checkReadyOnEveryCall = false;
  25327. this.checkReadyOnlyOnce = false;
  25328. this.state = "";
  25329. this.alpha = 1.0;
  25330. this.backFaceCulling = true;
  25331. /**
  25332. * An event triggered when the material is disposed.
  25333. * @type {BABYLON.Observable}
  25334. */
  25335. this.onDisposeObservable = new BABYLON.Observable();
  25336. /**
  25337. * An event triggered when the material is bound.
  25338. * @type {BABYLON.Observable}
  25339. */
  25340. this.onBindObservable = new BABYLON.Observable();
  25341. /**
  25342. * An event triggered when the material is unbound.
  25343. * @type {BABYLON.Observable}
  25344. */
  25345. this.onUnBindObservable = new BABYLON.Observable();
  25346. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25347. this.disableDepthWrite = false;
  25348. this.fogEnabled = true;
  25349. this.pointSize = 1.0;
  25350. this.zOffset = 0;
  25351. this._wasPreviouslyReady = false;
  25352. this._fillMode = Material.TriangleFillMode;
  25353. this.id = name;
  25354. this._scene = scene;
  25355. if (scene.useRightHandedSystem) {
  25356. this.sideOrientation = Material.ClockWiseSideOrientation;
  25357. }
  25358. else {
  25359. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25360. }
  25361. if (!doNotAdd) {
  25362. scene.materials.push(this);
  25363. }
  25364. }
  25365. Object.defineProperty(Material, "TriangleFillMode", {
  25366. get: function () {
  25367. return Material._TriangleFillMode;
  25368. },
  25369. enumerable: true,
  25370. configurable: true
  25371. });
  25372. Object.defineProperty(Material, "WireFrameFillMode", {
  25373. get: function () {
  25374. return Material._WireFrameFillMode;
  25375. },
  25376. enumerable: true,
  25377. configurable: true
  25378. });
  25379. Object.defineProperty(Material, "PointFillMode", {
  25380. get: function () {
  25381. return Material._PointFillMode;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25387. get: function () {
  25388. return Material._ClockWiseSideOrientation;
  25389. },
  25390. enumerable: true,
  25391. configurable: true
  25392. });
  25393. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25394. get: function () {
  25395. return Material._CounterClockWiseSideOrientation;
  25396. },
  25397. enumerable: true,
  25398. configurable: true
  25399. });
  25400. Object.defineProperty(Material.prototype, "onDispose", {
  25401. set: function (callback) {
  25402. if (this._onDisposeObserver) {
  25403. this.onDisposeObservable.remove(this._onDisposeObserver);
  25404. }
  25405. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25406. },
  25407. enumerable: true,
  25408. configurable: true
  25409. });
  25410. Object.defineProperty(Material.prototype, "onBind", {
  25411. set: function (callback) {
  25412. if (this._onBindObserver) {
  25413. this.onBindObservable.remove(this._onBindObserver);
  25414. }
  25415. this._onBindObserver = this.onBindObservable.add(callback);
  25416. },
  25417. enumerable: true,
  25418. configurable: true
  25419. });
  25420. Object.defineProperty(Material.prototype, "wireframe", {
  25421. get: function () {
  25422. return this._fillMode === Material.WireFrameFillMode;
  25423. },
  25424. set: function (value) {
  25425. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25426. },
  25427. enumerable: true,
  25428. configurable: true
  25429. });
  25430. Object.defineProperty(Material.prototype, "pointsCloud", {
  25431. get: function () {
  25432. return this._fillMode === Material.PointFillMode;
  25433. },
  25434. set: function (value) {
  25435. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25436. },
  25437. enumerable: true,
  25438. configurable: true
  25439. });
  25440. Object.defineProperty(Material.prototype, "fillMode", {
  25441. get: function () {
  25442. return this._fillMode;
  25443. },
  25444. set: function (value) {
  25445. this._fillMode = value;
  25446. },
  25447. enumerable: true,
  25448. configurable: true
  25449. });
  25450. /**
  25451. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25452. * subclasses should override adding information pertainent to themselves
  25453. */
  25454. Material.prototype.toString = function (fullDetails) {
  25455. var ret = "Name: " + this.name;
  25456. if (fullDetails) {
  25457. }
  25458. return ret;
  25459. };
  25460. Object.defineProperty(Material.prototype, "isFrozen", {
  25461. get: function () {
  25462. return this.checkReadyOnlyOnce;
  25463. },
  25464. enumerable: true,
  25465. configurable: true
  25466. });
  25467. Material.prototype.freeze = function () {
  25468. this.checkReadyOnlyOnce = true;
  25469. };
  25470. Material.prototype.unfreeze = function () {
  25471. this.checkReadyOnlyOnce = false;
  25472. };
  25473. Material.prototype.isReady = function (mesh, useInstances) {
  25474. return true;
  25475. };
  25476. Material.prototype.getEffect = function () {
  25477. return this._effect;
  25478. };
  25479. Material.prototype.getScene = function () {
  25480. return this._scene;
  25481. };
  25482. Material.prototype.needAlphaBlending = function () {
  25483. return (this.alpha < 1.0);
  25484. };
  25485. Material.prototype.needAlphaTesting = function () {
  25486. return false;
  25487. };
  25488. Material.prototype.getAlphaTestTexture = function () {
  25489. return null;
  25490. };
  25491. Material.prototype.markDirty = function () {
  25492. this._wasPreviouslyReady = false;
  25493. };
  25494. Material.prototype._preBind = function () {
  25495. var engine = this._scene.getEngine();
  25496. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25497. engine.enableEffect(this._effect);
  25498. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25499. };
  25500. Material.prototype.bind = function (world, mesh) {
  25501. this._scene._cachedMaterial = this;
  25502. this.onBindObservable.notifyObservers(mesh);
  25503. if (this.disableDepthWrite) {
  25504. var engine = this._scene.getEngine();
  25505. this._cachedDepthWriteState = engine.getDepthWrite();
  25506. engine.setDepthWrite(false);
  25507. }
  25508. };
  25509. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25510. };
  25511. Material.prototype.unbind = function () {
  25512. this.onUnBindObservable.notifyObservers(this);
  25513. if (this.disableDepthWrite) {
  25514. var engine = this._scene.getEngine();
  25515. engine.setDepthWrite(this._cachedDepthWriteState);
  25516. }
  25517. };
  25518. Material.prototype.clone = function (name) {
  25519. return null;
  25520. };
  25521. Material.prototype.getBindedMeshes = function () {
  25522. var result = new Array();
  25523. for (var index = 0; index < this._scene.meshes.length; index++) {
  25524. var mesh = this._scene.meshes[index];
  25525. if (mesh.material === this) {
  25526. result.push(mesh);
  25527. }
  25528. }
  25529. return result;
  25530. };
  25531. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25532. // Animations
  25533. this.getScene().stopAnimation(this);
  25534. // Remove from scene
  25535. var index = this._scene.materials.indexOf(this);
  25536. if (index >= 0) {
  25537. this._scene.materials.splice(index, 1);
  25538. }
  25539. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25540. if (forceDisposeEffect && this._effect) {
  25541. this._scene.getEngine()._releaseEffect(this._effect);
  25542. this._effect = null;
  25543. }
  25544. // Remove from meshes
  25545. for (index = 0; index < this._scene.meshes.length; index++) {
  25546. var mesh = this._scene.meshes[index];
  25547. if (mesh.material === this) {
  25548. mesh.material = null;
  25549. }
  25550. }
  25551. // Callback
  25552. this.onDisposeObservable.notifyObservers(this);
  25553. this.onDisposeObservable.clear();
  25554. this.onBindObservable.clear();
  25555. this.onUnBindObservable.clear();
  25556. };
  25557. Material.prototype.serialize = function () {
  25558. return BABYLON.SerializationHelper.Serialize(this);
  25559. };
  25560. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25561. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25562. multiMaterial.id = parsedMultiMaterial.id;
  25563. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25564. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25565. var subMatId = parsedMultiMaterial.materials[matIndex];
  25566. if (subMatId) {
  25567. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25568. }
  25569. else {
  25570. multiMaterial.subMaterials.push(null);
  25571. }
  25572. }
  25573. return multiMaterial;
  25574. };
  25575. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25576. if (!parsedMaterial.customType) {
  25577. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25578. }
  25579. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25580. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25581. ;
  25582. };
  25583. Material._TriangleFillMode = 0;
  25584. Material._WireFrameFillMode = 1;
  25585. Material._PointFillMode = 2;
  25586. Material._ClockWiseSideOrientation = 0;
  25587. Material._CounterClockWiseSideOrientation = 1;
  25588. __decorate([
  25589. BABYLON.serialize()
  25590. ], Material.prototype, "id", void 0);
  25591. __decorate([
  25592. BABYLON.serialize()
  25593. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25594. __decorate([
  25595. BABYLON.serialize()
  25596. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25597. __decorate([
  25598. BABYLON.serialize()
  25599. ], Material.prototype, "state", void 0);
  25600. __decorate([
  25601. BABYLON.serialize()
  25602. ], Material.prototype, "alpha", void 0);
  25603. __decorate([
  25604. BABYLON.serialize()
  25605. ], Material.prototype, "backFaceCulling", void 0);
  25606. __decorate([
  25607. BABYLON.serialize()
  25608. ], Material.prototype, "sideOrientation", void 0);
  25609. __decorate([
  25610. BABYLON.serialize()
  25611. ], Material.prototype, "alphaMode", void 0);
  25612. __decorate([
  25613. BABYLON.serialize()
  25614. ], Material.prototype, "disableDepthWrite", void 0);
  25615. __decorate([
  25616. BABYLON.serialize()
  25617. ], Material.prototype, "fogEnabled", void 0);
  25618. __decorate([
  25619. BABYLON.serialize()
  25620. ], Material.prototype, "pointSize", void 0);
  25621. __decorate([
  25622. BABYLON.serialize()
  25623. ], Material.prototype, "zOffset", void 0);
  25624. __decorate([
  25625. BABYLON.serialize()
  25626. ], Material.prototype, "wireframe", null);
  25627. __decorate([
  25628. BABYLON.serialize()
  25629. ], Material.prototype, "pointsCloud", null);
  25630. __decorate([
  25631. BABYLON.serialize()
  25632. ], Material.prototype, "fillMode", null);
  25633. return Material;
  25634. }());
  25635. BABYLON.Material = Material;
  25636. })(BABYLON || (BABYLON = {}));
  25637. var BABYLON;
  25638. (function (BABYLON) {
  25639. var StandardMaterialDefines = (function (_super) {
  25640. __extends(StandardMaterialDefines, _super);
  25641. function StandardMaterialDefines() {
  25642. _super.call(this);
  25643. this.DIFFUSE = false;
  25644. this.AMBIENT = false;
  25645. this.OPACITY = false;
  25646. this.OPACITYRGB = false;
  25647. this.REFLECTION = false;
  25648. this.EMISSIVE = false;
  25649. this.SPECULAR = false;
  25650. this.BUMP = false;
  25651. this.PARALLAX = false;
  25652. this.PARALLAXOCCLUSION = false;
  25653. this.SPECULAROVERALPHA = false;
  25654. this.CLIPPLANE = false;
  25655. this.ALPHATEST = false;
  25656. this.ALPHAFROMDIFFUSE = false;
  25657. this.POINTSIZE = false;
  25658. this.FOG = false;
  25659. this.SPECULARTERM = false;
  25660. this.DIFFUSEFRESNEL = false;
  25661. this.OPACITYFRESNEL = false;
  25662. this.REFLECTIONFRESNEL = false;
  25663. this.REFRACTIONFRESNEL = false;
  25664. this.EMISSIVEFRESNEL = false;
  25665. this.FRESNEL = false;
  25666. this.NORMAL = false;
  25667. this.UV1 = false;
  25668. this.UV2 = false;
  25669. this.VERTEXCOLOR = false;
  25670. this.VERTEXALPHA = false;
  25671. this.NUM_BONE_INFLUENCERS = 0;
  25672. this.BonesPerMesh = 0;
  25673. this.INSTANCES = false;
  25674. this.GLOSSINESS = false;
  25675. this.ROUGHNESS = false;
  25676. this.EMISSIVEASILLUMINATION = false;
  25677. this.LINKEMISSIVEWITHDIFFUSE = false;
  25678. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25679. this.LIGHTMAP = false;
  25680. this.USELIGHTMAPASSHADOWMAP = false;
  25681. this.REFLECTIONMAP_3D = false;
  25682. this.REFLECTIONMAP_SPHERICAL = false;
  25683. this.REFLECTIONMAP_PLANAR = false;
  25684. this.REFLECTIONMAP_CUBIC = false;
  25685. this.REFLECTIONMAP_PROJECTION = false;
  25686. this.REFLECTIONMAP_SKYBOX = false;
  25687. this.REFLECTIONMAP_EXPLICIT = false;
  25688. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25689. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25690. this.INVERTCUBICMAP = false;
  25691. this.LOGARITHMICDEPTH = false;
  25692. this.REFRACTION = false;
  25693. this.REFRACTIONMAP_3D = false;
  25694. this.REFLECTIONOVERALPHA = false;
  25695. this.INVERTNORMALMAPX = false;
  25696. this.INVERTNORMALMAPY = false;
  25697. this.SHADOWFULLFLOAT = false;
  25698. this.CAMERACOLORGRADING = false;
  25699. this.CAMERACOLORCURVES = false;
  25700. this.rebuild();
  25701. }
  25702. return StandardMaterialDefines;
  25703. }(BABYLON.MaterialDefines));
  25704. var StandardMaterial = (function (_super) {
  25705. __extends(StandardMaterial, _super);
  25706. function StandardMaterial(name, scene) {
  25707. var _this = this;
  25708. _super.call(this, name, scene);
  25709. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25710. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25711. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25712. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25713. this.specularPower = 64;
  25714. this.useAlphaFromDiffuseTexture = false;
  25715. this.useEmissiveAsIllumination = false;
  25716. this.linkEmissiveWithDiffuse = false;
  25717. this.useReflectionFresnelFromSpecular = false;
  25718. this.useSpecularOverAlpha = false;
  25719. this.useReflectionOverAlpha = false;
  25720. this.disableLighting = false;
  25721. this.useParallax = false;
  25722. this.useParallaxOcclusion = false;
  25723. this.parallaxScaleBias = 0.05;
  25724. this.roughness = 0;
  25725. this.indexOfRefraction = 0.98;
  25726. this.invertRefractionY = true;
  25727. this.useLightmapAsShadowmap = false;
  25728. this.useGlossinessFromSpecularMapAlpha = false;
  25729. this.maxSimultaneousLights = 4;
  25730. /**
  25731. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25732. */
  25733. this.invertNormalMapX = false;
  25734. /**
  25735. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25736. */
  25737. this.invertNormalMapY = false;
  25738. /**
  25739. * Color Grading 2D Lookup Texture.
  25740. * This allows special effects like sepia, black and white to sixties rendering style.
  25741. */
  25742. this.cameraColorGradingTexture = null;
  25743. /**
  25744. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25745. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25746. * 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;
  25747. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25748. */
  25749. this.cameraColorCurves = null;
  25750. this._renderTargets = new BABYLON.SmartArray(16);
  25751. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25752. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25753. this._defines = new StandardMaterialDefines();
  25754. this._cachedDefines = new StandardMaterialDefines();
  25755. this._cachedDefines.BonesPerMesh = -1;
  25756. this.getRenderTargetTextures = function () {
  25757. _this._renderTargets.reset();
  25758. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25759. _this._renderTargets.push(_this.reflectionTexture);
  25760. }
  25761. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25762. _this._renderTargets.push(_this.refractionTexture);
  25763. }
  25764. return _this._renderTargets;
  25765. };
  25766. }
  25767. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25768. get: function () {
  25769. return this._useLogarithmicDepth;
  25770. },
  25771. set: function (value) {
  25772. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25773. },
  25774. enumerable: true,
  25775. configurable: true
  25776. });
  25777. StandardMaterial.prototype.needAlphaBlending = function () {
  25778. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25779. };
  25780. StandardMaterial.prototype.needAlphaTesting = function () {
  25781. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25782. };
  25783. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25784. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25785. };
  25786. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25787. return this.diffuseTexture;
  25788. };
  25789. // Methods
  25790. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25791. if (!mesh) {
  25792. return true;
  25793. }
  25794. if (this._defines.INSTANCES !== useInstances) {
  25795. return false;
  25796. }
  25797. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25798. return true;
  25799. }
  25800. return false;
  25801. };
  25802. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25803. if (this.isFrozen) {
  25804. if (this._wasPreviouslyReady) {
  25805. return true;
  25806. }
  25807. }
  25808. var scene = this.getScene();
  25809. if (!this.checkReadyOnEveryCall) {
  25810. if (this._renderId === scene.getRenderId()) {
  25811. if (this._checkCache(scene, mesh, useInstances)) {
  25812. return true;
  25813. }
  25814. }
  25815. }
  25816. var engine = scene.getEngine();
  25817. var needNormals = false;
  25818. var needUVs = false;
  25819. this._defines.reset();
  25820. // Textures
  25821. if (scene.texturesEnabled) {
  25822. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25823. if (!this.diffuseTexture.isReady()) {
  25824. return false;
  25825. }
  25826. else {
  25827. needUVs = true;
  25828. this._defines.DIFFUSE = true;
  25829. }
  25830. }
  25831. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25832. if (!this.ambientTexture.isReady()) {
  25833. return false;
  25834. }
  25835. else {
  25836. needUVs = true;
  25837. this._defines.AMBIENT = true;
  25838. }
  25839. }
  25840. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25841. if (!this.opacityTexture.isReady()) {
  25842. return false;
  25843. }
  25844. else {
  25845. needUVs = true;
  25846. this._defines.OPACITY = true;
  25847. if (this.opacityTexture.getAlphaFromRGB) {
  25848. this._defines.OPACITYRGB = true;
  25849. }
  25850. }
  25851. }
  25852. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25853. if (!this.reflectionTexture.isReady()) {
  25854. return false;
  25855. }
  25856. else {
  25857. needNormals = true;
  25858. this._defines.REFLECTION = true;
  25859. if (this.roughness > 0) {
  25860. this._defines.ROUGHNESS = true;
  25861. }
  25862. if (this.useReflectionOverAlpha) {
  25863. this._defines.REFLECTIONOVERALPHA = true;
  25864. }
  25865. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25866. this._defines.INVERTCUBICMAP = true;
  25867. }
  25868. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25869. switch (this.reflectionTexture.coordinatesMode) {
  25870. case BABYLON.Texture.CUBIC_MODE:
  25871. case BABYLON.Texture.INVCUBIC_MODE:
  25872. this._defines.REFLECTIONMAP_CUBIC = true;
  25873. break;
  25874. case BABYLON.Texture.EXPLICIT_MODE:
  25875. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25876. break;
  25877. case BABYLON.Texture.PLANAR_MODE:
  25878. this._defines.REFLECTIONMAP_PLANAR = true;
  25879. break;
  25880. case BABYLON.Texture.PROJECTION_MODE:
  25881. this._defines.REFLECTIONMAP_PROJECTION = true;
  25882. break;
  25883. case BABYLON.Texture.SKYBOX_MODE:
  25884. this._defines.REFLECTIONMAP_SKYBOX = true;
  25885. break;
  25886. case BABYLON.Texture.SPHERICAL_MODE:
  25887. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25888. break;
  25889. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25890. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25891. break;
  25892. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25893. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25894. break;
  25895. }
  25896. }
  25897. }
  25898. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25899. if (!this.emissiveTexture.isReady()) {
  25900. return false;
  25901. }
  25902. else {
  25903. needUVs = true;
  25904. this._defines.EMISSIVE = true;
  25905. }
  25906. }
  25907. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25908. if (!this.lightmapTexture.isReady()) {
  25909. return false;
  25910. }
  25911. else {
  25912. needUVs = true;
  25913. this._defines.LIGHTMAP = true;
  25914. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25915. }
  25916. }
  25917. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25918. if (!this.specularTexture.isReady()) {
  25919. return false;
  25920. }
  25921. else {
  25922. needUVs = true;
  25923. this._defines.SPECULAR = true;
  25924. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25925. }
  25926. }
  25927. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25928. if (!this.bumpTexture.isReady()) {
  25929. return false;
  25930. }
  25931. else {
  25932. needUVs = true;
  25933. this._defines.BUMP = true;
  25934. if (this.useParallax) {
  25935. this._defines.PARALLAX = true;
  25936. if (this.useParallaxOcclusion) {
  25937. this._defines.PARALLAXOCCLUSION = true;
  25938. }
  25939. }
  25940. if (this.invertNormalMapX) {
  25941. this._defines.INVERTNORMALMAPX = true;
  25942. }
  25943. if (this.invertNormalMapY) {
  25944. this._defines.INVERTNORMALMAPY = true;
  25945. }
  25946. }
  25947. }
  25948. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25949. if (!this.refractionTexture.isReady()) {
  25950. return false;
  25951. }
  25952. else {
  25953. needUVs = true;
  25954. this._defines.REFRACTION = true;
  25955. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25956. }
  25957. }
  25958. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25959. if (!this.cameraColorGradingTexture.isReady()) {
  25960. return false;
  25961. }
  25962. else {
  25963. this._defines.CAMERACOLORGRADING = true;
  25964. }
  25965. }
  25966. }
  25967. // Effect
  25968. if (scene.clipPlane) {
  25969. this._defines.CLIPPLANE = true;
  25970. }
  25971. if (engine.getAlphaTesting()) {
  25972. this._defines.ALPHATEST = true;
  25973. }
  25974. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25975. this._defines.ALPHAFROMDIFFUSE = true;
  25976. }
  25977. if (this.useEmissiveAsIllumination) {
  25978. this._defines.EMISSIVEASILLUMINATION = true;
  25979. }
  25980. if (this.linkEmissiveWithDiffuse) {
  25981. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25982. }
  25983. if (this.useLogarithmicDepth) {
  25984. this._defines.LOGARITHMICDEPTH = true;
  25985. }
  25986. if (this.cameraColorCurves) {
  25987. this._defines.CAMERACOLORCURVES = true;
  25988. }
  25989. // Point size
  25990. if (this.pointsCloud || scene.forcePointsCloud) {
  25991. this._defines.POINTSIZE = true;
  25992. }
  25993. // Fog
  25994. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25995. this._defines.FOG = true;
  25996. }
  25997. if (scene.lightsEnabled && !this.disableLighting) {
  25998. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25999. }
  26000. if (StandardMaterial.FresnelEnabled) {
  26001. // Fresnel
  26002. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26003. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26004. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26005. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26006. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26007. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26008. this._defines.DIFFUSEFRESNEL = true;
  26009. }
  26010. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26011. this._defines.OPACITYFRESNEL = true;
  26012. }
  26013. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26014. this._defines.REFLECTIONFRESNEL = true;
  26015. if (this.useReflectionFresnelFromSpecular) {
  26016. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26017. }
  26018. }
  26019. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26020. this._defines.REFRACTIONFRESNEL = true;
  26021. }
  26022. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26023. this._defines.EMISSIVEFRESNEL = true;
  26024. }
  26025. needNormals = true;
  26026. this._defines.FRESNEL = true;
  26027. }
  26028. }
  26029. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26030. this._defines.SPECULAROVERALPHA = true;
  26031. }
  26032. // Attribs
  26033. if (mesh) {
  26034. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26035. this._defines.NORMAL = true;
  26036. }
  26037. if (needUVs) {
  26038. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26039. this._defines.UV1 = true;
  26040. }
  26041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26042. this._defines.UV2 = true;
  26043. }
  26044. }
  26045. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26046. this._defines.VERTEXCOLOR = true;
  26047. if (mesh.hasVertexAlpha) {
  26048. this._defines.VERTEXALPHA = true;
  26049. }
  26050. }
  26051. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26052. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26053. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26054. }
  26055. // Instances
  26056. if (useInstances) {
  26057. this._defines.INSTANCES = true;
  26058. }
  26059. }
  26060. // Get correct effect
  26061. if (!this._defines.isEqual(this._cachedDefines)) {
  26062. this._defines.cloneTo(this._cachedDefines);
  26063. scene.resetCachedMaterial();
  26064. // Fallbacks
  26065. var fallbacks = new BABYLON.EffectFallbacks();
  26066. if (this._defines.REFLECTION) {
  26067. fallbacks.addFallback(0, "REFLECTION");
  26068. }
  26069. if (this._defines.SPECULAR) {
  26070. fallbacks.addFallback(0, "SPECULAR");
  26071. }
  26072. if (this._defines.BUMP) {
  26073. fallbacks.addFallback(0, "BUMP");
  26074. }
  26075. if (this._defines.PARALLAX) {
  26076. fallbacks.addFallback(1, "PARALLAX");
  26077. }
  26078. if (this._defines.PARALLAXOCCLUSION) {
  26079. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26080. }
  26081. if (this._defines.SPECULAROVERALPHA) {
  26082. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26083. }
  26084. if (this._defines.FOG) {
  26085. fallbacks.addFallback(1, "FOG");
  26086. }
  26087. if (this._defines.POINTSIZE) {
  26088. fallbacks.addFallback(0, "POINTSIZE");
  26089. }
  26090. if (this._defines.LOGARITHMICDEPTH) {
  26091. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26092. }
  26093. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26094. if (this._defines.SPECULARTERM) {
  26095. fallbacks.addFallback(0, "SPECULARTERM");
  26096. }
  26097. if (this._defines.DIFFUSEFRESNEL) {
  26098. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26099. }
  26100. if (this._defines.OPACITYFRESNEL) {
  26101. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26102. }
  26103. if (this._defines.REFLECTIONFRESNEL) {
  26104. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26105. }
  26106. if (this._defines.EMISSIVEFRESNEL) {
  26107. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26108. }
  26109. if (this._defines.FRESNEL) {
  26110. fallbacks.addFallback(4, "FRESNEL");
  26111. }
  26112. //Attributes
  26113. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26114. if (this._defines.NORMAL) {
  26115. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26116. }
  26117. if (this._defines.UV1) {
  26118. attribs.push(BABYLON.VertexBuffer.UVKind);
  26119. }
  26120. if (this._defines.UV2) {
  26121. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26122. }
  26123. if (this._defines.VERTEXCOLOR) {
  26124. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26125. }
  26126. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26127. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26128. var shaderName = "default";
  26129. var join = this._defines.toString();
  26130. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26131. "vFogInfos", "vFogColor", "pointSize",
  26132. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26133. "mBones",
  26134. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26135. "depthValues",
  26136. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26137. "logarithmicDepthConstant"
  26138. ];
  26139. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26140. if (this._defines.CAMERACOLORCURVES) {
  26141. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26142. }
  26143. if (this._defines.CAMERACOLORGRADING) {
  26144. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26145. }
  26146. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26147. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26148. }
  26149. if (!this._effect.isReady()) {
  26150. return false;
  26151. }
  26152. this._renderId = scene.getRenderId();
  26153. this._wasPreviouslyReady = true;
  26154. if (mesh) {
  26155. if (!mesh._materialDefines) {
  26156. mesh._materialDefines = new StandardMaterialDefines();
  26157. }
  26158. this._defines.cloneTo(mesh._materialDefines);
  26159. }
  26160. return true;
  26161. };
  26162. StandardMaterial.prototype.unbind = function () {
  26163. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26164. this._effect.setTexture("reflection2DSampler", null);
  26165. }
  26166. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26167. this._effect.setTexture("refraction2DSampler", null);
  26168. }
  26169. _super.prototype.unbind.call(this);
  26170. };
  26171. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26172. this._effect.setMatrix("world", world);
  26173. };
  26174. StandardMaterial.prototype.bind = function (world, mesh) {
  26175. var scene = this.getScene();
  26176. // Matrices
  26177. this.bindOnlyWorldMatrix(world);
  26178. // Bones
  26179. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26180. if (scene.getCachedMaterial() !== this) {
  26181. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26182. if (StandardMaterial.FresnelEnabled) {
  26183. // Fresnel
  26184. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26185. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26186. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26187. }
  26188. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26189. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26190. }
  26191. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26192. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26193. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26194. }
  26195. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26196. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26197. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26198. }
  26199. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26200. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26201. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26202. }
  26203. }
  26204. // Textures
  26205. if (scene.texturesEnabled) {
  26206. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26207. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26208. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26209. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26210. }
  26211. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26212. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26213. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26214. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26215. }
  26216. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26217. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26218. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26219. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26220. }
  26221. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26222. if (this.reflectionTexture.isCube) {
  26223. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26224. }
  26225. else {
  26226. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26227. }
  26228. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26229. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26230. }
  26231. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26232. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26233. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26234. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26235. }
  26236. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26237. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26238. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26239. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26240. }
  26241. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26242. this._effect.setTexture("specularSampler", this.specularTexture);
  26243. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26244. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26245. }
  26246. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26247. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26248. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26249. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26250. }
  26251. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26252. var depth = 1.0;
  26253. if (this.refractionTexture.isCube) {
  26254. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26255. }
  26256. else {
  26257. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26258. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26259. if (this.refractionTexture.depth) {
  26260. depth = this.refractionTexture.depth;
  26261. }
  26262. }
  26263. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26264. }
  26265. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26266. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26267. }
  26268. }
  26269. // Clip plane
  26270. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26271. // Point size
  26272. if (this.pointsCloud) {
  26273. this._effect.setFloat("pointSize", this.pointSize);
  26274. }
  26275. // Colors
  26276. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26277. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26278. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26279. if (this._defines.SPECULARTERM) {
  26280. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26281. }
  26282. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26283. }
  26284. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26285. // Diffuse
  26286. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26287. // Lights
  26288. if (scene.lightsEnabled && !this.disableLighting) {
  26289. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26290. }
  26291. // View
  26292. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26293. this._effect.setMatrix("view", scene.getViewMatrix());
  26294. }
  26295. // Fog
  26296. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26297. // Log. depth
  26298. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26299. // Color Curves
  26300. if (this.cameraColorCurves) {
  26301. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26302. }
  26303. }
  26304. _super.prototype.bind.call(this, world, mesh);
  26305. };
  26306. StandardMaterial.prototype.getAnimatables = function () {
  26307. var results = [];
  26308. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26309. results.push(this.diffuseTexture);
  26310. }
  26311. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26312. results.push(this.ambientTexture);
  26313. }
  26314. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26315. results.push(this.opacityTexture);
  26316. }
  26317. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26318. results.push(this.reflectionTexture);
  26319. }
  26320. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26321. results.push(this.emissiveTexture);
  26322. }
  26323. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26324. results.push(this.specularTexture);
  26325. }
  26326. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26327. results.push(this.bumpTexture);
  26328. }
  26329. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26330. results.push(this.lightmapTexture);
  26331. }
  26332. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26333. results.push(this.refractionTexture);
  26334. }
  26335. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26336. results.push(this.cameraColorGradingTexture);
  26337. }
  26338. return results;
  26339. };
  26340. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26341. if (forceDisposeTextures) {
  26342. if (this.diffuseTexture) {
  26343. this.diffuseTexture.dispose();
  26344. }
  26345. if (this.ambientTexture) {
  26346. this.ambientTexture.dispose();
  26347. }
  26348. if (this.opacityTexture) {
  26349. this.opacityTexture.dispose();
  26350. }
  26351. if (this.reflectionTexture) {
  26352. this.reflectionTexture.dispose();
  26353. }
  26354. if (this.emissiveTexture) {
  26355. this.emissiveTexture.dispose();
  26356. }
  26357. if (this.specularTexture) {
  26358. this.specularTexture.dispose();
  26359. }
  26360. if (this.bumpTexture) {
  26361. this.bumpTexture.dispose();
  26362. }
  26363. if (this.lightmapTexture) {
  26364. this.lightmapTexture.dispose();
  26365. }
  26366. if (this.refractionTexture) {
  26367. this.refractionTexture.dispose();
  26368. }
  26369. if (this.cameraColorGradingTexture) {
  26370. this.cameraColorGradingTexture.dispose();
  26371. }
  26372. }
  26373. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26374. };
  26375. StandardMaterial.prototype.clone = function (name) {
  26376. var _this = this;
  26377. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26378. };
  26379. StandardMaterial.prototype.serialize = function () {
  26380. return BABYLON.SerializationHelper.Serialize(this);
  26381. };
  26382. // Statics
  26383. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26384. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26385. };
  26386. // Flags used to enable or disable a type of texture for all Standard Materials
  26387. StandardMaterial.DiffuseTextureEnabled = true;
  26388. StandardMaterial.AmbientTextureEnabled = true;
  26389. StandardMaterial.OpacityTextureEnabled = true;
  26390. StandardMaterial.ReflectionTextureEnabled = true;
  26391. StandardMaterial.EmissiveTextureEnabled = true;
  26392. StandardMaterial.SpecularTextureEnabled = true;
  26393. StandardMaterial.BumpTextureEnabled = true;
  26394. StandardMaterial.FresnelEnabled = true;
  26395. StandardMaterial.LightmapTextureEnabled = true;
  26396. StandardMaterial.RefractionTextureEnabled = true;
  26397. StandardMaterial.ColorGradingTextureEnabled = true;
  26398. __decorate([
  26399. BABYLON.serializeAsTexture()
  26400. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26401. __decorate([
  26402. BABYLON.serializeAsTexture()
  26403. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26404. __decorate([
  26405. BABYLON.serializeAsTexture()
  26406. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26407. __decorate([
  26408. BABYLON.serializeAsTexture()
  26409. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26410. __decorate([
  26411. BABYLON.serializeAsTexture()
  26412. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26413. __decorate([
  26414. BABYLON.serializeAsTexture()
  26415. ], StandardMaterial.prototype, "specularTexture", void 0);
  26416. __decorate([
  26417. BABYLON.serializeAsTexture()
  26418. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26419. __decorate([
  26420. BABYLON.serializeAsTexture()
  26421. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26422. __decorate([
  26423. BABYLON.serializeAsTexture()
  26424. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26425. __decorate([
  26426. BABYLON.serializeAsColor3("ambient")
  26427. ], StandardMaterial.prototype, "ambientColor", void 0);
  26428. __decorate([
  26429. BABYLON.serializeAsColor3("diffuse")
  26430. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26431. __decorate([
  26432. BABYLON.serializeAsColor3("specular")
  26433. ], StandardMaterial.prototype, "specularColor", void 0);
  26434. __decorate([
  26435. BABYLON.serializeAsColor3("emissive")
  26436. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26437. __decorate([
  26438. BABYLON.serialize()
  26439. ], StandardMaterial.prototype, "specularPower", void 0);
  26440. __decorate([
  26441. BABYLON.serialize()
  26442. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26443. __decorate([
  26444. BABYLON.serialize()
  26445. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26446. __decorate([
  26447. BABYLON.serialize()
  26448. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26449. __decorate([
  26450. BABYLON.serialize()
  26451. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26452. __decorate([
  26453. BABYLON.serialize()
  26454. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26455. __decorate([
  26456. BABYLON.serialize()
  26457. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26458. __decorate([
  26459. BABYLON.serialize()
  26460. ], StandardMaterial.prototype, "disableLighting", void 0);
  26461. __decorate([
  26462. BABYLON.serialize()
  26463. ], StandardMaterial.prototype, "useParallax", void 0);
  26464. __decorate([
  26465. BABYLON.serialize()
  26466. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26467. __decorate([
  26468. BABYLON.serialize()
  26469. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26470. __decorate([
  26471. BABYLON.serialize()
  26472. ], StandardMaterial.prototype, "roughness", void 0);
  26473. __decorate([
  26474. BABYLON.serialize()
  26475. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26476. __decorate([
  26477. BABYLON.serialize()
  26478. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26479. __decorate([
  26480. BABYLON.serialize()
  26481. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26482. __decorate([
  26483. BABYLON.serializeAsFresnelParameters()
  26484. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26485. __decorate([
  26486. BABYLON.serializeAsFresnelParameters()
  26487. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26488. __decorate([
  26489. BABYLON.serializeAsFresnelParameters()
  26490. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26491. __decorate([
  26492. BABYLON.serializeAsFresnelParameters()
  26493. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26494. __decorate([
  26495. BABYLON.serializeAsFresnelParameters()
  26496. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26497. __decorate([
  26498. BABYLON.serialize()
  26499. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26500. __decorate([
  26501. BABYLON.serialize()
  26502. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26503. __decorate([
  26504. BABYLON.serialize()
  26505. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26506. __decorate([
  26507. BABYLON.serialize()
  26508. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26509. __decorate([
  26510. BABYLON.serializeAsTexture()
  26511. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26512. __decorate([
  26513. BABYLON.serializeAsColorCurves()
  26514. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26515. __decorate([
  26516. BABYLON.serialize()
  26517. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26518. return StandardMaterial;
  26519. }(BABYLON.Material));
  26520. BABYLON.StandardMaterial = StandardMaterial;
  26521. })(BABYLON || (BABYLON = {}));
  26522. var BABYLON;
  26523. (function (BABYLON) {
  26524. var MultiMaterial = (function (_super) {
  26525. __extends(MultiMaterial, _super);
  26526. function MultiMaterial(name, scene) {
  26527. _super.call(this, name, scene, true);
  26528. this.subMaterials = new Array();
  26529. scene.multiMaterials.push(this);
  26530. }
  26531. // Properties
  26532. MultiMaterial.prototype.getSubMaterial = function (index) {
  26533. if (index < 0 || index >= this.subMaterials.length) {
  26534. return this.getScene().defaultMaterial;
  26535. }
  26536. return this.subMaterials[index];
  26537. };
  26538. // Methods
  26539. MultiMaterial.prototype.isReady = function (mesh) {
  26540. for (var index = 0; index < this.subMaterials.length; index++) {
  26541. var subMaterial = this.subMaterials[index];
  26542. if (subMaterial) {
  26543. if (!this.subMaterials[index].isReady(mesh)) {
  26544. return false;
  26545. }
  26546. }
  26547. }
  26548. return true;
  26549. };
  26550. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26551. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26552. for (var index = 0; index < this.subMaterials.length; index++) {
  26553. var subMaterial = null;
  26554. if (cloneChildren) {
  26555. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26556. }
  26557. else {
  26558. subMaterial = this.subMaterials[index];
  26559. }
  26560. newMultiMaterial.subMaterials.push(subMaterial);
  26561. }
  26562. return newMultiMaterial;
  26563. };
  26564. MultiMaterial.prototype.serialize = function () {
  26565. var serializationObject = {};
  26566. serializationObject.name = this.name;
  26567. serializationObject.id = this.id;
  26568. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26569. serializationObject.materials = [];
  26570. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26571. var subMat = this.subMaterials[matIndex];
  26572. if (subMat) {
  26573. serializationObject.materials.push(subMat.id);
  26574. }
  26575. else {
  26576. serializationObject.materials.push(null);
  26577. }
  26578. }
  26579. return serializationObject;
  26580. };
  26581. return MultiMaterial;
  26582. }(BABYLON.Material));
  26583. BABYLON.MultiMaterial = MultiMaterial;
  26584. })(BABYLON || (BABYLON = {}));
  26585. var BABYLON;
  26586. (function (BABYLON) {
  26587. var SceneLoader = (function () {
  26588. function SceneLoader() {
  26589. }
  26590. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26591. get: function () {
  26592. return 0;
  26593. },
  26594. enumerable: true,
  26595. configurable: true
  26596. });
  26597. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26598. get: function () {
  26599. return 1;
  26600. },
  26601. enumerable: true,
  26602. configurable: true
  26603. });
  26604. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26605. get: function () {
  26606. return 2;
  26607. },
  26608. enumerable: true,
  26609. configurable: true
  26610. });
  26611. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26612. get: function () {
  26613. return 3;
  26614. },
  26615. enumerable: true,
  26616. configurable: true
  26617. });
  26618. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26619. get: function () {
  26620. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26621. },
  26622. set: function (value) {
  26623. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26624. },
  26625. enumerable: true,
  26626. configurable: true
  26627. });
  26628. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26629. get: function () {
  26630. return SceneLoader._ShowLoadingScreen;
  26631. },
  26632. set: function (value) {
  26633. SceneLoader._ShowLoadingScreen = value;
  26634. },
  26635. enumerable: true,
  26636. configurable: true
  26637. });
  26638. Object.defineProperty(SceneLoader, "loggingLevel", {
  26639. get: function () {
  26640. return SceneLoader._loggingLevel;
  26641. },
  26642. set: function (value) {
  26643. SceneLoader._loggingLevel = value;
  26644. },
  26645. enumerable: true,
  26646. configurable: true
  26647. });
  26648. SceneLoader._getDefaultPlugin = function () {
  26649. return SceneLoader._registeredPlugins[".babylon"];
  26650. };
  26651. SceneLoader._getPluginForExtension = function (extension) {
  26652. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26653. if (registeredPlugin) {
  26654. return registeredPlugin;
  26655. }
  26656. return SceneLoader._getDefaultPlugin();
  26657. };
  26658. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26659. if (sceneFilename.name) {
  26660. sceneFilename = sceneFilename.name;
  26661. }
  26662. var dotPosition = sceneFilename.lastIndexOf(".");
  26663. var queryStringPosition = sceneFilename.indexOf("?");
  26664. if (queryStringPosition === -1) {
  26665. queryStringPosition = sceneFilename.length;
  26666. }
  26667. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26668. return SceneLoader._getPluginForExtension(extension);
  26669. };
  26670. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26671. SceneLoader._getDirectLoad = function (sceneFilename) {
  26672. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26673. return sceneFilename.substr(5);
  26674. }
  26675. return null;
  26676. };
  26677. // Public functions
  26678. SceneLoader.GetPluginForExtension = function (extension) {
  26679. return SceneLoader._getPluginForExtension(extension).plugin;
  26680. };
  26681. SceneLoader.RegisterPlugin = function (plugin) {
  26682. if (typeof plugin.extensions === "string") {
  26683. var extension = plugin.extensions;
  26684. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26685. plugin: plugin,
  26686. isBinary: false
  26687. };
  26688. }
  26689. else {
  26690. var extensions = plugin.extensions;
  26691. Object.keys(extensions).forEach(function (extension) {
  26692. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26693. plugin: plugin,
  26694. isBinary: extensions[extension].isBinary
  26695. };
  26696. });
  26697. }
  26698. };
  26699. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26700. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26701. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26702. return;
  26703. }
  26704. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26705. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26706. return;
  26707. }
  26708. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26709. var loadingToken = {};
  26710. scene._addPendingData(loadingToken);
  26711. var manifestChecked = function (success) {
  26712. scene.database = database;
  26713. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26714. var plugin = registeredPlugin.plugin;
  26715. var useArrayBuffer = registeredPlugin.isBinary;
  26716. var importMeshFromData = function (data) {
  26717. var meshes = [];
  26718. var particleSystems = [];
  26719. var skeletons = [];
  26720. try {
  26721. if (plugin.importMesh) {
  26722. var syncedPlugin = plugin;
  26723. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26724. if (onerror) {
  26725. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26726. }
  26727. scene._removePendingData(loadingToken);
  26728. return;
  26729. }
  26730. if (onsuccess) {
  26731. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26732. onsuccess(meshes, particleSystems, skeletons);
  26733. scene._removePendingData(loadingToken);
  26734. }
  26735. }
  26736. else {
  26737. var asyncedPlugin = plugin;
  26738. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26739. if (onsuccess) {
  26740. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26741. onsuccess(meshes, particleSystems, skeletons);
  26742. scene._removePendingData(loadingToken);
  26743. }
  26744. }, function () {
  26745. if (onerror) {
  26746. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26747. }
  26748. scene._removePendingData(loadingToken);
  26749. });
  26750. }
  26751. }
  26752. catch (e) {
  26753. if (onerror) {
  26754. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26755. }
  26756. scene._removePendingData(loadingToken);
  26757. }
  26758. };
  26759. if (directLoad) {
  26760. importMeshFromData(directLoad);
  26761. return;
  26762. }
  26763. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26764. importMeshFromData(data);
  26765. }, progressCallBack, database, useArrayBuffer);
  26766. };
  26767. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26768. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26769. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26770. }
  26771. else {
  26772. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26773. manifestChecked(true);
  26774. }
  26775. };
  26776. /**
  26777. * Load a scene
  26778. * @param rootUrl a string that defines the root url for scene and resources
  26779. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26780. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26781. */
  26782. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26783. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26784. };
  26785. /**
  26786. * Append a scene
  26787. * @param rootUrl a string that defines the root url for scene and resources
  26788. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26789. * @param scene is the instance of BABYLON.Scene to append to
  26790. */
  26791. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26792. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26793. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26794. return;
  26795. }
  26796. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26797. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26798. var plugin = registeredPlugin.plugin;
  26799. var useArrayBuffer = registeredPlugin.isBinary;
  26800. var database;
  26801. var loadingToken = {};
  26802. scene._addPendingData(loadingToken);
  26803. if (SceneLoader.ShowLoadingScreen) {
  26804. scene.getEngine().displayLoadingUI();
  26805. }
  26806. var loadSceneFromData = function (data) {
  26807. scene.database = database;
  26808. if (plugin.load) {
  26809. var syncedPlugin = plugin;
  26810. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26811. if (onerror) {
  26812. onerror(scene);
  26813. }
  26814. scene._removePendingData(loadingToken);
  26815. scene.getEngine().hideLoadingUI();
  26816. return;
  26817. }
  26818. if (onsuccess) {
  26819. onsuccess(scene);
  26820. }
  26821. scene._removePendingData(loadingToken);
  26822. }
  26823. else {
  26824. var asyncedPlugin = plugin;
  26825. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26826. if (onsuccess) {
  26827. onsuccess(scene);
  26828. }
  26829. scene._removePendingData(loadingToken);
  26830. }, function () {
  26831. if (onerror) {
  26832. onerror(scene);
  26833. }
  26834. scene._removePendingData(loadingToken);
  26835. scene.getEngine().hideLoadingUI();
  26836. });
  26837. }
  26838. if (SceneLoader.ShowLoadingScreen) {
  26839. scene.executeWhenReady(function () {
  26840. scene.getEngine().hideLoadingUI();
  26841. });
  26842. }
  26843. };
  26844. var manifestChecked = function (success) {
  26845. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26846. };
  26847. if (directLoad) {
  26848. loadSceneFromData(directLoad);
  26849. return;
  26850. }
  26851. if (rootUrl.indexOf("file:") === -1) {
  26852. if (scene.getEngine().enableOfflineSupport) {
  26853. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26854. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26855. }
  26856. else {
  26857. manifestChecked(true);
  26858. }
  26859. }
  26860. else {
  26861. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26862. }
  26863. };
  26864. // Flags
  26865. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26866. SceneLoader._ShowLoadingScreen = true;
  26867. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26868. // Members
  26869. SceneLoader._registeredPlugins = {};
  26870. return SceneLoader;
  26871. }());
  26872. BABYLON.SceneLoader = SceneLoader;
  26873. ;
  26874. })(BABYLON || (BABYLON = {}));
  26875. var BABYLON;
  26876. (function (BABYLON) {
  26877. var Internals;
  26878. (function (Internals) {
  26879. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26880. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26881. var parsedMaterial = parsedData.materials[index];
  26882. if (parsedMaterial.id === id) {
  26883. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26884. }
  26885. }
  26886. return null;
  26887. };
  26888. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26889. names = (names instanceof Array) ? names : [names];
  26890. for (var i in names) {
  26891. if (mesh.name === names[i]) {
  26892. hierarchyIds.push(mesh.id);
  26893. return true;
  26894. }
  26895. }
  26896. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26897. hierarchyIds.push(mesh.id);
  26898. return true;
  26899. }
  26900. return false;
  26901. };
  26902. var logOperation = function (operation, producer) {
  26903. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26904. };
  26905. BABYLON.SceneLoader.RegisterPlugin({
  26906. extensions: ".babylon",
  26907. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26908. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26909. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26910. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26911. // and avoid problems with multiple concurrent .babylon loads.
  26912. var log = "importMesh has failed JSON parse";
  26913. try {
  26914. var parsedData = JSON.parse(data);
  26915. log = "";
  26916. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26917. var loadedSkeletonsIds = [];
  26918. var loadedMaterialsIds = [];
  26919. var hierarchyIds = [];
  26920. var index;
  26921. var cache;
  26922. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26923. var parsedMesh = parsedData.meshes[index];
  26924. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26925. if (meshesNames instanceof Array) {
  26926. // Remove found mesh name from list.
  26927. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26928. }
  26929. //Geometry?
  26930. if (parsedMesh.geometryId) {
  26931. //does the file contain geometries?
  26932. if (parsedData.geometries) {
  26933. //find the correct geometry and add it to the scene
  26934. var found = false;
  26935. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26936. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26937. return;
  26938. }
  26939. else {
  26940. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26941. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26942. switch (geometryType) {
  26943. case "boxes":
  26944. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26945. break;
  26946. case "spheres":
  26947. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26948. break;
  26949. case "cylinders":
  26950. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26951. break;
  26952. case "toruses":
  26953. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26954. break;
  26955. case "grounds":
  26956. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26957. break;
  26958. case "planes":
  26959. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26960. break;
  26961. case "torusKnots":
  26962. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26963. break;
  26964. case "vertexData":
  26965. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26966. break;
  26967. }
  26968. found = true;
  26969. }
  26970. });
  26971. }
  26972. });
  26973. if (!found) {
  26974. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26975. }
  26976. }
  26977. }
  26978. // Material ?
  26979. if (parsedMesh.materialId) {
  26980. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26981. if (!materialFound && parsedData.multiMaterials) {
  26982. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26983. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26984. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26985. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26986. var subMatId = parsedMultiMaterial.materials[matIndex];
  26987. loadedMaterialsIds.push(subMatId);
  26988. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26989. log += "\n\tMaterial " + mat.toString(fullDetails);
  26990. }
  26991. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26992. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26993. materialFound = true;
  26994. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26995. break;
  26996. }
  26997. }
  26998. }
  26999. if (!materialFound) {
  27000. loadedMaterialsIds.push(parsedMesh.materialId);
  27001. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27002. if (!mat) {
  27003. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27004. }
  27005. else {
  27006. log += "\n\tMaterial " + mat.toString(fullDetails);
  27007. }
  27008. }
  27009. }
  27010. // Skeleton ?
  27011. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27012. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27013. if (!skeletonAlreadyLoaded) {
  27014. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27015. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27016. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27017. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27018. skeletons.push(skeleton);
  27019. loadedSkeletonsIds.push(parsedSkeleton.id);
  27020. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27021. }
  27022. }
  27023. }
  27024. }
  27025. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27026. meshes.push(mesh);
  27027. log += "\n\tMesh " + mesh.toString(fullDetails);
  27028. }
  27029. }
  27030. // Connecting parents
  27031. var currentMesh;
  27032. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27033. currentMesh = scene.meshes[index];
  27034. if (currentMesh._waitingParentId) {
  27035. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27036. currentMesh._waitingParentId = undefined;
  27037. }
  27038. }
  27039. // freeze and compute world matrix application
  27040. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27041. currentMesh = scene.meshes[index];
  27042. if (currentMesh._waitingFreezeWorldMatrix) {
  27043. currentMesh.freezeWorldMatrix();
  27044. currentMesh._waitingFreezeWorldMatrix = undefined;
  27045. }
  27046. else {
  27047. currentMesh.computeWorldMatrix(true);
  27048. }
  27049. }
  27050. // Particles
  27051. if (parsedData.particleSystems) {
  27052. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27053. var parsedParticleSystem = parsedData.particleSystems[index];
  27054. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27055. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27056. }
  27057. }
  27058. }
  27059. return true;
  27060. }
  27061. catch (err) {
  27062. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27063. log = null;
  27064. throw err;
  27065. }
  27066. finally {
  27067. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27068. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27069. }
  27070. }
  27071. },
  27072. load: function (scene, data, rootUrl) {
  27073. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27074. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27075. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27076. // and avoid problems with multiple concurrent .babylon loads.
  27077. var log = "importScene has failed JSON parse";
  27078. try {
  27079. var parsedData = JSON.parse(data);
  27080. log = "";
  27081. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27082. // Scene
  27083. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27084. scene.autoClear = parsedData.autoClear;
  27085. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27086. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27087. if (parsedData.gravity) {
  27088. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27089. }
  27090. // Fog
  27091. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27092. scene.fogMode = parsedData.fogMode;
  27093. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27094. scene.fogStart = parsedData.fogStart;
  27095. scene.fogEnd = parsedData.fogEnd;
  27096. scene.fogDensity = parsedData.fogDensity;
  27097. log += "\tFog mode for scene: ";
  27098. switch (scene.fogMode) {
  27099. // getters not compiling, so using hardcoded
  27100. case 1:
  27101. log += "exp\n";
  27102. break;
  27103. case 2:
  27104. log += "exp2\n";
  27105. break;
  27106. case 3:
  27107. log += "linear\n";
  27108. break;
  27109. }
  27110. }
  27111. //Physics
  27112. if (parsedData.physicsEnabled) {
  27113. var physicsPlugin;
  27114. if (parsedData.physicsEngine === "cannon") {
  27115. physicsPlugin = new BABYLON.CannonJSPlugin();
  27116. }
  27117. else if (parsedData.physicsEngine === "oimo") {
  27118. physicsPlugin = new BABYLON.OimoJSPlugin();
  27119. }
  27120. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27121. //else - default engine, which is currently oimo
  27122. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27123. scene.enablePhysics(physicsGravity, physicsPlugin);
  27124. }
  27125. //collisions, if defined. otherwise, default is true
  27126. if (parsedData.collisionsEnabled != undefined) {
  27127. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27128. }
  27129. scene.workerCollisions = !!parsedData.workerCollisions;
  27130. var index;
  27131. var cache;
  27132. // Lights
  27133. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27134. var parsedLight = parsedData.lights[index];
  27135. var light = BABYLON.Light.Parse(parsedLight, scene);
  27136. log += (index === 0 ? "\n\tLights:" : "");
  27137. log += "\n\t\t" + light.toString(fullDetails);
  27138. }
  27139. // Animations
  27140. if (parsedData.animations) {
  27141. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27142. var parsedAnimation = parsedData.animations[index];
  27143. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27144. scene.animations.push(animation);
  27145. log += (index === 0 ? "\n\tAnimations:" : "");
  27146. log += "\n\t\t" + animation.toString(fullDetails);
  27147. }
  27148. }
  27149. if (parsedData.autoAnimate) {
  27150. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27151. }
  27152. // Materials
  27153. if (parsedData.materials) {
  27154. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27155. var parsedMaterial = parsedData.materials[index];
  27156. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27157. log += (index === 0 ? "\n\tMaterials:" : "");
  27158. log += "\n\t\t" + mat.toString(fullDetails);
  27159. }
  27160. }
  27161. if (parsedData.multiMaterials) {
  27162. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27163. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27164. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27165. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27166. log += "\n\t\t" + mmat.toString(fullDetails);
  27167. }
  27168. }
  27169. // Skeletons
  27170. if (parsedData.skeletons) {
  27171. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27172. var parsedSkeleton = parsedData.skeletons[index];
  27173. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27174. log += (index === 0 ? "\n\tSkeletons:" : "");
  27175. log += "\n\t\t" + skeleton.toString(fullDetails);
  27176. }
  27177. }
  27178. // Geometries
  27179. var geometries = parsedData.geometries;
  27180. if (geometries) {
  27181. // Boxes
  27182. var boxes = geometries.boxes;
  27183. if (boxes) {
  27184. for (index = 0, cache = boxes.length; index < cache; index++) {
  27185. var parsedBox = boxes[index];
  27186. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27187. }
  27188. }
  27189. // Spheres
  27190. var spheres = geometries.spheres;
  27191. if (spheres) {
  27192. for (index = 0, cache = spheres.length; index < cache; index++) {
  27193. var parsedSphere = spheres[index];
  27194. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27195. }
  27196. }
  27197. // Cylinders
  27198. var cylinders = geometries.cylinders;
  27199. if (cylinders) {
  27200. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27201. var parsedCylinder = cylinders[index];
  27202. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27203. }
  27204. }
  27205. // Toruses
  27206. var toruses = geometries.toruses;
  27207. if (toruses) {
  27208. for (index = 0, cache = toruses.length; index < cache; index++) {
  27209. var parsedTorus = toruses[index];
  27210. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27211. }
  27212. }
  27213. // Grounds
  27214. var grounds = geometries.grounds;
  27215. if (grounds) {
  27216. for (index = 0, cache = grounds.length; index < cache; index++) {
  27217. var parsedGround = grounds[index];
  27218. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27219. }
  27220. }
  27221. // Planes
  27222. var planes = geometries.planes;
  27223. if (planes) {
  27224. for (index = 0, cache = planes.length; index < cache; index++) {
  27225. var parsedPlane = planes[index];
  27226. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27227. }
  27228. }
  27229. // TorusKnots
  27230. var torusKnots = geometries.torusKnots;
  27231. if (torusKnots) {
  27232. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27233. var parsedTorusKnot = torusKnots[index];
  27234. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27235. }
  27236. }
  27237. // VertexData
  27238. var vertexData = geometries.vertexData;
  27239. if (vertexData) {
  27240. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27241. var parsedVertexData = vertexData[index];
  27242. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27243. }
  27244. }
  27245. }
  27246. // Meshes
  27247. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27248. var parsedMesh = parsedData.meshes[index];
  27249. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27250. log += (index === 0 ? "\n\tMeshes:" : "");
  27251. log += "\n\t\t" + mesh.toString(fullDetails);
  27252. }
  27253. // Cameras
  27254. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27255. var parsedCamera = parsedData.cameras[index];
  27256. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27257. log += (index === 0 ? "\n\tCameras:" : "");
  27258. log += "\n\t\t" + camera.toString(fullDetails);
  27259. }
  27260. if (parsedData.activeCameraID) {
  27261. scene.setActiveCameraByID(parsedData.activeCameraID);
  27262. }
  27263. // Browsing all the graph to connect the dots
  27264. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27265. var camera = scene.cameras[index];
  27266. if (camera._waitingParentId) {
  27267. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27268. camera._waitingParentId = undefined;
  27269. }
  27270. }
  27271. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27272. var light = scene.lights[index];
  27273. if (light._waitingParentId) {
  27274. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27275. light._waitingParentId = undefined;
  27276. }
  27277. }
  27278. // Sounds
  27279. var loadedSounds = [];
  27280. var loadedSound;
  27281. if (BABYLON.AudioEngine && parsedData.sounds) {
  27282. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27283. var parsedSound = parsedData.sounds[index];
  27284. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27285. if (!parsedSound.url)
  27286. parsedSound.url = parsedSound.name;
  27287. if (!loadedSounds[parsedSound.url]) {
  27288. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27289. loadedSounds[parsedSound.url] = loadedSound;
  27290. }
  27291. else {
  27292. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27293. }
  27294. }
  27295. else {
  27296. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27297. }
  27298. }
  27299. }
  27300. loadedSounds = [];
  27301. // Connect parents & children and parse actions
  27302. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27303. var mesh = scene.meshes[index];
  27304. if (mesh._waitingParentId) {
  27305. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27306. mesh._waitingParentId = undefined;
  27307. }
  27308. if (mesh._waitingActions) {
  27309. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27310. mesh._waitingActions = undefined;
  27311. }
  27312. }
  27313. // freeze world matrix application
  27314. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27315. var currentMesh = scene.meshes[index];
  27316. if (currentMesh._waitingFreezeWorldMatrix) {
  27317. currentMesh.freezeWorldMatrix();
  27318. currentMesh._waitingFreezeWorldMatrix = undefined;
  27319. }
  27320. else {
  27321. currentMesh.computeWorldMatrix(true);
  27322. }
  27323. }
  27324. // Particles Systems
  27325. if (parsedData.particleSystems) {
  27326. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27327. var parsedParticleSystem = parsedData.particleSystems[index];
  27328. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27329. }
  27330. }
  27331. // Lens flares
  27332. if (parsedData.lensFlareSystems) {
  27333. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27334. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27335. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27336. }
  27337. }
  27338. // Shadows
  27339. if (parsedData.shadowGenerators) {
  27340. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27341. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27342. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27343. }
  27344. }
  27345. // Actions (scene)
  27346. if (parsedData.actions) {
  27347. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27348. }
  27349. // Finish
  27350. return true;
  27351. }
  27352. catch (err) {
  27353. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27354. log = null;
  27355. throw err;
  27356. }
  27357. finally {
  27358. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27359. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27360. }
  27361. }
  27362. }
  27363. });
  27364. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27365. })(BABYLON || (BABYLON = {}));
  27366. var BABYLON;
  27367. (function (BABYLON) {
  27368. var SpriteManager = (function () {
  27369. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27370. if (epsilon === void 0) { epsilon = 0.01; }
  27371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27372. this.name = name;
  27373. this.sprites = new Array();
  27374. this.renderingGroupId = 0;
  27375. this.layerMask = 0x0FFFFFFF;
  27376. this.fogEnabled = true;
  27377. this.isPickable = false;
  27378. /**
  27379. * An event triggered when the manager is disposed.
  27380. * @type {BABYLON.Observable}
  27381. */
  27382. this.onDisposeObservable = new BABYLON.Observable();
  27383. this._vertexBuffers = {};
  27384. this._capacity = capacity;
  27385. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27386. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27387. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27388. if (cellSize.width && cellSize.height) {
  27389. this.cellWidth = cellSize.width;
  27390. this.cellHeight = cellSize.height;
  27391. }
  27392. else if (cellSize !== undefined) {
  27393. this.cellWidth = cellSize;
  27394. this.cellHeight = cellSize;
  27395. }
  27396. else {
  27397. return;
  27398. }
  27399. this._scene = scene;
  27400. this._scene.spriteManagers.push(this);
  27401. var indices = [];
  27402. var index = 0;
  27403. for (var count = 0; count < capacity; count++) {
  27404. indices.push(index);
  27405. indices.push(index + 1);
  27406. indices.push(index + 2);
  27407. indices.push(index);
  27408. indices.push(index + 2);
  27409. indices.push(index + 3);
  27410. index += 4;
  27411. }
  27412. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27413. // VBO
  27414. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27415. this._vertexData = new Float32Array(capacity * 16 * 4);
  27416. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27417. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27418. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27419. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27420. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27421. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27422. this._vertexBuffers["options"] = options;
  27423. this._vertexBuffers["cellInfo"] = cellInfo;
  27424. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27425. // Effects
  27426. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27427. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27428. }
  27429. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27430. set: function (callback) {
  27431. if (this._onDisposeObserver) {
  27432. this.onDisposeObservable.remove(this._onDisposeObserver);
  27433. }
  27434. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27435. },
  27436. enumerable: true,
  27437. configurable: true
  27438. });
  27439. Object.defineProperty(SpriteManager.prototype, "texture", {
  27440. get: function () {
  27441. return this._spriteTexture;
  27442. },
  27443. set: function (value) {
  27444. this._spriteTexture = value;
  27445. },
  27446. enumerable: true,
  27447. configurable: true
  27448. });
  27449. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27450. var arrayOffset = index * 16;
  27451. if (offsetX === 0)
  27452. offsetX = this._epsilon;
  27453. else if (offsetX === 1)
  27454. offsetX = 1 - this._epsilon;
  27455. if (offsetY === 0)
  27456. offsetY = this._epsilon;
  27457. else if (offsetY === 1)
  27458. offsetY = 1 - this._epsilon;
  27459. this._vertexData[arrayOffset] = sprite.position.x;
  27460. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27461. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27462. this._vertexData[arrayOffset + 3] = sprite.angle;
  27463. this._vertexData[arrayOffset + 4] = sprite.width;
  27464. this._vertexData[arrayOffset + 5] = sprite.height;
  27465. this._vertexData[arrayOffset + 6] = offsetX;
  27466. this._vertexData[arrayOffset + 7] = offsetY;
  27467. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27468. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27469. var offset = (sprite.cellIndex / rowSize) >> 0;
  27470. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27471. this._vertexData[arrayOffset + 11] = offset;
  27472. // Color
  27473. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27474. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27475. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27476. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27477. };
  27478. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27479. var count = Math.min(this._capacity, this.sprites.length);
  27480. var min = BABYLON.Vector3.Zero();
  27481. var max = BABYLON.Vector3.Zero();
  27482. var distance = Number.MAX_VALUE;
  27483. var currentSprite;
  27484. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27485. var cameraView = camera.getViewMatrix();
  27486. for (var index = 0; index < count; index++) {
  27487. var sprite = this.sprites[index];
  27488. if (!sprite) {
  27489. continue;
  27490. }
  27491. if (predicate) {
  27492. if (!predicate(sprite)) {
  27493. continue;
  27494. }
  27495. }
  27496. else if (!sprite.isPickable) {
  27497. continue;
  27498. }
  27499. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27500. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27501. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27502. if (ray.intersectsBoxMinMax(min, max)) {
  27503. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27504. if (distance > currentDistance) {
  27505. distance = currentDistance;
  27506. currentSprite = sprite;
  27507. if (fastCheck) {
  27508. break;
  27509. }
  27510. }
  27511. }
  27512. }
  27513. if (currentSprite) {
  27514. var result = new BABYLON.PickingInfo();
  27515. result.hit = true;
  27516. result.pickedSprite = currentSprite;
  27517. result.distance = distance;
  27518. return result;
  27519. }
  27520. return null;
  27521. };
  27522. SpriteManager.prototype.render = function () {
  27523. // Check
  27524. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27525. return;
  27526. var engine = this._scene.getEngine();
  27527. var baseSize = this._spriteTexture.getBaseSize();
  27528. // Sprites
  27529. var deltaTime = engine.getDeltaTime();
  27530. var max = Math.min(this._capacity, this.sprites.length);
  27531. var rowSize = baseSize.width / this.cellWidth;
  27532. var offset = 0;
  27533. for (var index = 0; index < max; index++) {
  27534. var sprite = this.sprites[index];
  27535. if (!sprite) {
  27536. continue;
  27537. }
  27538. sprite._animate(deltaTime);
  27539. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27540. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27541. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27542. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27543. }
  27544. this._buffer.update(this._vertexData);
  27545. // Render
  27546. var effect = this._effectBase;
  27547. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27548. effect = this._effectFog;
  27549. }
  27550. engine.enableEffect(effect);
  27551. var viewMatrix = this._scene.getViewMatrix();
  27552. effect.setTexture("diffuseSampler", this._spriteTexture);
  27553. effect.setMatrix("view", viewMatrix);
  27554. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27555. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27556. // Fog
  27557. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27558. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27559. effect.setColor3("vFogColor", this._scene.fogColor);
  27560. }
  27561. // VBOs
  27562. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27563. // Draw order
  27564. engine.setDepthFunctionToLessOrEqual();
  27565. effect.setBool("alphaTest", true);
  27566. engine.setColorWrite(false);
  27567. engine.draw(true, 0, max * 6);
  27568. engine.setColorWrite(true);
  27569. effect.setBool("alphaTest", false);
  27570. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27571. engine.draw(true, 0, max * 6);
  27572. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27573. };
  27574. SpriteManager.prototype.dispose = function () {
  27575. if (this._buffer) {
  27576. this._buffer.dispose();
  27577. this._buffer = null;
  27578. }
  27579. if (this._indexBuffer) {
  27580. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27581. this._indexBuffer = null;
  27582. }
  27583. if (this._spriteTexture) {
  27584. this._spriteTexture.dispose();
  27585. this._spriteTexture = null;
  27586. }
  27587. // Remove from scene
  27588. var index = this._scene.spriteManagers.indexOf(this);
  27589. this._scene.spriteManagers.splice(index, 1);
  27590. // Callback
  27591. this.onDisposeObservable.notifyObservers(this);
  27592. this.onDisposeObservable.clear();
  27593. };
  27594. return SpriteManager;
  27595. }());
  27596. BABYLON.SpriteManager = SpriteManager;
  27597. })(BABYLON || (BABYLON = {}));
  27598. var BABYLON;
  27599. (function (BABYLON) {
  27600. var Sprite = (function () {
  27601. function Sprite(name, manager) {
  27602. this.name = name;
  27603. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27604. this.width = 1.0;
  27605. this.height = 1.0;
  27606. this.angle = 0;
  27607. this.cellIndex = 0;
  27608. this.invertU = 0;
  27609. this.invertV = 0;
  27610. this.animations = new Array();
  27611. this.isPickable = false;
  27612. this._animationStarted = false;
  27613. this._loopAnimation = false;
  27614. this._fromIndex = 0;
  27615. this._toIndex = 0;
  27616. this._delay = 0;
  27617. this._direction = 1;
  27618. this._frameCount = 0;
  27619. this._time = 0;
  27620. this._manager = manager;
  27621. this._manager.sprites.push(this);
  27622. this.position = BABYLON.Vector3.Zero();
  27623. }
  27624. Object.defineProperty(Sprite.prototype, "size", {
  27625. get: function () {
  27626. return this.width;
  27627. },
  27628. set: function (value) {
  27629. this.width = value;
  27630. this.height = value;
  27631. },
  27632. enumerable: true,
  27633. configurable: true
  27634. });
  27635. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27636. this._fromIndex = from;
  27637. this._toIndex = to;
  27638. this._loopAnimation = loop;
  27639. this._delay = delay;
  27640. this._animationStarted = true;
  27641. this._direction = from < to ? 1 : -1;
  27642. this.cellIndex = from;
  27643. this._time = 0;
  27644. this._onAnimationEnd = onAnimationEnd;
  27645. };
  27646. Sprite.prototype.stopAnimation = function () {
  27647. this._animationStarted = false;
  27648. };
  27649. Sprite.prototype._animate = function (deltaTime) {
  27650. if (!this._animationStarted)
  27651. return;
  27652. this._time += deltaTime;
  27653. if (this._time > this._delay) {
  27654. this._time = this._time % this._delay;
  27655. this.cellIndex += this._direction;
  27656. if (this.cellIndex === this._toIndex) {
  27657. if (this._loopAnimation) {
  27658. this.cellIndex = this._fromIndex;
  27659. }
  27660. else {
  27661. this._animationStarted = false;
  27662. if (this._onAnimationEnd) {
  27663. this._onAnimationEnd();
  27664. }
  27665. if (this.disposeWhenFinishedAnimating) {
  27666. this.dispose();
  27667. }
  27668. }
  27669. }
  27670. }
  27671. };
  27672. Sprite.prototype.dispose = function () {
  27673. for (var i = 0; i < this._manager.sprites.length; i++) {
  27674. if (this._manager.sprites[i] == this) {
  27675. this._manager.sprites.splice(i, 1);
  27676. }
  27677. }
  27678. };
  27679. return Sprite;
  27680. }());
  27681. BABYLON.Sprite = Sprite;
  27682. })(BABYLON || (BABYLON = {}));
  27683. var BABYLON;
  27684. (function (BABYLON) {
  27685. var Layer = (function () {
  27686. function Layer(name, imgUrl, scene, isBackground, color) {
  27687. this.name = name;
  27688. this.scale = new BABYLON.Vector2(1, 1);
  27689. this.offset = new BABYLON.Vector2(0, 0);
  27690. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27691. this._vertexBuffers = {};
  27692. // Events
  27693. /**
  27694. * An event triggered when the layer is disposed.
  27695. * @type {BABYLON.Observable}
  27696. */
  27697. this.onDisposeObservable = new BABYLON.Observable();
  27698. /**
  27699. * An event triggered before rendering the scene
  27700. * @type {BABYLON.Observable}
  27701. */
  27702. this.onBeforeRenderObservable = new BABYLON.Observable();
  27703. /**
  27704. * An event triggered after rendering the scene
  27705. * @type {BABYLON.Observable}
  27706. */
  27707. this.onAfterRenderObservable = new BABYLON.Observable();
  27708. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27709. this.isBackground = isBackground === undefined ? true : isBackground;
  27710. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27711. this._scene = scene;
  27712. this._scene.layers.push(this);
  27713. var engine = scene.getEngine();
  27714. // VBO
  27715. var vertices = [];
  27716. vertices.push(1, 1);
  27717. vertices.push(-1, 1);
  27718. vertices.push(-1, -1);
  27719. vertices.push(1, -1);
  27720. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27721. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27722. // Indices
  27723. var indices = [];
  27724. indices.push(0);
  27725. indices.push(1);
  27726. indices.push(2);
  27727. indices.push(0);
  27728. indices.push(2);
  27729. indices.push(3);
  27730. this._indexBuffer = engine.createIndexBuffer(indices);
  27731. // Effects
  27732. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27733. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27734. }
  27735. Object.defineProperty(Layer.prototype, "onDispose", {
  27736. set: function (callback) {
  27737. if (this._onDisposeObserver) {
  27738. this.onDisposeObservable.remove(this._onDisposeObserver);
  27739. }
  27740. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27741. },
  27742. enumerable: true,
  27743. configurable: true
  27744. });
  27745. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27746. set: function (callback) {
  27747. if (this._onBeforeRenderObserver) {
  27748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27749. }
  27750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27751. },
  27752. enumerable: true,
  27753. configurable: true
  27754. });
  27755. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27756. set: function (callback) {
  27757. if (this._onAfterRenderObserver) {
  27758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27759. }
  27760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27761. },
  27762. enumerable: true,
  27763. configurable: true
  27764. });
  27765. Layer.prototype.render = function () {
  27766. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27767. // Check
  27768. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27769. return;
  27770. var engine = this._scene.getEngine();
  27771. this.onBeforeRenderObservable.notifyObservers(this);
  27772. // Render
  27773. engine.enableEffect(currentEffect);
  27774. engine.setState(false);
  27775. // Texture
  27776. currentEffect.setTexture("textureSampler", this.texture);
  27777. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27778. // Color
  27779. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27780. // Scale / offset
  27781. currentEffect.setVector2("offset", this.offset);
  27782. currentEffect.setVector2("scale", this.scale);
  27783. // VBOs
  27784. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27785. // Draw order
  27786. if (!this.alphaTest) {
  27787. engine.setAlphaMode(this.alphaBlendingMode);
  27788. engine.draw(true, 0, 6);
  27789. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27790. }
  27791. else {
  27792. engine.draw(true, 0, 6);
  27793. }
  27794. this.onAfterRenderObservable.notifyObservers(this);
  27795. };
  27796. Layer.prototype.dispose = function () {
  27797. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27798. if (vertexBuffer) {
  27799. vertexBuffer.dispose();
  27800. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27801. }
  27802. if (this._indexBuffer) {
  27803. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27804. this._indexBuffer = null;
  27805. }
  27806. if (this.texture) {
  27807. this.texture.dispose();
  27808. this.texture = null;
  27809. }
  27810. // Remove from scene
  27811. var index = this._scene.layers.indexOf(this);
  27812. this._scene.layers.splice(index, 1);
  27813. // Callback
  27814. this.onDisposeObservable.notifyObservers(this);
  27815. this.onDisposeObservable.clear();
  27816. this.onAfterRenderObservable.clear();
  27817. this.onBeforeRenderObservable.clear();
  27818. };
  27819. return Layer;
  27820. }());
  27821. BABYLON.Layer = Layer;
  27822. })(BABYLON || (BABYLON = {}));
  27823. var BABYLON;
  27824. (function (BABYLON) {
  27825. var Particle = (function () {
  27826. function Particle() {
  27827. this.position = BABYLON.Vector3.Zero();
  27828. this.direction = BABYLON.Vector3.Zero();
  27829. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27830. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27831. this.lifeTime = 1.0;
  27832. this.age = 0;
  27833. this.size = 0;
  27834. this.angle = 0;
  27835. this.angularSpeed = 0;
  27836. }
  27837. Particle.prototype.copyTo = function (other) {
  27838. other.position.copyFrom(this.position);
  27839. other.direction.copyFrom(this.direction);
  27840. other.color.copyFrom(this.color);
  27841. other.colorStep.copyFrom(this.colorStep);
  27842. other.lifeTime = this.lifeTime;
  27843. other.age = this.age;
  27844. other.size = this.size;
  27845. other.angle = this.angle;
  27846. other.angularSpeed = this.angularSpeed;
  27847. };
  27848. return Particle;
  27849. }());
  27850. BABYLON.Particle = Particle;
  27851. })(BABYLON || (BABYLON = {}));
  27852. var BABYLON;
  27853. (function (BABYLON) {
  27854. var randomNumber = function (min, max) {
  27855. if (min === max) {
  27856. return (min);
  27857. }
  27858. var random = Math.random();
  27859. return ((random * (max - min)) + min);
  27860. };
  27861. var ParticleSystem = (function () {
  27862. function ParticleSystem(name, capacity, scene, customEffect) {
  27863. var _this = this;
  27864. this.name = name;
  27865. // Members
  27866. this.animations = [];
  27867. this.renderingGroupId = 0;
  27868. this.emitter = null;
  27869. this.emitRate = 10;
  27870. this.manualEmitCount = -1;
  27871. this.updateSpeed = 0.01;
  27872. this.targetStopDuration = 0;
  27873. this.disposeOnStop = false;
  27874. this.minEmitPower = 1;
  27875. this.maxEmitPower = 1;
  27876. this.minLifeTime = 1;
  27877. this.maxLifeTime = 1;
  27878. this.minSize = 1;
  27879. this.maxSize = 1;
  27880. this.minAngularSpeed = 0;
  27881. this.maxAngularSpeed = 0;
  27882. this.layerMask = 0x0FFFFFFF;
  27883. /**
  27884. * An event triggered when the system is disposed.
  27885. * @type {BABYLON.Observable}
  27886. */
  27887. this.onDisposeObservable = new BABYLON.Observable();
  27888. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27889. this.forceDepthWrite = false;
  27890. this.gravity = BABYLON.Vector3.Zero();
  27891. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27892. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27893. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27894. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27895. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27896. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27897. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27898. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27899. this.particles = new Array();
  27900. this._stockParticles = new Array();
  27901. this._newPartsExcess = 0;
  27902. this._vertexBuffers = {};
  27903. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27904. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27905. this._scaledDirection = BABYLON.Vector3.Zero();
  27906. this._scaledGravity = BABYLON.Vector3.Zero();
  27907. this._currentRenderId = -1;
  27908. this._started = false;
  27909. this._stopped = false;
  27910. this._actualFrame = 0;
  27911. this.id = name;
  27912. this._capacity = capacity;
  27913. this._scene = scene;
  27914. this._customEffect = customEffect;
  27915. scene.particleSystems.push(this);
  27916. var indices = [];
  27917. var index = 0;
  27918. for (var count = 0; count < capacity; count++) {
  27919. indices.push(index);
  27920. indices.push(index + 1);
  27921. indices.push(index + 2);
  27922. indices.push(index);
  27923. indices.push(index + 2);
  27924. indices.push(index + 3);
  27925. index += 4;
  27926. }
  27927. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27928. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27929. this._vertexData = new Float32Array(capacity * 11 * 4);
  27930. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27931. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27932. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27933. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27934. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27935. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27936. this._vertexBuffers["options"] = options;
  27937. // Default behaviors
  27938. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27939. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27940. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27941. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27942. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27943. };
  27944. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27945. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27946. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27947. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27949. };
  27950. this.updateFunction = function (particles) {
  27951. for (var index = 0; index < particles.length; index++) {
  27952. var particle = particles[index];
  27953. particle.age += _this._scaledUpdateSpeed;
  27954. if (particle.age >= particle.lifeTime) {
  27955. _this.recycleParticle(particle);
  27956. index--;
  27957. continue;
  27958. }
  27959. else {
  27960. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27961. particle.color.addInPlace(_this._scaledColorStep);
  27962. if (particle.color.a < 0)
  27963. particle.color.a = 0;
  27964. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27965. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27966. particle.position.addInPlace(_this._scaledDirection);
  27967. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27968. particle.direction.addInPlace(_this._scaledGravity);
  27969. }
  27970. }
  27971. };
  27972. }
  27973. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27974. set: function (callback) {
  27975. if (this._onDisposeObserver) {
  27976. this.onDisposeObservable.remove(this._onDisposeObserver);
  27977. }
  27978. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27979. },
  27980. enumerable: true,
  27981. configurable: true
  27982. });
  27983. ParticleSystem.prototype.recycleParticle = function (particle) {
  27984. var lastParticle = this.particles.pop();
  27985. if (lastParticle !== particle) {
  27986. lastParticle.copyTo(particle);
  27987. this._stockParticles.push(lastParticle);
  27988. }
  27989. };
  27990. ParticleSystem.prototype.getCapacity = function () {
  27991. return this._capacity;
  27992. };
  27993. ParticleSystem.prototype.isAlive = function () {
  27994. return this._alive;
  27995. };
  27996. ParticleSystem.prototype.isStarted = function () {
  27997. return this._started;
  27998. };
  27999. ParticleSystem.prototype.start = function () {
  28000. this._started = true;
  28001. this._stopped = false;
  28002. this._actualFrame = 0;
  28003. };
  28004. ParticleSystem.prototype.stop = function () {
  28005. this._stopped = true;
  28006. };
  28007. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28008. var offset = index * 11;
  28009. this._vertexData[offset] = particle.position.x;
  28010. this._vertexData[offset + 1] = particle.position.y;
  28011. this._vertexData[offset + 2] = particle.position.z;
  28012. this._vertexData[offset + 3] = particle.color.r;
  28013. this._vertexData[offset + 4] = particle.color.g;
  28014. this._vertexData[offset + 5] = particle.color.b;
  28015. this._vertexData[offset + 6] = particle.color.a;
  28016. this._vertexData[offset + 7] = particle.angle;
  28017. this._vertexData[offset + 8] = particle.size;
  28018. this._vertexData[offset + 9] = offsetX;
  28019. this._vertexData[offset + 10] = offsetY;
  28020. };
  28021. ParticleSystem.prototype._update = function (newParticles) {
  28022. // Update current
  28023. this._alive = this.particles.length > 0;
  28024. this.updateFunction(this.particles);
  28025. // Add new ones
  28026. var worldMatrix;
  28027. if (this.emitter.position) {
  28028. worldMatrix = this.emitter.getWorldMatrix();
  28029. }
  28030. else {
  28031. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28032. }
  28033. var particle;
  28034. for (var index = 0; index < newParticles; index++) {
  28035. if (this.particles.length === this._capacity) {
  28036. break;
  28037. }
  28038. if (this._stockParticles.length !== 0) {
  28039. particle = this._stockParticles.pop();
  28040. particle.age = 0;
  28041. }
  28042. else {
  28043. particle = new BABYLON.Particle();
  28044. }
  28045. this.particles.push(particle);
  28046. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28047. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28048. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28049. particle.size = randomNumber(this.minSize, this.maxSize);
  28050. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28051. this.startPositionFunction(worldMatrix, particle.position, particle);
  28052. var step = randomNumber(0, 1.0);
  28053. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28054. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28055. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28056. }
  28057. };
  28058. ParticleSystem.prototype._getEffect = function () {
  28059. if (this._customEffect) {
  28060. return this._customEffect;
  28061. }
  28062. ;
  28063. var defines = [];
  28064. if (this._scene.clipPlane) {
  28065. defines.push("#define CLIPPLANE");
  28066. }
  28067. // Effect
  28068. var join = defines.join("\n");
  28069. if (this._cachedDefines !== join) {
  28070. this._cachedDefines = join;
  28071. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28072. }
  28073. return this._effect;
  28074. };
  28075. ParticleSystem.prototype.animate = function () {
  28076. if (!this._started)
  28077. return;
  28078. var effect = this._getEffect();
  28079. // Check
  28080. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28081. return;
  28082. if (this._currentRenderId === this._scene.getRenderId()) {
  28083. return;
  28084. }
  28085. this._currentRenderId = this._scene.getRenderId();
  28086. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28087. // determine the number of particles we need to create
  28088. var newParticles;
  28089. if (this.manualEmitCount > -1) {
  28090. newParticles = this.manualEmitCount;
  28091. this._newPartsExcess = 0;
  28092. this.manualEmitCount = 0;
  28093. }
  28094. else {
  28095. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28096. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28097. }
  28098. if (this._newPartsExcess > 1.0) {
  28099. newParticles += this._newPartsExcess >> 0;
  28100. this._newPartsExcess -= this._newPartsExcess >> 0;
  28101. }
  28102. this._alive = false;
  28103. if (!this._stopped) {
  28104. this._actualFrame += this._scaledUpdateSpeed;
  28105. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28106. this.stop();
  28107. }
  28108. else {
  28109. newParticles = 0;
  28110. }
  28111. this._update(newParticles);
  28112. // Stopped?
  28113. if (this._stopped) {
  28114. if (!this._alive) {
  28115. this._started = false;
  28116. if (this.disposeOnStop) {
  28117. this._scene._toBeDisposed.push(this);
  28118. }
  28119. }
  28120. }
  28121. // Update VBO
  28122. var offset = 0;
  28123. for (var index = 0; index < this.particles.length; index++) {
  28124. var particle = this.particles[index];
  28125. this._appendParticleVertex(offset++, particle, 0, 0);
  28126. this._appendParticleVertex(offset++, particle, 1, 0);
  28127. this._appendParticleVertex(offset++, particle, 1, 1);
  28128. this._appendParticleVertex(offset++, particle, 0, 1);
  28129. }
  28130. this._vertexBuffer.update(this._vertexData);
  28131. };
  28132. ParticleSystem.prototype.render = function () {
  28133. var effect = this._getEffect();
  28134. // Check
  28135. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28136. return 0;
  28137. var engine = this._scene.getEngine();
  28138. // Render
  28139. engine.enableEffect(effect);
  28140. engine.setState(false);
  28141. var viewMatrix = this._scene.getViewMatrix();
  28142. effect.setTexture("diffuseSampler", this.particleTexture);
  28143. effect.setMatrix("view", viewMatrix);
  28144. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28145. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28146. if (this._scene.clipPlane) {
  28147. var clipPlane = this._scene.clipPlane;
  28148. var invView = viewMatrix.clone();
  28149. invView.invert();
  28150. effect.setMatrix("invView", invView);
  28151. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28152. }
  28153. // VBOs
  28154. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28155. // Draw order
  28156. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28157. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28158. }
  28159. else {
  28160. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28161. }
  28162. if (this.forceDepthWrite) {
  28163. engine.setDepthWrite(true);
  28164. }
  28165. engine.draw(true, 0, this.particles.length * 6);
  28166. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28167. return this.particles.length;
  28168. };
  28169. ParticleSystem.prototype.dispose = function () {
  28170. if (this._vertexBuffer) {
  28171. this._vertexBuffer.dispose();
  28172. this._vertexBuffer = null;
  28173. }
  28174. if (this._indexBuffer) {
  28175. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28176. this._indexBuffer = null;
  28177. }
  28178. if (this.particleTexture) {
  28179. this.particleTexture.dispose();
  28180. this.particleTexture = null;
  28181. }
  28182. // Remove from scene
  28183. var index = this._scene.particleSystems.indexOf(this);
  28184. this._scene.particleSystems.splice(index, 1);
  28185. // Callback
  28186. this.onDisposeObservable.notifyObservers(this);
  28187. this.onDisposeObservable.clear();
  28188. };
  28189. // Clone
  28190. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28191. var result = new ParticleSystem(name, this._capacity, this._scene);
  28192. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28193. if (newEmitter === undefined) {
  28194. newEmitter = this.emitter;
  28195. }
  28196. result.emitter = newEmitter;
  28197. if (this.particleTexture) {
  28198. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28199. }
  28200. result.start();
  28201. return result;
  28202. };
  28203. ParticleSystem.prototype.serialize = function () {
  28204. var serializationObject = {};
  28205. serializationObject.name = this.name;
  28206. serializationObject.id = this.id;
  28207. // Emitter
  28208. if (this.emitter.position) {
  28209. serializationObject.emitterId = this.emitter.id;
  28210. }
  28211. else {
  28212. serializationObject.emitter = this.emitter.asArray();
  28213. }
  28214. serializationObject.capacity = this.getCapacity();
  28215. if (this.particleTexture) {
  28216. serializationObject.textureName = this.particleTexture.name;
  28217. }
  28218. // Animations
  28219. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28220. // Particle system
  28221. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28222. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28223. serializationObject.minSize = this.minSize;
  28224. serializationObject.maxSize = this.maxSize;
  28225. serializationObject.minEmitPower = this.minEmitPower;
  28226. serializationObject.maxEmitPower = this.maxEmitPower;
  28227. serializationObject.minLifeTime = this.minLifeTime;
  28228. serializationObject.maxLifeTime = this.maxLifeTime;
  28229. serializationObject.emitRate = this.emitRate;
  28230. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28231. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28232. serializationObject.gravity = this.gravity.asArray();
  28233. serializationObject.direction1 = this.direction1.asArray();
  28234. serializationObject.direction2 = this.direction2.asArray();
  28235. serializationObject.color1 = this.color1.asArray();
  28236. serializationObject.color2 = this.color2.asArray();
  28237. serializationObject.colorDead = this.colorDead.asArray();
  28238. serializationObject.updateSpeed = this.updateSpeed;
  28239. serializationObject.targetStopDuration = this.targetStopDuration;
  28240. serializationObject.textureMask = this.textureMask.asArray();
  28241. serializationObject.blendMode = this.blendMode;
  28242. return serializationObject;
  28243. };
  28244. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28245. var name = parsedParticleSystem.name;
  28246. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28247. if (parsedParticleSystem.id) {
  28248. particleSystem.id = parsedParticleSystem.id;
  28249. }
  28250. // Texture
  28251. if (parsedParticleSystem.textureName) {
  28252. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28253. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28254. }
  28255. // Emitter
  28256. if (parsedParticleSystem.emitterId) {
  28257. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28258. }
  28259. else {
  28260. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28261. }
  28262. // Animations
  28263. if (parsedParticleSystem.animations) {
  28264. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28265. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28266. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28267. }
  28268. }
  28269. if (parsedParticleSystem.autoAnimate) {
  28270. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28271. }
  28272. // Particle system
  28273. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28274. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28275. particleSystem.minSize = parsedParticleSystem.minSize;
  28276. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28277. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28278. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28279. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28280. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28281. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28282. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28283. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28284. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28285. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28286. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28287. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28288. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28289. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28290. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28291. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28292. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28293. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28294. if (!parsedParticleSystem.preventAutoStart) {
  28295. particleSystem.start();
  28296. }
  28297. return particleSystem;
  28298. };
  28299. // Statics
  28300. ParticleSystem.BLENDMODE_ONEONE = 0;
  28301. ParticleSystem.BLENDMODE_STANDARD = 1;
  28302. return ParticleSystem;
  28303. }());
  28304. BABYLON.ParticleSystem = ParticleSystem;
  28305. })(BABYLON || (BABYLON = {}));
  28306. var BABYLON;
  28307. (function (BABYLON) {
  28308. var AnimationRange = (function () {
  28309. function AnimationRange(name, from, to) {
  28310. this.name = name;
  28311. this.from = from;
  28312. this.to = to;
  28313. }
  28314. AnimationRange.prototype.clone = function () {
  28315. return new AnimationRange(this.name, this.from, this.to);
  28316. };
  28317. return AnimationRange;
  28318. }());
  28319. BABYLON.AnimationRange = AnimationRange;
  28320. /**
  28321. * Composed of a frame, and an action function
  28322. */
  28323. var AnimationEvent = (function () {
  28324. function AnimationEvent(frame, action, onlyOnce) {
  28325. this.frame = frame;
  28326. this.action = action;
  28327. this.onlyOnce = onlyOnce;
  28328. this.isDone = false;
  28329. }
  28330. return AnimationEvent;
  28331. }());
  28332. BABYLON.AnimationEvent = AnimationEvent;
  28333. var PathCursor = (function () {
  28334. function PathCursor(path) {
  28335. this.path = path;
  28336. this._onchange = new Array();
  28337. this.value = 0;
  28338. this.animations = new Array();
  28339. }
  28340. PathCursor.prototype.getPoint = function () {
  28341. var point = this.path.getPointAtLengthPosition(this.value);
  28342. return new BABYLON.Vector3(point.x, 0, point.y);
  28343. };
  28344. PathCursor.prototype.moveAhead = function (step) {
  28345. if (step === void 0) { step = 0.002; }
  28346. this.move(step);
  28347. return this;
  28348. };
  28349. PathCursor.prototype.moveBack = function (step) {
  28350. if (step === void 0) { step = 0.002; }
  28351. this.move(-step);
  28352. return this;
  28353. };
  28354. PathCursor.prototype.move = function (step) {
  28355. if (Math.abs(step) > 1) {
  28356. throw "step size should be less than 1.";
  28357. }
  28358. this.value += step;
  28359. this.ensureLimits();
  28360. this.raiseOnChange();
  28361. return this;
  28362. };
  28363. PathCursor.prototype.ensureLimits = function () {
  28364. while (this.value > 1) {
  28365. this.value -= 1;
  28366. }
  28367. while (this.value < 0) {
  28368. this.value += 1;
  28369. }
  28370. return this;
  28371. };
  28372. // used by animation engine
  28373. PathCursor.prototype.markAsDirty = function (propertyName) {
  28374. this.ensureLimits();
  28375. this.raiseOnChange();
  28376. return this;
  28377. };
  28378. PathCursor.prototype.raiseOnChange = function () {
  28379. var _this = this;
  28380. this._onchange.forEach(function (f) { return f(_this); });
  28381. return this;
  28382. };
  28383. PathCursor.prototype.onchange = function (f) {
  28384. this._onchange.push(f);
  28385. return this;
  28386. };
  28387. return PathCursor;
  28388. }());
  28389. BABYLON.PathCursor = PathCursor;
  28390. var Animation = (function () {
  28391. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28392. this.name = name;
  28393. this.targetProperty = targetProperty;
  28394. this.framePerSecond = framePerSecond;
  28395. this.dataType = dataType;
  28396. this.loopMode = loopMode;
  28397. this.enableBlending = enableBlending;
  28398. this._offsetsCache = {};
  28399. this._highLimitsCache = {};
  28400. this._stopped = false;
  28401. this._blendingFactor = 0;
  28402. // The set of event that will be linked to this animation
  28403. this._events = new Array();
  28404. this.allowMatricesInterpolation = false;
  28405. this.blendingSpeed = 0.01;
  28406. this._ranges = {};
  28407. this.targetPropertyPath = targetProperty.split(".");
  28408. this.dataType = dataType;
  28409. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28410. }
  28411. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28412. var dataType = undefined;
  28413. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28414. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28415. }
  28416. else if (from instanceof BABYLON.Quaternion) {
  28417. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28418. }
  28419. else if (from instanceof BABYLON.Vector3) {
  28420. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28421. }
  28422. else if (from instanceof BABYLON.Vector2) {
  28423. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28424. }
  28425. else if (from instanceof BABYLON.Color3) {
  28426. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28427. }
  28428. else if (from instanceof BABYLON.Size) {
  28429. dataType = Animation.ANIMATIONTYPE_SIZE;
  28430. }
  28431. if (dataType == undefined) {
  28432. return null;
  28433. }
  28434. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28435. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28436. animation.setKeys(keys);
  28437. if (easingFunction !== undefined) {
  28438. animation.setEasingFunction(easingFunction);
  28439. }
  28440. return animation;
  28441. };
  28442. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28443. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28444. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28445. };
  28446. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28447. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28448. node.animations.push(animation);
  28449. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28450. };
  28451. // Methods
  28452. /**
  28453. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28454. */
  28455. Animation.prototype.toString = function (fullDetails) {
  28456. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28457. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28458. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28459. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28460. if (fullDetails) {
  28461. ret += ", Ranges: {";
  28462. var first = true;
  28463. for (var name in this._ranges) {
  28464. if (first) {
  28465. ret += ", ";
  28466. first = false;
  28467. }
  28468. ret += name;
  28469. }
  28470. ret += "}";
  28471. }
  28472. return ret;
  28473. };
  28474. /**
  28475. * Add an event to this animation.
  28476. */
  28477. Animation.prototype.addEvent = function (event) {
  28478. this._events.push(event);
  28479. };
  28480. /**
  28481. * Remove all events found at the given frame
  28482. * @param frame
  28483. */
  28484. Animation.prototype.removeEvents = function (frame) {
  28485. for (var index = 0; index < this._events.length; index++) {
  28486. if (this._events[index].frame === frame) {
  28487. this._events.splice(index, 1);
  28488. index--;
  28489. }
  28490. }
  28491. };
  28492. Animation.prototype.createRange = function (name, from, to) {
  28493. // check name not already in use; could happen for bones after serialized
  28494. if (!this._ranges[name]) {
  28495. this._ranges[name] = new AnimationRange(name, from, to);
  28496. }
  28497. };
  28498. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28499. if (deleteFrames === void 0) { deleteFrames = true; }
  28500. if (this._ranges[name]) {
  28501. if (deleteFrames) {
  28502. var from = this._ranges[name].from;
  28503. var to = this._ranges[name].to;
  28504. // this loop MUST go high to low for multiple splices to work
  28505. for (var key = this._keys.length - 1; key >= 0; key--) {
  28506. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28507. this._keys.splice(key, 1);
  28508. }
  28509. }
  28510. }
  28511. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28512. }
  28513. };
  28514. Animation.prototype.getRange = function (name) {
  28515. return this._ranges[name];
  28516. };
  28517. Animation.prototype.reset = function () {
  28518. this._offsetsCache = {};
  28519. this._highLimitsCache = {};
  28520. this.currentFrame = 0;
  28521. this._blendingFactor = 0;
  28522. this._originalBlendValue = null;
  28523. };
  28524. Animation.prototype.isStopped = function () {
  28525. return this._stopped;
  28526. };
  28527. Animation.prototype.getKeys = function () {
  28528. return this._keys;
  28529. };
  28530. Animation.prototype.getHighestFrame = function () {
  28531. var ret = 0;
  28532. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28533. if (ret < this._keys[key].frame) {
  28534. ret = this._keys[key].frame;
  28535. }
  28536. }
  28537. return ret;
  28538. };
  28539. Animation.prototype.getEasingFunction = function () {
  28540. return this._easingFunction;
  28541. };
  28542. Animation.prototype.setEasingFunction = function (easingFunction) {
  28543. this._easingFunction = easingFunction;
  28544. };
  28545. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28546. return startValue + (endValue - startValue) * gradient;
  28547. };
  28548. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28549. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28550. };
  28551. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28552. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28553. };
  28554. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28555. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28556. };
  28557. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28558. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28559. };
  28560. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28561. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28562. };
  28563. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28564. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28565. };
  28566. Animation.prototype.clone = function () {
  28567. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28568. if (this._keys) {
  28569. clone.setKeys(this._keys);
  28570. }
  28571. if (this._ranges) {
  28572. clone._ranges = {};
  28573. for (var name in this._ranges) {
  28574. clone._ranges[name] = this._ranges[name].clone();
  28575. }
  28576. }
  28577. return clone;
  28578. };
  28579. Animation.prototype.setKeys = function (values) {
  28580. this._keys = values.slice(0);
  28581. this._offsetsCache = {};
  28582. this._highLimitsCache = {};
  28583. };
  28584. Animation.prototype._getKeyValue = function (value) {
  28585. if (typeof value === "function") {
  28586. return value();
  28587. }
  28588. return value;
  28589. };
  28590. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28591. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28592. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28593. }
  28594. this.currentFrame = currentFrame;
  28595. // Try to get a hash to find the right key
  28596. 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));
  28597. if (this._keys[startKey].frame >= currentFrame) {
  28598. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28599. startKey--;
  28600. }
  28601. }
  28602. for (var key = startKey; key < this._keys.length; key++) {
  28603. if (this._keys[key + 1].frame >= currentFrame) {
  28604. var startValue = this._getKeyValue(this._keys[key].value);
  28605. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28606. // gradient : percent of currentFrame between the frame inf and the frame sup
  28607. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28608. // check for easingFunction and correction of gradient
  28609. if (this._easingFunction != null) {
  28610. gradient = this._easingFunction.ease(gradient);
  28611. }
  28612. switch (this.dataType) {
  28613. // Float
  28614. case Animation.ANIMATIONTYPE_FLOAT:
  28615. switch (loopMode) {
  28616. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28617. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28618. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28619. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28620. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28621. }
  28622. break;
  28623. // Quaternion
  28624. case Animation.ANIMATIONTYPE_QUATERNION:
  28625. var quaternion = null;
  28626. switch (loopMode) {
  28627. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28628. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28629. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28630. break;
  28631. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28632. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28633. break;
  28634. }
  28635. return quaternion;
  28636. // Vector3
  28637. case Animation.ANIMATIONTYPE_VECTOR3:
  28638. switch (loopMode) {
  28639. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28640. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28641. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28642. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28643. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28644. }
  28645. // Vector2
  28646. case Animation.ANIMATIONTYPE_VECTOR2:
  28647. switch (loopMode) {
  28648. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28649. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28650. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28651. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28652. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28653. }
  28654. // Size
  28655. case Animation.ANIMATIONTYPE_SIZE:
  28656. switch (loopMode) {
  28657. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28658. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28659. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28660. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28661. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28662. }
  28663. // Color3
  28664. case Animation.ANIMATIONTYPE_COLOR3:
  28665. switch (loopMode) {
  28666. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28667. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28668. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28669. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28670. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28671. }
  28672. // Matrix
  28673. case Animation.ANIMATIONTYPE_MATRIX:
  28674. switch (loopMode) {
  28675. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28676. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28677. if (this.allowMatricesInterpolation) {
  28678. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28679. }
  28680. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28681. return startValue;
  28682. }
  28683. default:
  28684. break;
  28685. }
  28686. break;
  28687. }
  28688. }
  28689. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28690. };
  28691. Animation.prototype.setValue = function (currentValue, blend) {
  28692. if (blend === void 0) { blend = false; }
  28693. // Set value
  28694. var path;
  28695. var destination;
  28696. if (this.targetPropertyPath.length > 1) {
  28697. var property = this._target[this.targetPropertyPath[0]];
  28698. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28699. property = property[this.targetPropertyPath[index]];
  28700. }
  28701. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28702. destination = property;
  28703. }
  28704. else {
  28705. path = this.targetPropertyPath[0];
  28706. destination = this._target;
  28707. }
  28708. // Blending
  28709. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28710. if (!this._originalBlendValue) {
  28711. if (destination[path].clone) {
  28712. this._originalBlendValue = destination[path].clone();
  28713. }
  28714. else {
  28715. this._originalBlendValue = destination[path];
  28716. }
  28717. }
  28718. if (this._originalBlendValue.prototype) {
  28719. if (this._originalBlendValue.prototype.Lerp) {
  28720. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28721. }
  28722. else {
  28723. destination[path] = currentValue;
  28724. }
  28725. }
  28726. else if (this._originalBlendValue.m) {
  28727. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28728. }
  28729. else {
  28730. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28731. }
  28732. this._blendingFactor += this.blendingSpeed;
  28733. }
  28734. else {
  28735. destination[path] = currentValue;
  28736. }
  28737. if (this._target.markAsDirty) {
  28738. this._target.markAsDirty(this.targetProperty);
  28739. }
  28740. };
  28741. Animation.prototype.goToFrame = function (frame) {
  28742. if (frame < this._keys[0].frame) {
  28743. frame = this._keys[0].frame;
  28744. }
  28745. else if (frame > this._keys[this._keys.length - 1].frame) {
  28746. frame = this._keys[this._keys.length - 1].frame;
  28747. }
  28748. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28749. this.setValue(currentValue);
  28750. };
  28751. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28752. if (blend === void 0) { blend = false; }
  28753. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28754. this._stopped = true;
  28755. return false;
  28756. }
  28757. var returnValue = true;
  28758. // Adding a start key at frame 0 if missing
  28759. if (this._keys[0].frame !== 0) {
  28760. var newKey = { frame: 0, value: this._keys[0].value };
  28761. this._keys.splice(0, 0, newKey);
  28762. }
  28763. // Check limits
  28764. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28765. from = this._keys[0].frame;
  28766. }
  28767. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28768. to = this._keys[this._keys.length - 1].frame;
  28769. }
  28770. // Compute ratio
  28771. var range = to - from;
  28772. var offsetValue;
  28773. // ratio represents the frame delta between from and to
  28774. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28775. var highLimitValue = 0;
  28776. if (ratio > range && !loop) {
  28777. returnValue = false;
  28778. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28779. }
  28780. else {
  28781. // Get max value if required
  28782. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28783. var keyOffset = to.toString() + from.toString();
  28784. if (!this._offsetsCache[keyOffset]) {
  28785. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28786. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28787. switch (this.dataType) {
  28788. // Float
  28789. case Animation.ANIMATIONTYPE_FLOAT:
  28790. this._offsetsCache[keyOffset] = toValue - fromValue;
  28791. break;
  28792. // Quaternion
  28793. case Animation.ANIMATIONTYPE_QUATERNION:
  28794. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28795. break;
  28796. // Vector3
  28797. case Animation.ANIMATIONTYPE_VECTOR3:
  28798. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28799. // Vector2
  28800. case Animation.ANIMATIONTYPE_VECTOR2:
  28801. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28802. // Size
  28803. case Animation.ANIMATIONTYPE_SIZE:
  28804. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28805. // Color3
  28806. case Animation.ANIMATIONTYPE_COLOR3:
  28807. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28808. default:
  28809. break;
  28810. }
  28811. this._highLimitsCache[keyOffset] = toValue;
  28812. }
  28813. highLimitValue = this._highLimitsCache[keyOffset];
  28814. offsetValue = this._offsetsCache[keyOffset];
  28815. }
  28816. }
  28817. if (offsetValue === undefined) {
  28818. switch (this.dataType) {
  28819. // Float
  28820. case Animation.ANIMATIONTYPE_FLOAT:
  28821. offsetValue = 0;
  28822. break;
  28823. // Quaternion
  28824. case Animation.ANIMATIONTYPE_QUATERNION:
  28825. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28826. break;
  28827. // Vector3
  28828. case Animation.ANIMATIONTYPE_VECTOR3:
  28829. offsetValue = BABYLON.Vector3.Zero();
  28830. break;
  28831. // Vector2
  28832. case Animation.ANIMATIONTYPE_VECTOR2:
  28833. offsetValue = BABYLON.Vector2.Zero();
  28834. break;
  28835. // Size
  28836. case Animation.ANIMATIONTYPE_SIZE:
  28837. offsetValue = BABYLON.Size.Zero();
  28838. break;
  28839. // Color3
  28840. case Animation.ANIMATIONTYPE_COLOR3:
  28841. offsetValue = BABYLON.Color3.Black();
  28842. }
  28843. }
  28844. // Compute value
  28845. var repeatCount = (ratio / range) >> 0;
  28846. var currentFrame = returnValue ? from + ratio % range : to;
  28847. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28848. // Set value
  28849. this.setValue(currentValue);
  28850. // Check events
  28851. for (var index = 0; index < this._events.length; index++) {
  28852. if (currentFrame >= this._events[index].frame) {
  28853. var event = this._events[index];
  28854. if (!event.isDone) {
  28855. // If event should be done only once, remove it.
  28856. if (event.onlyOnce) {
  28857. this._events.splice(index, 1);
  28858. index--;
  28859. }
  28860. event.isDone = true;
  28861. event.action();
  28862. } // Don't do anything if the event has already be done.
  28863. }
  28864. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28865. // reset event, the animation is looping
  28866. this._events[index].isDone = false;
  28867. }
  28868. }
  28869. if (!returnValue) {
  28870. this._stopped = true;
  28871. }
  28872. return returnValue;
  28873. };
  28874. Animation.prototype.serialize = function () {
  28875. var serializationObject = {};
  28876. serializationObject.name = this.name;
  28877. serializationObject.property = this.targetProperty;
  28878. serializationObject.framePerSecond = this.framePerSecond;
  28879. serializationObject.dataType = this.dataType;
  28880. serializationObject.loopBehavior = this.loopMode;
  28881. var dataType = this.dataType;
  28882. serializationObject.keys = [];
  28883. var keys = this.getKeys();
  28884. for (var index = 0; index < keys.length; index++) {
  28885. var animationKey = keys[index];
  28886. var key = {};
  28887. key.frame = animationKey.frame;
  28888. switch (dataType) {
  28889. case Animation.ANIMATIONTYPE_FLOAT:
  28890. key.values = [animationKey.value];
  28891. break;
  28892. case Animation.ANIMATIONTYPE_QUATERNION:
  28893. case Animation.ANIMATIONTYPE_MATRIX:
  28894. case Animation.ANIMATIONTYPE_VECTOR3:
  28895. case Animation.ANIMATIONTYPE_COLOR3:
  28896. key.values = animationKey.value.asArray();
  28897. break;
  28898. }
  28899. serializationObject.keys.push(key);
  28900. }
  28901. serializationObject.ranges = [];
  28902. for (var name in this._ranges) {
  28903. var range = {};
  28904. range.name = name;
  28905. range.from = this._ranges[name].from;
  28906. range.to = this._ranges[name].to;
  28907. serializationObject.ranges.push(range);
  28908. }
  28909. return serializationObject;
  28910. };
  28911. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28912. get: function () {
  28913. return Animation._ANIMATIONTYPE_FLOAT;
  28914. },
  28915. enumerable: true,
  28916. configurable: true
  28917. });
  28918. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28919. get: function () {
  28920. return Animation._ANIMATIONTYPE_VECTOR3;
  28921. },
  28922. enumerable: true,
  28923. configurable: true
  28924. });
  28925. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28926. get: function () {
  28927. return Animation._ANIMATIONTYPE_VECTOR2;
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28933. get: function () {
  28934. return Animation._ANIMATIONTYPE_SIZE;
  28935. },
  28936. enumerable: true,
  28937. configurable: true
  28938. });
  28939. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28940. get: function () {
  28941. return Animation._ANIMATIONTYPE_QUATERNION;
  28942. },
  28943. enumerable: true,
  28944. configurable: true
  28945. });
  28946. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28947. get: function () {
  28948. return Animation._ANIMATIONTYPE_MATRIX;
  28949. },
  28950. enumerable: true,
  28951. configurable: true
  28952. });
  28953. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28954. get: function () {
  28955. return Animation._ANIMATIONTYPE_COLOR3;
  28956. },
  28957. enumerable: true,
  28958. configurable: true
  28959. });
  28960. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28961. get: function () {
  28962. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28963. },
  28964. enumerable: true,
  28965. configurable: true
  28966. });
  28967. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28968. get: function () {
  28969. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28970. },
  28971. enumerable: true,
  28972. configurable: true
  28973. });
  28974. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28975. get: function () {
  28976. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28977. },
  28978. enumerable: true,
  28979. configurable: true
  28980. });
  28981. Animation.Parse = function (parsedAnimation) {
  28982. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28983. var dataType = parsedAnimation.dataType;
  28984. var keys = [];
  28985. var data;
  28986. var index;
  28987. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28988. var key = parsedAnimation.keys[index];
  28989. switch (dataType) {
  28990. case Animation.ANIMATIONTYPE_FLOAT:
  28991. data = key.values[0];
  28992. break;
  28993. case Animation.ANIMATIONTYPE_QUATERNION:
  28994. data = BABYLON.Quaternion.FromArray(key.values);
  28995. break;
  28996. case Animation.ANIMATIONTYPE_MATRIX:
  28997. data = BABYLON.Matrix.FromArray(key.values);
  28998. break;
  28999. case Animation.ANIMATIONTYPE_COLOR3:
  29000. data = BABYLON.Color3.FromArray(key.values);
  29001. break;
  29002. case Animation.ANIMATIONTYPE_VECTOR3:
  29003. default:
  29004. data = BABYLON.Vector3.FromArray(key.values);
  29005. break;
  29006. }
  29007. keys.push({
  29008. frame: key.frame,
  29009. value: data
  29010. });
  29011. }
  29012. animation.setKeys(keys);
  29013. if (parsedAnimation.ranges) {
  29014. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29015. data = parsedAnimation.ranges[index];
  29016. animation.createRange(data.name, data.from, data.to);
  29017. }
  29018. }
  29019. return animation;
  29020. };
  29021. Animation.AppendSerializedAnimations = function (source, destination) {
  29022. if (source.animations) {
  29023. destination.animations = [];
  29024. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29025. var animation = source.animations[animationIndex];
  29026. destination.animations.push(animation.serialize());
  29027. }
  29028. }
  29029. };
  29030. // Statics
  29031. Animation._ANIMATIONTYPE_FLOAT = 0;
  29032. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29033. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29034. Animation._ANIMATIONTYPE_MATRIX = 3;
  29035. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29036. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29037. Animation._ANIMATIONTYPE_SIZE = 6;
  29038. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29039. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29040. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29041. return Animation;
  29042. }());
  29043. BABYLON.Animation = Animation;
  29044. })(BABYLON || (BABYLON = {}));
  29045. var BABYLON;
  29046. (function (BABYLON) {
  29047. var Animatable = (function () {
  29048. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29049. if (fromFrame === void 0) { fromFrame = 0; }
  29050. if (toFrame === void 0) { toFrame = 100; }
  29051. if (loopAnimation === void 0) { loopAnimation = false; }
  29052. if (speedRatio === void 0) { speedRatio = 1.0; }
  29053. this.target = target;
  29054. this.fromFrame = fromFrame;
  29055. this.toFrame = toFrame;
  29056. this.loopAnimation = loopAnimation;
  29057. this.speedRatio = speedRatio;
  29058. this.onAnimationEnd = onAnimationEnd;
  29059. this._animations = new Array();
  29060. this._paused = false;
  29061. this.animationStarted = false;
  29062. if (animations) {
  29063. this.appendAnimations(target, animations);
  29064. }
  29065. this._scene = scene;
  29066. scene._activeAnimatables.push(this);
  29067. }
  29068. // Methods
  29069. Animatable.prototype.getAnimations = function () {
  29070. return this._animations;
  29071. };
  29072. Animatable.prototype.appendAnimations = function (target, animations) {
  29073. for (var index = 0; index < animations.length; index++) {
  29074. var animation = animations[index];
  29075. animation._target = target;
  29076. this._animations.push(animation);
  29077. }
  29078. };
  29079. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29080. var animations = this._animations;
  29081. for (var index = 0; index < animations.length; index++) {
  29082. if (animations[index].targetProperty === property) {
  29083. return animations[index];
  29084. }
  29085. }
  29086. return null;
  29087. };
  29088. Animatable.prototype.reset = function () {
  29089. var animations = this._animations;
  29090. for (var index = 0; index < animations.length; index++) {
  29091. animations[index].reset();
  29092. }
  29093. this._localDelayOffset = null;
  29094. this._pausedDelay = null;
  29095. };
  29096. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29097. var animations = this._animations;
  29098. for (var index = 0; index < animations.length; index++) {
  29099. animations[index].enableBlending = true;
  29100. animations[index].blendingSpeed = blendingSpeed;
  29101. }
  29102. };
  29103. Animatable.prototype.disableBlending = function () {
  29104. var animations = this._animations;
  29105. for (var index = 0; index < animations.length; index++) {
  29106. animations[index].enableBlending = false;
  29107. }
  29108. };
  29109. Animatable.prototype.goToFrame = function (frame) {
  29110. var animations = this._animations;
  29111. if (animations[0]) {
  29112. var fps = animations[0].framePerSecond;
  29113. var currentFrame = animations[0].currentFrame;
  29114. var adjustTime = frame - currentFrame;
  29115. var delay = adjustTime * 1000 / fps;
  29116. this._localDelayOffset -= delay;
  29117. }
  29118. for (var index = 0; index < animations.length; index++) {
  29119. animations[index].goToFrame(frame);
  29120. }
  29121. };
  29122. Animatable.prototype.pause = function () {
  29123. if (this._paused) {
  29124. return;
  29125. }
  29126. this._paused = true;
  29127. };
  29128. Animatable.prototype.restart = function () {
  29129. this._paused = false;
  29130. };
  29131. Animatable.prototype.stop = function (animationName) {
  29132. var index = this._scene._activeAnimatables.indexOf(this);
  29133. if (index > -1) {
  29134. var animations = this._animations;
  29135. var numberOfAnimationsStopped = 0;
  29136. for (var index = animations.length - 1; index >= 0; index--) {
  29137. if (typeof animationName === "string" && animations[index].name != animationName) {
  29138. continue;
  29139. }
  29140. animations[index].reset();
  29141. animations.splice(index, 1);
  29142. numberOfAnimationsStopped++;
  29143. }
  29144. if (animations.length == numberOfAnimationsStopped) {
  29145. this._scene._activeAnimatables.splice(index, 1);
  29146. if (this.onAnimationEnd) {
  29147. this.onAnimationEnd();
  29148. }
  29149. }
  29150. }
  29151. };
  29152. Animatable.prototype._animate = function (delay) {
  29153. if (this._paused) {
  29154. this.animationStarted = false;
  29155. if (!this._pausedDelay) {
  29156. this._pausedDelay = delay;
  29157. }
  29158. return true;
  29159. }
  29160. if (!this._localDelayOffset) {
  29161. this._localDelayOffset = delay;
  29162. }
  29163. else if (this._pausedDelay) {
  29164. this._localDelayOffset += delay - this._pausedDelay;
  29165. this._pausedDelay = null;
  29166. }
  29167. // Animating
  29168. var running = false;
  29169. var animations = this._animations;
  29170. var index;
  29171. for (index = 0; index < animations.length; index++) {
  29172. var animation = animations[index];
  29173. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29174. running = running || isRunning;
  29175. }
  29176. this.animationStarted = running;
  29177. if (!running) {
  29178. // Remove from active animatables
  29179. index = this._scene._activeAnimatables.indexOf(this);
  29180. this._scene._activeAnimatables.splice(index, 1);
  29181. }
  29182. if (!running && this.onAnimationEnd) {
  29183. this.onAnimationEnd();
  29184. this.onAnimationEnd = null;
  29185. }
  29186. return running;
  29187. };
  29188. return Animatable;
  29189. }());
  29190. BABYLON.Animatable = Animatable;
  29191. })(BABYLON || (BABYLON = {}));
  29192. var BABYLON;
  29193. (function (BABYLON) {
  29194. var EasingFunction = (function () {
  29195. function EasingFunction() {
  29196. // Properties
  29197. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29198. }
  29199. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29200. get: function () {
  29201. return EasingFunction._EASINGMODE_EASEIN;
  29202. },
  29203. enumerable: true,
  29204. configurable: true
  29205. });
  29206. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29207. get: function () {
  29208. return EasingFunction._EASINGMODE_EASEOUT;
  29209. },
  29210. enumerable: true,
  29211. configurable: true
  29212. });
  29213. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29214. get: function () {
  29215. return EasingFunction._EASINGMODE_EASEINOUT;
  29216. },
  29217. enumerable: true,
  29218. configurable: true
  29219. });
  29220. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29221. var n = Math.min(Math.max(easingMode, 0), 2);
  29222. this._easingMode = n;
  29223. };
  29224. EasingFunction.prototype.getEasingMode = function () {
  29225. return this._easingMode;
  29226. };
  29227. EasingFunction.prototype.easeInCore = function (gradient) {
  29228. throw new Error('You must implement this method');
  29229. };
  29230. EasingFunction.prototype.ease = function (gradient) {
  29231. switch (this._easingMode) {
  29232. case EasingFunction.EASINGMODE_EASEIN:
  29233. return this.easeInCore(gradient);
  29234. case EasingFunction.EASINGMODE_EASEOUT:
  29235. return (1 - this.easeInCore(1 - gradient));
  29236. }
  29237. if (gradient >= 0.5) {
  29238. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29239. }
  29240. return (this.easeInCore(gradient * 2) * 0.5);
  29241. };
  29242. //Statics
  29243. EasingFunction._EASINGMODE_EASEIN = 0;
  29244. EasingFunction._EASINGMODE_EASEOUT = 1;
  29245. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29246. return EasingFunction;
  29247. }());
  29248. BABYLON.EasingFunction = EasingFunction;
  29249. var CircleEase = (function (_super) {
  29250. __extends(CircleEase, _super);
  29251. function CircleEase() {
  29252. _super.apply(this, arguments);
  29253. }
  29254. CircleEase.prototype.easeInCore = function (gradient) {
  29255. gradient = Math.max(0, Math.min(1, gradient));
  29256. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29257. };
  29258. return CircleEase;
  29259. }(EasingFunction));
  29260. BABYLON.CircleEase = CircleEase;
  29261. var BackEase = (function (_super) {
  29262. __extends(BackEase, _super);
  29263. function BackEase(amplitude) {
  29264. if (amplitude === void 0) { amplitude = 1; }
  29265. _super.call(this);
  29266. this.amplitude = amplitude;
  29267. }
  29268. BackEase.prototype.easeInCore = function (gradient) {
  29269. var num = Math.max(0, this.amplitude);
  29270. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29271. };
  29272. return BackEase;
  29273. }(EasingFunction));
  29274. BABYLON.BackEase = BackEase;
  29275. var BounceEase = (function (_super) {
  29276. __extends(BounceEase, _super);
  29277. function BounceEase(bounces, bounciness) {
  29278. if (bounces === void 0) { bounces = 3; }
  29279. if (bounciness === void 0) { bounciness = 2; }
  29280. _super.call(this);
  29281. this.bounces = bounces;
  29282. this.bounciness = bounciness;
  29283. }
  29284. BounceEase.prototype.easeInCore = function (gradient) {
  29285. var y = Math.max(0.0, this.bounces);
  29286. var bounciness = this.bounciness;
  29287. if (bounciness <= 1.0) {
  29288. bounciness = 1.001;
  29289. }
  29290. var num9 = Math.pow(bounciness, y);
  29291. var num5 = 1.0 - bounciness;
  29292. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29293. var num15 = gradient * num4;
  29294. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29295. var num3 = Math.floor(num65);
  29296. var num13 = num3 + 1.0;
  29297. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29298. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29299. var num7 = (num8 + num12) * 0.5;
  29300. var num6 = gradient - num7;
  29301. var num2 = num7 - num8;
  29302. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29303. };
  29304. return BounceEase;
  29305. }(EasingFunction));
  29306. BABYLON.BounceEase = BounceEase;
  29307. var CubicEase = (function (_super) {
  29308. __extends(CubicEase, _super);
  29309. function CubicEase() {
  29310. _super.apply(this, arguments);
  29311. }
  29312. CubicEase.prototype.easeInCore = function (gradient) {
  29313. return (gradient * gradient * gradient);
  29314. };
  29315. return CubicEase;
  29316. }(EasingFunction));
  29317. BABYLON.CubicEase = CubicEase;
  29318. var ElasticEase = (function (_super) {
  29319. __extends(ElasticEase, _super);
  29320. function ElasticEase(oscillations, springiness) {
  29321. if (oscillations === void 0) { oscillations = 3; }
  29322. if (springiness === void 0) { springiness = 3; }
  29323. _super.call(this);
  29324. this.oscillations = oscillations;
  29325. this.springiness = springiness;
  29326. }
  29327. ElasticEase.prototype.easeInCore = function (gradient) {
  29328. var num2;
  29329. var num3 = Math.max(0.0, this.oscillations);
  29330. var num = Math.max(0.0, this.springiness);
  29331. if (num == 0) {
  29332. num2 = gradient;
  29333. }
  29334. else {
  29335. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29336. }
  29337. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29338. };
  29339. return ElasticEase;
  29340. }(EasingFunction));
  29341. BABYLON.ElasticEase = ElasticEase;
  29342. var ExponentialEase = (function (_super) {
  29343. __extends(ExponentialEase, _super);
  29344. function ExponentialEase(exponent) {
  29345. if (exponent === void 0) { exponent = 2; }
  29346. _super.call(this);
  29347. this.exponent = exponent;
  29348. }
  29349. ExponentialEase.prototype.easeInCore = function (gradient) {
  29350. if (this.exponent <= 0) {
  29351. return gradient;
  29352. }
  29353. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29354. };
  29355. return ExponentialEase;
  29356. }(EasingFunction));
  29357. BABYLON.ExponentialEase = ExponentialEase;
  29358. var PowerEase = (function (_super) {
  29359. __extends(PowerEase, _super);
  29360. function PowerEase(power) {
  29361. if (power === void 0) { power = 2; }
  29362. _super.call(this);
  29363. this.power = power;
  29364. }
  29365. PowerEase.prototype.easeInCore = function (gradient) {
  29366. var y = Math.max(0.0, this.power);
  29367. return Math.pow(gradient, y);
  29368. };
  29369. return PowerEase;
  29370. }(EasingFunction));
  29371. BABYLON.PowerEase = PowerEase;
  29372. var QuadraticEase = (function (_super) {
  29373. __extends(QuadraticEase, _super);
  29374. function QuadraticEase() {
  29375. _super.apply(this, arguments);
  29376. }
  29377. QuadraticEase.prototype.easeInCore = function (gradient) {
  29378. return (gradient * gradient);
  29379. };
  29380. return QuadraticEase;
  29381. }(EasingFunction));
  29382. BABYLON.QuadraticEase = QuadraticEase;
  29383. var QuarticEase = (function (_super) {
  29384. __extends(QuarticEase, _super);
  29385. function QuarticEase() {
  29386. _super.apply(this, arguments);
  29387. }
  29388. QuarticEase.prototype.easeInCore = function (gradient) {
  29389. return (gradient * gradient * gradient * gradient);
  29390. };
  29391. return QuarticEase;
  29392. }(EasingFunction));
  29393. BABYLON.QuarticEase = QuarticEase;
  29394. var QuinticEase = (function (_super) {
  29395. __extends(QuinticEase, _super);
  29396. function QuinticEase() {
  29397. _super.apply(this, arguments);
  29398. }
  29399. QuinticEase.prototype.easeInCore = function (gradient) {
  29400. return (gradient * gradient * gradient * gradient * gradient);
  29401. };
  29402. return QuinticEase;
  29403. }(EasingFunction));
  29404. BABYLON.QuinticEase = QuinticEase;
  29405. var SineEase = (function (_super) {
  29406. __extends(SineEase, _super);
  29407. function SineEase() {
  29408. _super.apply(this, arguments);
  29409. }
  29410. SineEase.prototype.easeInCore = function (gradient) {
  29411. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29412. };
  29413. return SineEase;
  29414. }(EasingFunction));
  29415. BABYLON.SineEase = SineEase;
  29416. var BezierCurveEase = (function (_super) {
  29417. __extends(BezierCurveEase, _super);
  29418. function BezierCurveEase(x1, y1, x2, y2) {
  29419. if (x1 === void 0) { x1 = 0; }
  29420. if (y1 === void 0) { y1 = 0; }
  29421. if (x2 === void 0) { x2 = 1; }
  29422. if (y2 === void 0) { y2 = 1; }
  29423. _super.call(this);
  29424. this.x1 = x1;
  29425. this.y1 = y1;
  29426. this.x2 = x2;
  29427. this.y2 = y2;
  29428. }
  29429. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29430. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29431. };
  29432. return BezierCurveEase;
  29433. }(EasingFunction));
  29434. BABYLON.BezierCurveEase = BezierCurveEase;
  29435. })(BABYLON || (BABYLON = {}));
  29436. var BABYLON;
  29437. (function (BABYLON) {
  29438. var Bone = (function (_super) {
  29439. __extends(Bone, _super);
  29440. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29441. _super.call(this, name, skeleton.getScene());
  29442. this.name = name;
  29443. this.children = new Array();
  29444. this.animations = new Array();
  29445. this._worldTransform = new BABYLON.Matrix();
  29446. this._absoluteTransform = new BABYLON.Matrix();
  29447. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29448. this._scaleMatrix = BABYLON.Matrix.Identity();
  29449. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  29450. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  29451. this._syncScaleVector = function () {
  29452. var lm = this.getLocalMatrix();
  29453. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  29454. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  29455. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  29456. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  29457. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  29458. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  29459. this._scaleVector.x = xs * Math.sqrt(xsq);
  29460. this._scaleVector.y = ys * Math.sqrt(ysq);
  29461. this._scaleVector.z = zs * Math.sqrt(zsq);
  29462. if (this._parent) {
  29463. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  29464. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  29465. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  29466. }
  29467. };
  29468. this._skeleton = skeleton;
  29469. this._matrix = matrix;
  29470. this._baseMatrix = matrix;
  29471. this._restPose = restPose ? restPose : matrix.clone();
  29472. skeleton.bones.push(this);
  29473. if (parentBone) {
  29474. this._parent = parentBone;
  29475. parentBone.children.push(this);
  29476. }
  29477. else {
  29478. this._parent = null;
  29479. }
  29480. this._updateDifferenceMatrix();
  29481. }
  29482. // Members
  29483. Bone.prototype.getParent = function () {
  29484. return this._parent;
  29485. };
  29486. Bone.prototype.getLocalMatrix = function () {
  29487. return this._matrix;
  29488. };
  29489. Bone.prototype.getBaseMatrix = function () {
  29490. return this._baseMatrix;
  29491. };
  29492. Bone.prototype.getRestPose = function () {
  29493. return this._restPose;
  29494. };
  29495. Bone.prototype.returnToRest = function () {
  29496. this.updateMatrix(this._restPose.clone());
  29497. };
  29498. Bone.prototype.getWorldMatrix = function () {
  29499. return this._worldTransform;
  29500. };
  29501. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29502. return this._invertedAbsoluteTransform;
  29503. };
  29504. Bone.prototype.getAbsoluteTransform = function () {
  29505. return this._absoluteTransform;
  29506. };
  29507. // Methods
  29508. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29509. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29510. this._baseMatrix = matrix.clone();
  29511. this._matrix = matrix.clone();
  29512. this._skeleton._markAsDirty();
  29513. if (updateDifferenceMatrix) {
  29514. this._updateDifferenceMatrix();
  29515. }
  29516. };
  29517. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29518. if (!rootMatrix) {
  29519. rootMatrix = this._baseMatrix;
  29520. }
  29521. if (this._parent) {
  29522. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29523. }
  29524. else {
  29525. this._absoluteTransform.copyFrom(rootMatrix);
  29526. }
  29527. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29528. for (var index = 0; index < this.children.length; index++) {
  29529. this.children[index]._updateDifferenceMatrix();
  29530. }
  29531. };
  29532. Bone.prototype.markAsDirty = function () {
  29533. this._currentRenderId++;
  29534. this._skeleton._markAsDirty();
  29535. };
  29536. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29537. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29538. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29539. // all animation may be coming from a library skeleton, so may need to create animation
  29540. if (this.animations.length === 0) {
  29541. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29542. this.animations[0].setKeys([]);
  29543. }
  29544. // get animation info / verify there is such a range from the source bone
  29545. var sourceRange = source.animations[0].getRange(rangeName);
  29546. if (!sourceRange) {
  29547. return false;
  29548. }
  29549. var from = sourceRange.from;
  29550. var to = sourceRange.to;
  29551. var sourceKeys = source.animations[0].getKeys();
  29552. // rescaling prep
  29553. var sourceBoneLength = source.length;
  29554. var sourceParent = source.getParent();
  29555. var parent = this.getParent();
  29556. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29557. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29558. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29559. var destKeys = this.animations[0].getKeys();
  29560. // loop vars declaration
  29561. var orig;
  29562. var origTranslation;
  29563. var mat;
  29564. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29565. orig = sourceKeys[key];
  29566. if (orig.frame >= from && orig.frame <= to) {
  29567. if (rescaleAsRequired) {
  29568. mat = orig.value.clone();
  29569. // scale based on parent ratio, when bone has parent
  29570. if (parentScalingReqd) {
  29571. origTranslation = mat.getTranslation();
  29572. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29573. }
  29574. else if (dimensionsScalingReqd) {
  29575. origTranslation = mat.getTranslation();
  29576. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29577. }
  29578. else {
  29579. mat = orig.value;
  29580. }
  29581. }
  29582. else {
  29583. mat = orig.value;
  29584. }
  29585. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29586. }
  29587. }
  29588. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29589. return true;
  29590. };
  29591. Bone.prototype.translate = function (vec) {
  29592. var lm = this.getLocalMatrix();
  29593. lm.m[12] += vec.x;
  29594. lm.m[13] += vec.y;
  29595. lm.m[14] += vec.z;
  29596. this.markAsDirty();
  29597. };
  29598. Bone.prototype.setPosition = function (position) {
  29599. var lm = this.getLocalMatrix();
  29600. lm.m[12] = position.x;
  29601. lm.m[13] = position.y;
  29602. lm.m[14] = position.z;
  29603. this.markAsDirty();
  29604. };
  29605. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  29606. if (mesh === void 0) { mesh = null; }
  29607. this._skeleton.computeAbsoluteTransforms();
  29608. var tmat = BABYLON.Tmp.Matrix[0];
  29609. var vec = BABYLON.Tmp.Vector3[0];
  29610. if (mesh) {
  29611. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29612. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29613. }
  29614. else {
  29615. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29616. }
  29617. tmat.invert();
  29618. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  29619. var lm = this.getLocalMatrix();
  29620. lm.m[12] = vec.x;
  29621. lm.m[13] = vec.y;
  29622. lm.m[14] = vec.z;
  29623. this.markAsDirty();
  29624. };
  29625. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  29626. if (scaleChildren === void 0) { scaleChildren = false; }
  29627. if (this.animations[0] && !this.animations[0].isStopped()) {
  29628. if (!scaleChildren) {
  29629. this._negateScaleChildren.x = 1 / x;
  29630. this._negateScaleChildren.y = 1 / y;
  29631. this._negateScaleChildren.z = 1 / z;
  29632. }
  29633. this._syncScaleVector();
  29634. }
  29635. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  29636. };
  29637. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  29638. if (scaleChildren === void 0) { scaleChildren = false; }
  29639. var locMat = this.getLocalMatrix();
  29640. var origLocMat = BABYLON.Tmp.Matrix[0];
  29641. origLocMat.copyFrom(locMat);
  29642. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  29643. origLocMatInv.copyFrom(origLocMat);
  29644. origLocMatInv.invert();
  29645. var scaleMat = BABYLON.Tmp.Matrix[2];
  29646. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  29647. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  29648. this._scaleVector.x *= x;
  29649. this._scaleVector.y *= y;
  29650. this._scaleVector.z *= z;
  29651. locMat.multiplyToRef(origLocMatInv, locMat);
  29652. locMat.multiplyToRef(scaleMat, locMat);
  29653. locMat.multiplyToRef(origLocMat, locMat);
  29654. var parent = this.getParent();
  29655. if (parent) {
  29656. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  29657. }
  29658. else {
  29659. this.getAbsoluteTransform().copyFrom(locMat);
  29660. }
  29661. var len = this.children.length;
  29662. scaleMat.invert();
  29663. for (var i = 0; i < len; i++) {
  29664. var child = this.children[i];
  29665. var cm = child.getLocalMatrix();
  29666. cm.multiplyToRef(scaleMat, cm);
  29667. var lm = child.getLocalMatrix();
  29668. lm.m[12] *= x;
  29669. lm.m[13] *= y;
  29670. lm.m[14] *= z;
  29671. }
  29672. this.computeAbsoluteTransforms();
  29673. if (scaleChildren) {
  29674. for (var i = 0; i < len; i++) {
  29675. this.children[i].scale(x, y, z, scaleChildren);
  29676. }
  29677. }
  29678. this.markAsDirty();
  29679. };
  29680. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  29681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29682. if (mesh === void 0) { mesh = null; }
  29683. var rotMat = BABYLON.Tmp.Matrix[0];
  29684. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  29685. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29686. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29687. rotMatInv.multiplyToRef(rotMat, rotMat);
  29688. this._rotateWithMatrix(rotMat, space, mesh);
  29689. };
  29690. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  29691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29692. if (mesh === void 0) { mesh = null; }
  29693. var rmat = BABYLON.Tmp.Matrix[0];
  29694. rmat.m[12] = 0;
  29695. rmat.m[13] = 0;
  29696. rmat.m[14] = 0;
  29697. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  29698. this._rotateWithMatrix(rmat, space, mesh);
  29699. };
  29700. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  29701. var rotMat = BABYLON.Tmp.Matrix[0];
  29702. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  29703. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29704. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29705. rotMatInv.multiplyToRef(rotMat, rotMat);
  29706. this._rotateWithMatrix(rotMat, space, mesh);
  29707. };
  29708. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  29709. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29710. if (mesh === void 0) { mesh = null; }
  29711. var lmat = this.getLocalMatrix();
  29712. var lx = lmat.m[12];
  29713. var ly = lmat.m[13];
  29714. var lz = lmat.m[14];
  29715. var parent = this.getParent();
  29716. var parentScale = BABYLON.Tmp.Matrix[3];
  29717. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  29718. if (parent) {
  29719. if (space == BABYLON.Space.WORLD) {
  29720. if (mesh) {
  29721. parentScale.copyFrom(mesh.getWorldMatrix());
  29722. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  29723. }
  29724. else {
  29725. parentScale.copyFrom(parent.getAbsoluteTransform());
  29726. }
  29727. }
  29728. else {
  29729. parentScale = parent._scaleMatrix;
  29730. }
  29731. parentScaleInv.copyFrom(parentScale);
  29732. parentScaleInv.invert();
  29733. lmat.multiplyToRef(parentScale, lmat);
  29734. lmat.multiplyToRef(rmat, lmat);
  29735. lmat.multiplyToRef(parentScaleInv, lmat);
  29736. }
  29737. else {
  29738. if (space == BABYLON.Space.WORLD && mesh) {
  29739. parentScale.copyFrom(mesh.getWorldMatrix());
  29740. parentScaleInv.copyFrom(parentScale);
  29741. parentScaleInv.invert();
  29742. lmat.multiplyToRef(parentScale, lmat);
  29743. lmat.multiplyToRef(rmat, lmat);
  29744. lmat.multiplyToRef(parentScaleInv, lmat);
  29745. }
  29746. else {
  29747. lmat.multiplyToRef(rmat, lmat);
  29748. }
  29749. }
  29750. lmat.m[12] = lx;
  29751. lmat.m[13] = ly;
  29752. lmat.m[14] = lz;
  29753. this.computeAbsoluteTransforms();
  29754. this.markAsDirty();
  29755. };
  29756. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  29757. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29758. if (mesh === void 0) { mesh = null; }
  29759. if (space == BABYLON.Space.WORLD) {
  29760. rotMatInv.copyFrom(this.getAbsoluteTransform());
  29761. if (mesh) {
  29762. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  29763. }
  29764. rotMatInv.invert();
  29765. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29766. scaleMatrix.copyFrom(this._scaleMatrix);
  29767. scaleMatrix.m[0] *= -1;
  29768. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29769. }
  29770. else {
  29771. rotMatInv.copyFrom(this.getLocalMatrix());
  29772. rotMatInv.invert();
  29773. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29774. scaleMatrix.copyFrom(this._scaleMatrix);
  29775. if (this._parent) {
  29776. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  29777. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  29778. pscaleMatrix.invert();
  29779. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  29780. }
  29781. else {
  29782. scaleMatrix.m[0] *= -1;
  29783. }
  29784. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29785. }
  29786. };
  29787. Bone.prototype.getScale = function () {
  29788. return this._scaleVector.clone();
  29789. };
  29790. Bone.prototype.getScaleToRef = function (result) {
  29791. result.copyFrom(this._scaleVector);
  29792. };
  29793. Bone.prototype.getAbsolutePosition = function (mesh) {
  29794. if (mesh === void 0) { mesh = null; }
  29795. var pos = BABYLON.Vector3.Zero();
  29796. this.getAbsolutePositionToRef(mesh, pos);
  29797. return pos;
  29798. };
  29799. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  29800. if (mesh === void 0) { mesh = null; }
  29801. this._skeleton.computeAbsoluteTransforms();
  29802. var tmat = BABYLON.Tmp.Matrix[0];
  29803. if (mesh) {
  29804. tmat.copyFrom(this.getAbsoluteTransform());
  29805. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29806. }
  29807. else {
  29808. tmat = this.getAbsoluteTransform();
  29809. }
  29810. result.x = tmat.m[12];
  29811. result.y = tmat.m[13];
  29812. result.z = tmat.m[14];
  29813. };
  29814. Bone.prototype.computeAbsoluteTransforms = function () {
  29815. if (this._parent) {
  29816. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29817. }
  29818. else {
  29819. this._absoluteTransform.copyFrom(this._matrix);
  29820. }
  29821. var children = this.children;
  29822. var len = children.length;
  29823. for (var i = 0; i < len; i++) {
  29824. children[i].computeAbsoluteTransforms();
  29825. }
  29826. };
  29827. return Bone;
  29828. }(BABYLON.Node));
  29829. BABYLON.Bone = Bone;
  29830. })(BABYLON || (BABYLON = {}));
  29831. var BABYLON;
  29832. (function (BABYLON) {
  29833. var Skeleton = (function () {
  29834. function Skeleton(name, id, scene) {
  29835. this.name = name;
  29836. this.id = id;
  29837. this.bones = new Array();
  29838. this.needInitialSkinMatrix = false;
  29839. this._isDirty = true;
  29840. this._meshesWithPoseMatrix = new Array();
  29841. this._identity = BABYLON.Matrix.Identity();
  29842. this._ranges = {};
  29843. this._lastAbsoluteTransformsUpdateId = -1;
  29844. this.bones = [];
  29845. this._scene = scene;
  29846. scene.skeletons.push(this);
  29847. //make sure it will recalculate the matrix next time prepare is called.
  29848. this._isDirty = true;
  29849. }
  29850. // Members
  29851. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29852. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29853. return mesh._bonesTransformMatrices;
  29854. }
  29855. return this._transformMatrices;
  29856. };
  29857. Skeleton.prototype.getScene = function () {
  29858. return this._scene;
  29859. };
  29860. // Methods
  29861. /**
  29862. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29863. */
  29864. Skeleton.prototype.toString = function (fullDetails) {
  29865. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29866. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29867. if (fullDetails) {
  29868. ret += ", Ranges: {";
  29869. var first = true;
  29870. for (var name_1 in this._ranges) {
  29871. if (first) {
  29872. ret += ", ";
  29873. first = false;
  29874. }
  29875. ret += name_1;
  29876. }
  29877. ret += "}";
  29878. }
  29879. return ret;
  29880. };
  29881. /**
  29882. * Get bone's index searching by name
  29883. * @param {string} name is bone's name to search for
  29884. * @return {number} Indice of the bone. Returns -1 if not found
  29885. */
  29886. Skeleton.prototype.getBoneIndexByName = function (name) {
  29887. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29888. if (this.bones[boneIndex].name === name) {
  29889. return boneIndex;
  29890. }
  29891. }
  29892. return -1;
  29893. };
  29894. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29895. // check name not already in use
  29896. if (!this._ranges[name]) {
  29897. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29898. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29899. if (this.bones[i].animations[0]) {
  29900. this.bones[i].animations[0].createRange(name, from, to);
  29901. }
  29902. }
  29903. }
  29904. };
  29905. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29906. if (deleteFrames === void 0) { deleteFrames = true; }
  29907. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29908. if (this.bones[i].animations[0]) {
  29909. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29910. }
  29911. }
  29912. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29913. };
  29914. Skeleton.prototype.getAnimationRange = function (name) {
  29915. return this._ranges[name];
  29916. };
  29917. /**
  29918. * Returns as an Array, all AnimationRanges defined on this skeleton
  29919. */
  29920. Skeleton.prototype.getAnimationRanges = function () {
  29921. var animationRanges = [];
  29922. var name;
  29923. var i = 0;
  29924. for (name in this._ranges) {
  29925. animationRanges[i] = this._ranges[name];
  29926. i++;
  29927. }
  29928. return animationRanges;
  29929. };
  29930. /**
  29931. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29932. */
  29933. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29934. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29935. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29936. return false;
  29937. }
  29938. var ret = true;
  29939. var frameOffset = this._getHighestAnimationFrame() + 1;
  29940. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29941. var boneDict = {};
  29942. var sourceBones = source.bones;
  29943. var nBones;
  29944. var i;
  29945. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29946. boneDict[sourceBones[i].name] = sourceBones[i];
  29947. }
  29948. if (this.bones.length !== sourceBones.length) {
  29949. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29950. ret = false;
  29951. }
  29952. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29953. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29954. var boneName = this.bones[i].name;
  29955. var sourceBone = boneDict[boneName];
  29956. if (sourceBone) {
  29957. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29958. }
  29959. else {
  29960. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29961. ret = false;
  29962. }
  29963. }
  29964. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29965. var range = source.getAnimationRange(name);
  29966. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29967. return ret;
  29968. };
  29969. Skeleton.prototype.returnToRest = function () {
  29970. for (var index = 0; index < this.bones.length; index++) {
  29971. this.bones[index].returnToRest();
  29972. }
  29973. };
  29974. Skeleton.prototype._getHighestAnimationFrame = function () {
  29975. var ret = 0;
  29976. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29977. if (this.bones[i].animations[0]) {
  29978. var highest = this.bones[i].animations[0].getHighestFrame();
  29979. if (ret < highest) {
  29980. ret = highest;
  29981. }
  29982. }
  29983. }
  29984. return ret;
  29985. };
  29986. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29987. var range = this.getAnimationRange(name);
  29988. if (!range) {
  29989. return null;
  29990. }
  29991. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29992. };
  29993. Skeleton.prototype._markAsDirty = function () {
  29994. this._isDirty = true;
  29995. };
  29996. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29997. this._meshesWithPoseMatrix.push(mesh);
  29998. };
  29999. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  30000. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  30001. if (index > -1) {
  30002. this._meshesWithPoseMatrix.splice(index, 1);
  30003. }
  30004. };
  30005. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  30006. for (var index = 0; index < this.bones.length; index++) {
  30007. var bone = this.bones[index];
  30008. var parentBone = bone.getParent();
  30009. if (parentBone) {
  30010. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  30011. }
  30012. else {
  30013. if (initialSkinMatrix) {
  30014. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  30015. }
  30016. else {
  30017. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  30018. }
  30019. }
  30020. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  30021. }
  30022. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  30023. };
  30024. Skeleton.prototype.prepare = function () {
  30025. if (!this._isDirty) {
  30026. return;
  30027. }
  30028. if (this.needInitialSkinMatrix) {
  30029. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  30030. var mesh = this._meshesWithPoseMatrix[index];
  30031. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  30032. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30033. }
  30034. var poseMatrix = mesh.getPoseMatrix();
  30035. // Prepare bones
  30036. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  30037. var bone = this.bones[boneIndex];
  30038. if (!bone.getParent()) {
  30039. var matrix = bone.getBaseMatrix();
  30040. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  30041. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  30042. }
  30043. }
  30044. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  30045. }
  30046. }
  30047. else {
  30048. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  30049. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30050. }
  30051. this._computeTransformMatrices(this._transformMatrices, null);
  30052. }
  30053. this._isDirty = false;
  30054. this._scene._activeBones.addCount(this.bones.length, false);
  30055. };
  30056. Skeleton.prototype.getAnimatables = function () {
  30057. if (!this._animatables || this._animatables.length !== this.bones.length) {
  30058. this._animatables = [];
  30059. for (var index = 0; index < this.bones.length; index++) {
  30060. this._animatables.push(this.bones[index]);
  30061. }
  30062. }
  30063. return this._animatables;
  30064. };
  30065. Skeleton.prototype.clone = function (name, id) {
  30066. var result = new Skeleton(name, id || name, this._scene);
  30067. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30068. for (var index = 0; index < this.bones.length; index++) {
  30069. var source = this.bones[index];
  30070. var parentBone = null;
  30071. if (source.getParent()) {
  30072. var parentIndex = this.bones.indexOf(source.getParent());
  30073. parentBone = result.bones[parentIndex];
  30074. }
  30075. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  30076. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  30077. }
  30078. if (this._ranges) {
  30079. result._ranges = {};
  30080. for (var rangeName in this._ranges) {
  30081. result._ranges[rangeName] = this._ranges[rangeName].clone();
  30082. }
  30083. }
  30084. this._isDirty = true;
  30085. return result;
  30086. };
  30087. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  30088. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  30089. this.bones.forEach(function (bone) {
  30090. bone.animations.forEach(function (animation) {
  30091. animation.enableBlending = true;
  30092. animation.blendingSpeed = blendingSpeed;
  30093. });
  30094. });
  30095. };
  30096. Skeleton.prototype.dispose = function () {
  30097. this._meshesWithPoseMatrix = [];
  30098. // Animations
  30099. this.getScene().stopAnimation(this);
  30100. // Remove from scene
  30101. this.getScene().removeSkeleton(this);
  30102. };
  30103. Skeleton.prototype.serialize = function () {
  30104. var serializationObject = {};
  30105. serializationObject.name = this.name;
  30106. serializationObject.id = this.id;
  30107. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  30108. serializationObject.bones = [];
  30109. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30110. for (var index = 0; index < this.bones.length; index++) {
  30111. var bone = this.bones[index];
  30112. var serializedBone = {
  30113. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  30114. name: bone.name,
  30115. matrix: bone.getLocalMatrix().toArray(),
  30116. rest: bone.getRestPose().toArray()
  30117. };
  30118. serializationObject.bones.push(serializedBone);
  30119. if (bone.length) {
  30120. serializedBone.length = bone.length;
  30121. }
  30122. if (bone.animations && bone.animations.length > 0) {
  30123. serializedBone.animation = bone.animations[0].serialize();
  30124. }
  30125. serializationObject.ranges = [];
  30126. for (var name in this._ranges) {
  30127. var range = {};
  30128. range.name = name;
  30129. range.from = this._ranges[name].from;
  30130. range.to = this._ranges[name].to;
  30131. serializationObject.ranges.push(range);
  30132. }
  30133. }
  30134. return serializationObject;
  30135. };
  30136. Skeleton.Parse = function (parsedSkeleton, scene) {
  30137. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  30138. if (parsedSkeleton.dimensionsAtRest) {
  30139. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  30140. }
  30141. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  30142. var index;
  30143. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  30144. var parsedBone = parsedSkeleton.bones[index];
  30145. var parentBone = null;
  30146. if (parsedBone.parentBoneIndex > -1) {
  30147. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  30148. }
  30149. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  30150. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  30151. if (parsedBone.length) {
  30152. bone.length = parsedBone.length;
  30153. }
  30154. if (parsedBone.animation) {
  30155. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  30156. }
  30157. }
  30158. // placed after bones, so createAnimationRange can cascade down
  30159. if (parsedSkeleton.ranges) {
  30160. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  30161. var data = parsedSkeleton.ranges[index];
  30162. skeleton.createAnimationRange(data.name, data.from, data.to);
  30163. }
  30164. }
  30165. return skeleton;
  30166. };
  30167. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  30168. if (forceUpdate === void 0) { forceUpdate = false; }
  30169. var renderId = this._scene.getRenderId();
  30170. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  30171. this.bones[0].computeAbsoluteTransforms();
  30172. this._lastAbsoluteTransformsUpdateId = renderId;
  30173. }
  30174. };
  30175. return Skeleton;
  30176. }());
  30177. BABYLON.Skeleton = Skeleton;
  30178. })(BABYLON || (BABYLON = {}));
  30179. var BABYLON;
  30180. (function (BABYLON) {
  30181. var PostProcess = (function () {
  30182. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  30183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  30184. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30185. this.name = name;
  30186. this.width = -1;
  30187. this.height = -1;
  30188. /*
  30189. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  30190. Can only be used on a single postprocess or on the last one of a chain.
  30191. */
  30192. this.enablePixelPerfectMode = false;
  30193. this._reusable = false;
  30194. this._textures = new BABYLON.SmartArray(2);
  30195. this._currentRenderTextureInd = 0;
  30196. this._scaleRatio = new BABYLON.Vector2(1, 1);
  30197. // Events
  30198. /**
  30199. * An event triggered when the postprocess is activated.
  30200. * @type {BABYLON.Observable}
  30201. */
  30202. this.onActivateObservable = new BABYLON.Observable();
  30203. /**
  30204. * An event triggered when the postprocess changes its size.
  30205. * @type {BABYLON.Observable}
  30206. */
  30207. this.onSizeChangedObservable = new BABYLON.Observable();
  30208. /**
  30209. * An event triggered when the postprocess applies its effect.
  30210. * @type {BABYLON.Observable}
  30211. */
  30212. this.onApplyObservable = new BABYLON.Observable();
  30213. /**
  30214. * An event triggered before rendering the postprocess
  30215. * @type {BABYLON.Observable}
  30216. */
  30217. this.onBeforeRenderObservable = new BABYLON.Observable();
  30218. /**
  30219. * An event triggered after rendering the postprocess
  30220. * @type {BABYLON.Observable}
  30221. */
  30222. this.onAfterRenderObservable = new BABYLON.Observable();
  30223. if (camera != null) {
  30224. this._camera = camera;
  30225. this._scene = camera.getScene();
  30226. camera.attachPostProcess(this);
  30227. this._engine = this._scene.getEngine();
  30228. }
  30229. else {
  30230. this._engine = engine;
  30231. }
  30232. this._options = options;
  30233. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  30234. this._reusable = reusable || false;
  30235. this._textureType = textureType;
  30236. this._samplers = samplers || [];
  30237. this._samplers.push("textureSampler");
  30238. this._fragmentUrl = fragmentUrl;
  30239. this._parameters = parameters || [];
  30240. this._parameters.push("scale");
  30241. this.updateEffect(defines);
  30242. }
  30243. Object.defineProperty(PostProcess.prototype, "onActivate", {
  30244. set: function (callback) {
  30245. if (this._onActivateObserver) {
  30246. this.onActivateObservable.remove(this._onActivateObserver);
  30247. }
  30248. this._onActivateObserver = this.onActivateObservable.add(callback);
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  30254. set: function (callback) {
  30255. if (this._onSizeChangedObserver) {
  30256. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  30257. }
  30258. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(PostProcess.prototype, "onApply", {
  30264. set: function (callback) {
  30265. if (this._onApplyObserver) {
  30266. this.onApplyObservable.remove(this._onApplyObserver);
  30267. }
  30268. this._onApplyObserver = this.onApplyObservable.add(callback);
  30269. },
  30270. enumerable: true,
  30271. configurable: true
  30272. });
  30273. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  30274. set: function (callback) {
  30275. if (this._onBeforeRenderObserver) {
  30276. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  30277. }
  30278. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  30279. },
  30280. enumerable: true,
  30281. configurable: true
  30282. });
  30283. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  30284. set: function (callback) {
  30285. if (this._onAfterRenderObserver) {
  30286. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  30287. }
  30288. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  30289. },
  30290. enumerable: true,
  30291. configurable: true
  30292. });
  30293. PostProcess.prototype.updateEffect = function (defines) {
  30294. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  30295. };
  30296. PostProcess.prototype.isReusable = function () {
  30297. return this._reusable;
  30298. };
  30299. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  30300. PostProcess.prototype.markTextureDirty = function () {
  30301. this.width = -1;
  30302. };
  30303. PostProcess.prototype.activate = function (camera, sourceTexture) {
  30304. camera = camera || this._camera;
  30305. var scene = camera.getScene();
  30306. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  30307. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  30308. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  30309. var desiredWidth = this._options.width || requiredWidth;
  30310. var desiredHeight = this._options.height || requiredHeight;
  30311. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  30312. if (!this._options.width) {
  30313. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  30314. }
  30315. if (!this._options.height) {
  30316. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  30317. }
  30318. }
  30319. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  30320. if (this._textures.length > 0) {
  30321. for (var i = 0; i < this._textures.length; i++) {
  30322. this._engine._releaseTexture(this._textures.data[i]);
  30323. }
  30324. this._textures.reset();
  30325. }
  30326. this.width = desiredWidth;
  30327. this.height = desiredHeight;
  30328. var textureSize = { width: this.width, height: this.height };
  30329. var textureOptions = {
  30330. generateMipMaps: false,
  30331. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  30332. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  30333. samplingMode: this.renderTargetSamplingMode,
  30334. type: this._textureType
  30335. };
  30336. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30337. if (this._reusable) {
  30338. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30339. }
  30340. this.onSizeChangedObservable.notifyObservers(this);
  30341. }
  30342. if (this.enablePixelPerfectMode) {
  30343. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  30344. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  30345. }
  30346. else {
  30347. this._scaleRatio.copyFromFloats(1, 1);
  30348. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  30349. }
  30350. this.onActivateObservable.notifyObservers(camera);
  30351. // Clear
  30352. if (this.clearColor) {
  30353. this._engine.clear(this.clearColor, true, true, true);
  30354. }
  30355. else {
  30356. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  30357. }
  30358. if (this._reusable) {
  30359. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  30360. }
  30361. };
  30362. Object.defineProperty(PostProcess.prototype, "isSupported", {
  30363. get: function () {
  30364. return this._effect.isSupported;
  30365. },
  30366. enumerable: true,
  30367. configurable: true
  30368. });
  30369. PostProcess.prototype.apply = function () {
  30370. // Check
  30371. if (!this._effect.isReady())
  30372. return null;
  30373. // States
  30374. this._engine.enableEffect(this._effect);
  30375. this._engine.setState(false);
  30376. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30377. this._engine.setDepthBuffer(false);
  30378. this._engine.setDepthWrite(false);
  30379. // Texture
  30380. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  30381. // Parameters
  30382. this._effect.setVector2("scale", this._scaleRatio);
  30383. this.onApplyObservable.notifyObservers(this._effect);
  30384. return this._effect;
  30385. };
  30386. PostProcess.prototype.dispose = function (camera) {
  30387. camera = camera || this._camera;
  30388. if (this._textures.length > 0) {
  30389. for (var i = 0; i < this._textures.length; i++) {
  30390. this._engine._releaseTexture(this._textures.data[i]);
  30391. }
  30392. this._textures.reset();
  30393. }
  30394. if (!camera) {
  30395. return;
  30396. }
  30397. camera.detachPostProcess(this);
  30398. var index = camera._postProcesses.indexOf(this);
  30399. if (index === 0 && camera._postProcesses.length > 0) {
  30400. this._camera._postProcesses[0].markTextureDirty();
  30401. }
  30402. this.onActivateObservable.clear();
  30403. this.onAfterRenderObservable.clear();
  30404. this.onApplyObservable.clear();
  30405. this.onBeforeRenderObservable.clear();
  30406. this.onSizeChangedObservable.clear();
  30407. };
  30408. return PostProcess;
  30409. }());
  30410. BABYLON.PostProcess = PostProcess;
  30411. })(BABYLON || (BABYLON = {}));
  30412. var BABYLON;
  30413. (function (BABYLON) {
  30414. var PostProcessManager = (function () {
  30415. function PostProcessManager(scene) {
  30416. this._vertexBuffers = {};
  30417. this._scene = scene;
  30418. }
  30419. PostProcessManager.prototype._prepareBuffers = function () {
  30420. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30421. return;
  30422. }
  30423. // VBO
  30424. var vertices = [];
  30425. vertices.push(1, 1);
  30426. vertices.push(-1, 1);
  30427. vertices.push(-1, -1);
  30428. vertices.push(1, -1);
  30429. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30430. // Indices
  30431. var indices = [];
  30432. indices.push(0);
  30433. indices.push(1);
  30434. indices.push(2);
  30435. indices.push(0);
  30436. indices.push(2);
  30437. indices.push(3);
  30438. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30439. };
  30440. // Methods
  30441. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  30442. var postProcesses = this._scene.activeCamera._postProcesses;
  30443. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30444. return false;
  30445. }
  30446. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  30447. return true;
  30448. };
  30449. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  30450. var engine = this._scene.getEngine();
  30451. for (var index = 0; index < postProcesses.length; index++) {
  30452. if (index < postProcesses.length - 1) {
  30453. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30454. }
  30455. else {
  30456. if (targetTexture) {
  30457. engine.bindFramebuffer(targetTexture);
  30458. }
  30459. else {
  30460. engine.restoreDefaultFramebuffer();
  30461. }
  30462. }
  30463. var pp = postProcesses[index];
  30464. var effect = pp.apply();
  30465. if (effect) {
  30466. pp.onBeforeRenderObservable.notifyObservers(effect);
  30467. // VBOs
  30468. this._prepareBuffers();
  30469. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30470. // Draw order
  30471. engine.draw(true, 0, 6);
  30472. pp.onAfterRenderObservable.notifyObservers(effect);
  30473. }
  30474. }
  30475. // Restore depth buffer
  30476. engine.setDepthBuffer(true);
  30477. engine.setDepthWrite(true);
  30478. };
  30479. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  30480. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30481. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30482. return;
  30483. }
  30484. var engine = this._scene.getEngine();
  30485. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30486. if (index < len - 1) {
  30487. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30488. }
  30489. else {
  30490. if (targetTexture) {
  30491. engine.bindFramebuffer(targetTexture, faceIndex);
  30492. }
  30493. else {
  30494. engine.restoreDefaultFramebuffer();
  30495. }
  30496. }
  30497. if (doNotPresent) {
  30498. break;
  30499. }
  30500. var pp = postProcesses[index];
  30501. var effect = pp.apply();
  30502. if (effect) {
  30503. pp.onBeforeRenderObservable.notifyObservers(effect);
  30504. // VBOs
  30505. this._prepareBuffers();
  30506. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30507. // Draw order
  30508. engine.draw(true, 0, 6);
  30509. pp.onAfterRenderObservable.notifyObservers(effect);
  30510. }
  30511. }
  30512. // Restore depth buffer
  30513. engine.setDepthBuffer(true);
  30514. engine.setDepthWrite(true);
  30515. };
  30516. PostProcessManager.prototype.dispose = function () {
  30517. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30518. if (buffer) {
  30519. buffer.dispose();
  30520. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30521. }
  30522. if (this._indexBuffer) {
  30523. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30524. this._indexBuffer = null;
  30525. }
  30526. };
  30527. return PostProcessManager;
  30528. }());
  30529. BABYLON.PostProcessManager = PostProcessManager;
  30530. })(BABYLON || (BABYLON = {}));
  30531. var BABYLON;
  30532. (function (BABYLON) {
  30533. var PassPostProcess = (function (_super) {
  30534. __extends(PassPostProcess, _super);
  30535. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  30536. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  30537. }
  30538. return PassPostProcess;
  30539. }(BABYLON.PostProcess));
  30540. BABYLON.PassPostProcess = PassPostProcess;
  30541. })(BABYLON || (BABYLON = {}));
  30542. var BABYLON;
  30543. (function (BABYLON) {
  30544. /**
  30545. * This is a holder class for the physics joint created by the physics plugin.
  30546. * It holds a set of functions to control the underlying joint.
  30547. */
  30548. var PhysicsJoint = (function () {
  30549. function PhysicsJoint(type, jointData) {
  30550. this.type = type;
  30551. this.jointData = jointData;
  30552. jointData.nativeParams = jointData.nativeParams || {};
  30553. }
  30554. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  30555. get: function () {
  30556. return this._physicsJoint;
  30557. },
  30558. set: function (newJoint) {
  30559. if (this._physicsJoint) {
  30560. }
  30561. this._physicsJoint = newJoint;
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30567. set: function (physicsPlugin) {
  30568. this._physicsPlugin = physicsPlugin;
  30569. },
  30570. enumerable: true,
  30571. configurable: true
  30572. });
  30573. /**
  30574. * Execute a function that is physics-plugin specific.
  30575. * @param {Function} func the function that will be executed.
  30576. * It accepts two parameters: the physics world and the physics joint.
  30577. */
  30578. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30579. func(this._physicsPlugin.world, this._physicsJoint);
  30580. };
  30581. //TODO check if the native joints are the same
  30582. //Joint Types
  30583. PhysicsJoint.DistanceJoint = 0;
  30584. PhysicsJoint.HingeJoint = 1;
  30585. PhysicsJoint.BallAndSocketJoint = 2;
  30586. PhysicsJoint.WheelJoint = 3;
  30587. PhysicsJoint.SliderJoint = 4;
  30588. //OIMO
  30589. PhysicsJoint.PrismaticJoint = 5;
  30590. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30591. PhysicsJoint.UniversalJoint = 6;
  30592. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30593. //Cannon
  30594. //Similar to a Ball-Joint. Different in params
  30595. PhysicsJoint.PointToPointJoint = 8;
  30596. //Cannon only at the moment
  30597. PhysicsJoint.SpringJoint = 9;
  30598. PhysicsJoint.LockJoint = 10;
  30599. return PhysicsJoint;
  30600. }());
  30601. BABYLON.PhysicsJoint = PhysicsJoint;
  30602. /**
  30603. * A class representing a physics distance joint.
  30604. */
  30605. var DistanceJoint = (function (_super) {
  30606. __extends(DistanceJoint, _super);
  30607. function DistanceJoint(jointData) {
  30608. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30609. }
  30610. /**
  30611. * Update the predefined distance.
  30612. */
  30613. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30614. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30615. };
  30616. return DistanceJoint;
  30617. }(PhysicsJoint));
  30618. BABYLON.DistanceJoint = DistanceJoint;
  30619. var MotorEnabledJoint = (function (_super) {
  30620. __extends(MotorEnabledJoint, _super);
  30621. function MotorEnabledJoint(type, jointData) {
  30622. _super.call(this, type, jointData);
  30623. }
  30624. /**
  30625. * Set the motor values.
  30626. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30627. * @param {number} force the force to apply
  30628. * @param {number} maxForce max force for this motor.
  30629. */
  30630. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30631. this._physicsPlugin.setMotor(this, force, maxForce);
  30632. };
  30633. /**
  30634. * Set the motor's limits.
  30635. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30636. */
  30637. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30638. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30639. };
  30640. return MotorEnabledJoint;
  30641. }(PhysicsJoint));
  30642. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30643. /**
  30644. * This class represents a single hinge physics joint
  30645. */
  30646. var HingeJoint = (function (_super) {
  30647. __extends(HingeJoint, _super);
  30648. function HingeJoint(jointData) {
  30649. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30650. }
  30651. /**
  30652. * Set the motor values.
  30653. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30654. * @param {number} force the force to apply
  30655. * @param {number} maxForce max force for this motor.
  30656. */
  30657. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30658. this._physicsPlugin.setMotor(this, force, maxForce);
  30659. };
  30660. /**
  30661. * Set the motor's limits.
  30662. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30663. */
  30664. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30665. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30666. };
  30667. return HingeJoint;
  30668. }(MotorEnabledJoint));
  30669. BABYLON.HingeJoint = HingeJoint;
  30670. /**
  30671. * This class represents a dual hinge physics joint (same as wheel joint)
  30672. */
  30673. var Hinge2Joint = (function (_super) {
  30674. __extends(Hinge2Joint, _super);
  30675. function Hinge2Joint(jointData) {
  30676. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30677. }
  30678. /**
  30679. * Set the motor values.
  30680. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30681. * @param {number} force the force to apply
  30682. * @param {number} maxForce max force for this motor.
  30683. * @param {motorIndex} the motor's index, 0 or 1.
  30684. */
  30685. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30686. if (motorIndex === void 0) { motorIndex = 0; }
  30687. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30688. };
  30689. /**
  30690. * Set the motor limits.
  30691. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30692. * @param {number} upperLimit the upper limit
  30693. * @param {number} lowerLimit lower limit
  30694. * @param {motorIndex} the motor's index, 0 or 1.
  30695. */
  30696. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30697. if (motorIndex === void 0) { motorIndex = 0; }
  30698. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30699. };
  30700. return Hinge2Joint;
  30701. }(MotorEnabledJoint));
  30702. BABYLON.Hinge2Joint = Hinge2Joint;
  30703. })(BABYLON || (BABYLON = {}));
  30704. var BABYLON;
  30705. (function (BABYLON) {
  30706. var PhysicsImpostor = (function () {
  30707. function PhysicsImpostor(object, type, _options, _scene) {
  30708. var _this = this;
  30709. if (_options === void 0) { _options = { mass: 0 }; }
  30710. this.object = object;
  30711. this.type = type;
  30712. this._options = _options;
  30713. this._scene = _scene;
  30714. this._bodyUpdateRequired = false;
  30715. this._onBeforePhysicsStepCallbacks = new Array();
  30716. this._onAfterPhysicsStepCallbacks = new Array();
  30717. this._onPhysicsCollideCallbacks = [];
  30718. this._deltaPosition = BABYLON.Vector3.Zero();
  30719. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30720. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30721. /**
  30722. * this function is executed by the physics engine.
  30723. */
  30724. this.beforeStep = function () {
  30725. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30726. //conjugate deltaRotation
  30727. if (_this._deltaRotationConjugated) {
  30728. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30729. }
  30730. else {
  30731. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30732. }
  30733. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30734. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30735. func(_this);
  30736. });
  30737. };
  30738. /**
  30739. * this function is executed by the physics engine.
  30740. */
  30741. this.afterStep = function () {
  30742. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30743. func(_this);
  30744. });
  30745. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30746. _this.object.position.addInPlace(_this._deltaPosition);
  30747. if (_this._deltaRotation) {
  30748. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30749. }
  30750. };
  30751. //event and body object due to cannon's event-based architecture.
  30752. this.onCollide = function (e) {
  30753. if (!_this._onPhysicsCollideCallbacks.length)
  30754. return;
  30755. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30756. if (otherImpostor) {
  30757. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30758. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30759. }).forEach(function (obj) {
  30760. obj.callback(_this, otherImpostor);
  30761. });
  30762. }
  30763. };
  30764. //sanity check!
  30765. if (!this.object) {
  30766. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30767. return;
  30768. }
  30769. //legacy support for old syntax.
  30770. if (!this._scene && object.getScene) {
  30771. this._scene = object.getScene();
  30772. }
  30773. this._physicsEngine = this._scene.getPhysicsEngine();
  30774. if (!this._physicsEngine) {
  30775. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30776. }
  30777. else {
  30778. //set the object's quaternion, if not set
  30779. if (!this.object.rotationQuaternion) {
  30780. if (this.object.rotation) {
  30781. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30782. }
  30783. else {
  30784. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30785. }
  30786. }
  30787. //default options params
  30788. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30789. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30790. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30791. this._joints = [];
  30792. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30793. if (!this.object.parent) {
  30794. this._init();
  30795. }
  30796. }
  30797. }
  30798. /**
  30799. * This function will completly initialize this impostor.
  30800. * It will create a new body - but only if this mesh has no parent.
  30801. * If it has, this impostor will not be used other than to define the impostor
  30802. * of the child mesh.
  30803. */
  30804. PhysicsImpostor.prototype._init = function () {
  30805. this._physicsEngine.removeImpostor(this);
  30806. this.physicsBody = null;
  30807. this._parent = this._parent || this._getPhysicsParent();
  30808. if (!this.parent) {
  30809. this._physicsEngine.addImpostor(this);
  30810. }
  30811. };
  30812. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30813. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30814. var parentMesh = this.object.parent;
  30815. return parentMesh.physicsImpostor;
  30816. }
  30817. return;
  30818. };
  30819. /**
  30820. * Should a new body be generated.
  30821. */
  30822. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30823. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30824. };
  30825. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30826. this.forceUpdate();
  30827. };
  30828. /**
  30829. * Force a regeneration of this or the parent's impostor's body.
  30830. * Use under cautious - This will remove all joints already implemented.
  30831. */
  30832. PhysicsImpostor.prototype.forceUpdate = function () {
  30833. this._init();
  30834. if (this.parent) {
  30835. this.parent.forceUpdate();
  30836. }
  30837. };
  30838. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30839. /*public get mesh(): AbstractMesh {
  30840. return this._mesh;
  30841. }*/
  30842. /**
  30843. * Gets the body that holds this impostor. Either its own, or its parent.
  30844. */
  30845. get: function () {
  30846. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30847. },
  30848. /**
  30849. * Set the physics body. Used mainly by the physics engine/plugin
  30850. */
  30851. set: function (physicsBody) {
  30852. if (this._physicsBody) {
  30853. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30854. }
  30855. this._physicsBody = physicsBody;
  30856. this.resetUpdateFlags();
  30857. },
  30858. enumerable: true,
  30859. configurable: true
  30860. });
  30861. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30862. get: function () {
  30863. return this._parent;
  30864. },
  30865. set: function (value) {
  30866. this._parent = value;
  30867. },
  30868. enumerable: true,
  30869. configurable: true
  30870. });
  30871. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30872. this._bodyUpdateRequired = false;
  30873. };
  30874. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30875. if (this.object.getBoundingInfo) {
  30876. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30877. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30878. }
  30879. else {
  30880. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30881. }
  30882. };
  30883. PhysicsImpostor.prototype.getObjectCenter = function () {
  30884. if (this.object.getBoundingInfo) {
  30885. return this.object.getBoundingInfo().boundingBox.center;
  30886. }
  30887. else {
  30888. return this.object.position;
  30889. }
  30890. };
  30891. /**
  30892. * Get a specific parametes from the options parameter.
  30893. */
  30894. PhysicsImpostor.prototype.getParam = function (paramName) {
  30895. return this._options[paramName];
  30896. };
  30897. /**
  30898. * Sets a specific parameter in the options given to the physics plugin
  30899. */
  30900. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30901. this._options[paramName] = value;
  30902. this._bodyUpdateRequired = true;
  30903. };
  30904. /**
  30905. * Specifically change the body's mass option. Won't recreate the physics body object
  30906. */
  30907. PhysicsImpostor.prototype.setMass = function (mass) {
  30908. if (this.getParam("mass") !== mass) {
  30909. this.setParam("mass", mass);
  30910. }
  30911. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30912. };
  30913. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30914. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30915. };
  30916. /**
  30917. * Set the body's linear velocity.
  30918. */
  30919. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30920. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30921. };
  30922. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30923. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30924. };
  30925. /**
  30926. * Set the body's linear velocity.
  30927. */
  30928. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30929. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30930. };
  30931. /**
  30932. * Execute a function with the physics plugin native code.
  30933. * Provide a function the will have two variables - the world object and the physics body object.
  30934. */
  30935. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30936. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30937. };
  30938. /**
  30939. * Register a function that will be executed before the physics world is stepping forward.
  30940. */
  30941. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30942. this._onBeforePhysicsStepCallbacks.push(func);
  30943. };
  30944. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30945. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30946. if (index > -1) {
  30947. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30948. }
  30949. else {
  30950. BABYLON.Tools.Warn("Function to remove was not found");
  30951. }
  30952. };
  30953. /**
  30954. * Register a function that will be executed after the physics step
  30955. */
  30956. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30957. this._onAfterPhysicsStepCallbacks.push(func);
  30958. };
  30959. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30960. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30961. if (index > -1) {
  30962. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30963. }
  30964. else {
  30965. BABYLON.Tools.Warn("Function to remove was not found");
  30966. }
  30967. };
  30968. /**
  30969. * register a function that will be executed when this impostor collides against a different body.
  30970. */
  30971. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30972. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30973. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30974. };
  30975. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30976. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30977. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30978. if (index > -1) {
  30979. this._onPhysicsCollideCallbacks.splice(index, 1);
  30980. }
  30981. else {
  30982. BABYLON.Tools.Warn("Function to remove was not found");
  30983. }
  30984. };
  30985. /**
  30986. * Apply a force
  30987. */
  30988. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30989. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30990. };
  30991. /**
  30992. * Apply an impulse
  30993. */
  30994. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30995. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30996. };
  30997. /**
  30998. * A help function to create a joint.
  30999. */
  31000. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  31001. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  31002. this.addJoint(otherImpostor, joint);
  31003. };
  31004. /**
  31005. * Add a joint to this impostor with a different impostor.
  31006. */
  31007. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  31008. this._joints.push({
  31009. otherImpostor: otherImpostor,
  31010. joint: joint
  31011. });
  31012. this._physicsEngine.addJoint(this, otherImpostor, joint);
  31013. };
  31014. /**
  31015. * Will keep this body still, in a sleep mode.
  31016. */
  31017. PhysicsImpostor.prototype.sleep = function () {
  31018. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  31019. };
  31020. /**
  31021. * Wake the body up.
  31022. */
  31023. PhysicsImpostor.prototype.wakeUp = function () {
  31024. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  31025. };
  31026. PhysicsImpostor.prototype.clone = function (newObject) {
  31027. if (!newObject)
  31028. return null;
  31029. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  31030. };
  31031. PhysicsImpostor.prototype.dispose = function () {
  31032. var _this = this;
  31033. //no dispose if no physics engine is available.
  31034. if (!this._physicsEngine) {
  31035. return;
  31036. }
  31037. this._joints.forEach(function (j) {
  31038. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  31039. });
  31040. //dispose the physics body
  31041. this._physicsEngine.removeImpostor(this);
  31042. if (this.parent) {
  31043. this.parent.forceUpdate();
  31044. }
  31045. else {
  31046. }
  31047. };
  31048. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  31049. this._deltaPosition.copyFrom(position);
  31050. };
  31051. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  31052. if (!this._deltaRotation) {
  31053. this._deltaRotation = new BABYLON.Quaternion();
  31054. }
  31055. this._deltaRotation.copyFrom(rotation);
  31056. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  31057. };
  31058. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  31059. //Impostor types
  31060. PhysicsImpostor.NoImpostor = 0;
  31061. PhysicsImpostor.SphereImpostor = 1;
  31062. PhysicsImpostor.BoxImpostor = 2;
  31063. PhysicsImpostor.PlaneImpostor = 3;
  31064. PhysicsImpostor.MeshImpostor = 4;
  31065. PhysicsImpostor.CylinderImpostor = 7;
  31066. PhysicsImpostor.ParticleImpostor = 8;
  31067. PhysicsImpostor.HeightmapImpostor = 9;
  31068. return PhysicsImpostor;
  31069. }());
  31070. BABYLON.PhysicsImpostor = PhysicsImpostor;
  31071. })(BABYLON || (BABYLON = {}));
  31072. var BABYLON;
  31073. (function (BABYLON) {
  31074. var PhysicsEngine = (function () {
  31075. function PhysicsEngine(gravity, _physicsPlugin) {
  31076. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  31077. this._physicsPlugin = _physicsPlugin;
  31078. //new methods and parameters
  31079. this._impostors = [];
  31080. this._joints = [];
  31081. if (!this._physicsPlugin.isSupported()) {
  31082. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  31083. + "Please make sure it is included.");
  31084. }
  31085. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  31086. this.setGravity(gravity);
  31087. this.setTimeStep();
  31088. }
  31089. PhysicsEngine.prototype.setGravity = function (gravity) {
  31090. this.gravity = gravity;
  31091. this._physicsPlugin.setGravity(this.gravity);
  31092. };
  31093. /**
  31094. * Set the time step of the physics engine.
  31095. * default is 1/60.
  31096. * To slow it down, enter 1/600 for example.
  31097. * To speed it up, 1/30
  31098. * @param {number} newTimeStep the new timestep to apply to this world.
  31099. */
  31100. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  31101. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  31102. this._physicsPlugin.setTimeStep(newTimeStep);
  31103. };
  31104. PhysicsEngine.prototype.dispose = function () {
  31105. this._impostors.forEach(function (impostor) {
  31106. impostor.dispose();
  31107. });
  31108. this._physicsPlugin.dispose();
  31109. };
  31110. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  31111. return this._physicsPlugin.name;
  31112. };
  31113. /**
  31114. * Adding a new impostor for the impostor tracking.
  31115. * This will be done by the impostor itself.
  31116. * @param {PhysicsImpostor} impostor the impostor to add
  31117. */
  31118. PhysicsEngine.prototype.addImpostor = function (impostor) {
  31119. impostor.uniqueId = this._impostors.push(impostor);
  31120. //if no parent, generate the body
  31121. if (!impostor.parent) {
  31122. this._physicsPlugin.generatePhysicsBody(impostor);
  31123. }
  31124. };
  31125. /**
  31126. * Remove an impostor from the engine.
  31127. * This impostor and its mesh will not longer be updated by the physics engine.
  31128. * @param {PhysicsImpostor} impostor the impostor to remove
  31129. */
  31130. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  31131. var index = this._impostors.indexOf(impostor);
  31132. if (index > -1) {
  31133. var removed = this._impostors.splice(index, 1);
  31134. //Is it needed?
  31135. if (removed.length) {
  31136. //this will also remove it from the world.
  31137. removed[0].physicsBody = null;
  31138. }
  31139. }
  31140. };
  31141. /**
  31142. * Add a joint to the physics engine
  31143. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  31144. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  31145. * @param {PhysicsJoint} the joint that will connect both impostors.
  31146. */
  31147. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  31148. var impostorJoint = {
  31149. mainImpostor: mainImpostor,
  31150. connectedImpostor: connectedImpostor,
  31151. joint: joint
  31152. };
  31153. joint.physicsPlugin = this._physicsPlugin;
  31154. this._joints.push(impostorJoint);
  31155. this._physicsPlugin.generateJoint(impostorJoint);
  31156. };
  31157. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  31158. var matchingJoints = this._joints.filter(function (impostorJoint) {
  31159. return (impostorJoint.connectedImpostor === connectedImpostor
  31160. && impostorJoint.joint === joint
  31161. && impostorJoint.mainImpostor === mainImpostor);
  31162. });
  31163. if (matchingJoints.length) {
  31164. this._physicsPlugin.removeJoint(matchingJoints[0]);
  31165. }
  31166. };
  31167. /**
  31168. * Called by the scene. no need to call it.
  31169. */
  31170. PhysicsEngine.prototype._step = function (delta) {
  31171. var _this = this;
  31172. //check if any mesh has no body / requires an update
  31173. this._impostors.forEach(function (impostor) {
  31174. if (impostor.isBodyInitRequired()) {
  31175. _this._physicsPlugin.generatePhysicsBody(impostor);
  31176. }
  31177. });
  31178. if (delta > 0.1) {
  31179. delta = 0.1;
  31180. }
  31181. else if (delta <= 0) {
  31182. delta = 1.0 / 60.0;
  31183. }
  31184. this._physicsPlugin.executeStep(delta, this._impostors);
  31185. };
  31186. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  31187. return this._physicsPlugin;
  31188. };
  31189. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  31190. for (var i = 0; i < this._impostors.length; ++i) {
  31191. if (this._impostors[i].object === object) {
  31192. return this._impostors[i];
  31193. }
  31194. }
  31195. };
  31196. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  31197. for (var i = 0; i < this._impostors.length; ++i) {
  31198. if (this._impostors[i].physicsBody === body) {
  31199. return this._impostors[i];
  31200. }
  31201. }
  31202. };
  31203. // Statics, Legacy support.
  31204. /**
  31205. * @Deprecated
  31206. *
  31207. */
  31208. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  31209. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  31210. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  31211. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  31212. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  31213. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  31214. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  31215. PhysicsEngine.CapsuleImpostor = -1;
  31216. PhysicsEngine.ConeImpostor = -1;
  31217. PhysicsEngine.ConvexHullImpostor = -1;
  31218. PhysicsEngine.Epsilon = 0.001;
  31219. return PhysicsEngine;
  31220. }());
  31221. BABYLON.PhysicsEngine = PhysicsEngine;
  31222. })(BABYLON || (BABYLON = {}));
  31223. var BABYLON;
  31224. (function (BABYLON) {
  31225. var VertexData = (function () {
  31226. function VertexData() {
  31227. }
  31228. VertexData.prototype.set = function (data, kind) {
  31229. switch (kind) {
  31230. case BABYLON.VertexBuffer.PositionKind:
  31231. this.positions = data;
  31232. break;
  31233. case BABYLON.VertexBuffer.NormalKind:
  31234. this.normals = data;
  31235. break;
  31236. case BABYLON.VertexBuffer.UVKind:
  31237. this.uvs = data;
  31238. break;
  31239. case BABYLON.VertexBuffer.UV2Kind:
  31240. this.uvs2 = data;
  31241. break;
  31242. case BABYLON.VertexBuffer.UV3Kind:
  31243. this.uvs3 = data;
  31244. break;
  31245. case BABYLON.VertexBuffer.UV4Kind:
  31246. this.uvs4 = data;
  31247. break;
  31248. case BABYLON.VertexBuffer.UV5Kind:
  31249. this.uvs5 = data;
  31250. break;
  31251. case BABYLON.VertexBuffer.UV6Kind:
  31252. this.uvs6 = data;
  31253. break;
  31254. case BABYLON.VertexBuffer.ColorKind:
  31255. this.colors = data;
  31256. break;
  31257. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31258. this.matricesIndices = data;
  31259. break;
  31260. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31261. this.matricesWeights = data;
  31262. break;
  31263. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31264. this.matricesIndicesExtra = data;
  31265. break;
  31266. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31267. this.matricesWeightsExtra = data;
  31268. break;
  31269. }
  31270. };
  31271. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31272. this._applyTo(mesh, updatable);
  31273. };
  31274. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31275. this._applyTo(geometry, updatable);
  31276. };
  31277. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31278. this._update(mesh);
  31279. };
  31280. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31281. this._update(geometry);
  31282. };
  31283. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31284. if (this.positions) {
  31285. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31286. }
  31287. if (this.normals) {
  31288. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31289. }
  31290. if (this.uvs) {
  31291. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31292. }
  31293. if (this.uvs2) {
  31294. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31295. }
  31296. if (this.uvs3) {
  31297. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31298. }
  31299. if (this.uvs4) {
  31300. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31301. }
  31302. if (this.uvs5) {
  31303. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31304. }
  31305. if (this.uvs6) {
  31306. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31307. }
  31308. if (this.colors) {
  31309. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31310. }
  31311. if (this.matricesIndices) {
  31312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31313. }
  31314. if (this.matricesWeights) {
  31315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31316. }
  31317. if (this.matricesIndicesExtra) {
  31318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31319. }
  31320. if (this.matricesWeightsExtra) {
  31321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31322. }
  31323. if (this.indices) {
  31324. meshOrGeometry.setIndices(this.indices);
  31325. }
  31326. };
  31327. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31328. if (this.positions) {
  31329. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31330. }
  31331. if (this.normals) {
  31332. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31333. }
  31334. if (this.uvs) {
  31335. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31336. }
  31337. if (this.uvs2) {
  31338. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31339. }
  31340. if (this.uvs3) {
  31341. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31342. }
  31343. if (this.uvs4) {
  31344. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31345. }
  31346. if (this.uvs5) {
  31347. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31348. }
  31349. if (this.uvs6) {
  31350. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31351. }
  31352. if (this.colors) {
  31353. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31354. }
  31355. if (this.matricesIndices) {
  31356. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31357. }
  31358. if (this.matricesWeights) {
  31359. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31360. }
  31361. if (this.matricesIndicesExtra) {
  31362. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31363. }
  31364. if (this.matricesWeightsExtra) {
  31365. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31366. }
  31367. if (this.indices) {
  31368. meshOrGeometry.setIndices(this.indices);
  31369. }
  31370. };
  31371. VertexData.prototype.transform = function (matrix) {
  31372. var transformed = BABYLON.Vector3.Zero();
  31373. var index;
  31374. if (this.positions) {
  31375. var position = BABYLON.Vector3.Zero();
  31376. for (index = 0; index < this.positions.length; index += 3) {
  31377. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31378. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31379. this.positions[index] = transformed.x;
  31380. this.positions[index + 1] = transformed.y;
  31381. this.positions[index + 2] = transformed.z;
  31382. }
  31383. }
  31384. if (this.normals) {
  31385. var normal = BABYLON.Vector3.Zero();
  31386. for (index = 0; index < this.normals.length; index += 3) {
  31387. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31388. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31389. this.normals[index] = transformed.x;
  31390. this.normals[index + 1] = transformed.y;
  31391. this.normals[index + 2] = transformed.z;
  31392. }
  31393. }
  31394. };
  31395. VertexData.prototype.merge = function (other) {
  31396. if (other.indices) {
  31397. if (!this.indices) {
  31398. this.indices = [];
  31399. }
  31400. var offset = this.positions ? this.positions.length / 3 : 0;
  31401. for (var index = 0; index < other.indices.length; index++) {
  31402. //TODO check type - if Int32Array!
  31403. this.indices.push(other.indices[index] + offset);
  31404. }
  31405. }
  31406. this.positions = this._mergeElement(this.positions, other.positions);
  31407. this.normals = this._mergeElement(this.normals, other.normals);
  31408. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31409. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31410. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31411. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31412. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31413. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31414. this.colors = this._mergeElement(this.colors, other.colors);
  31415. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31416. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31417. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31418. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31419. };
  31420. VertexData.prototype._mergeElement = function (source, other) {
  31421. if (!other)
  31422. return source;
  31423. if (!source)
  31424. return other;
  31425. var len = other.length + source.length;
  31426. var isSrcTypedArray = source instanceof Float32Array;
  31427. var isOthTypedArray = other instanceof Float32Array;
  31428. // use non-loop method when the source is Float32Array
  31429. if (isSrcTypedArray) {
  31430. var ret32 = new Float32Array(len);
  31431. ret32.set(source);
  31432. ret32.set(other, source.length);
  31433. return ret32;
  31434. }
  31435. else if (!isOthTypedArray) {
  31436. return source.concat(other);
  31437. }
  31438. else {
  31439. var ret = source.slice(0); // copy source to a separate array
  31440. for (var i = 0, len = other.length; i < len; i++) {
  31441. ret.push(other[i]);
  31442. }
  31443. return ret;
  31444. }
  31445. };
  31446. VertexData.prototype.serialize = function () {
  31447. var serializationObject = this.serialize();
  31448. if (this.positions) {
  31449. serializationObject.positions = this.positions;
  31450. }
  31451. if (this.normals) {
  31452. serializationObject.normals = this.normals;
  31453. }
  31454. if (this.uvs) {
  31455. serializationObject.uvs = this.uvs;
  31456. }
  31457. if (this.uvs2) {
  31458. serializationObject.uvs2 = this.uvs2;
  31459. }
  31460. if (this.uvs3) {
  31461. serializationObject.uvs3 = this.uvs3;
  31462. }
  31463. if (this.uvs4) {
  31464. serializationObject.uvs4 = this.uvs4;
  31465. }
  31466. if (this.uvs5) {
  31467. serializationObject.uvs5 = this.uvs5;
  31468. }
  31469. if (this.uvs6) {
  31470. serializationObject.uvs6 = this.uvs6;
  31471. }
  31472. if (this.colors) {
  31473. serializationObject.colors = this.colors;
  31474. }
  31475. if (this.matricesIndices) {
  31476. serializationObject.matricesIndices = this.matricesIndices;
  31477. serializationObject.matricesIndices._isExpanded = true;
  31478. }
  31479. if (this.matricesWeights) {
  31480. serializationObject.matricesWeights = this.matricesWeights;
  31481. }
  31482. if (this.matricesIndicesExtra) {
  31483. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31484. serializationObject.matricesIndicesExtra._isExpanded = true;
  31485. }
  31486. if (this.matricesWeightsExtra) {
  31487. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  31488. }
  31489. serializationObject.indices = this.indices;
  31490. return serializationObject;
  31491. };
  31492. // Statics
  31493. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  31494. return VertexData._ExtractFrom(mesh, copyWhenShared);
  31495. };
  31496. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  31497. return VertexData._ExtractFrom(geometry, copyWhenShared);
  31498. };
  31499. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  31500. var result = new VertexData();
  31501. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31502. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  31503. }
  31504. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31505. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  31506. }
  31507. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31508. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  31509. }
  31510. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31511. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  31512. }
  31513. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31514. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  31515. }
  31516. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31517. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  31518. }
  31519. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31520. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  31521. }
  31522. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31523. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  31524. }
  31525. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31526. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  31527. }
  31528. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31529. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  31530. }
  31531. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31532. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  31533. }
  31534. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31535. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  31536. }
  31537. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31538. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  31539. }
  31540. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31541. return result;
  31542. };
  31543. VertexData.CreateRibbon = function (options) {
  31544. var pathArray = options.pathArray;
  31545. var closeArray = options.closeArray || false;
  31546. var closePath = options.closePath || false;
  31547. var invertUV = options.invertUV || false;
  31548. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31549. var offset = options.offset || defaultOffset;
  31550. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31551. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31552. var positions = [];
  31553. var indices = [];
  31554. var normals = [];
  31555. var uvs = [];
  31556. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31557. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31558. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31559. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31560. var minlg; // minimal length among all paths from pathArray
  31561. var lg = []; // array of path lengths : nb of vertex per path
  31562. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31563. var p; // path iterator
  31564. var i; // point iterator
  31565. var j; // point iterator
  31566. // if single path in pathArray
  31567. if (pathArray.length < 2) {
  31568. var ar1 = [];
  31569. var ar2 = [];
  31570. for (i = 0; i < pathArray[0].length - offset; i++) {
  31571. ar1.push(pathArray[0][i]);
  31572. ar2.push(pathArray[0][i + offset]);
  31573. }
  31574. pathArray = [ar1, ar2];
  31575. }
  31576. // positions and horizontal distances (u)
  31577. var idc = 0;
  31578. var closePathCorr = (closePath) ? 1 : 0;
  31579. var path;
  31580. var l;
  31581. minlg = pathArray[0].length;
  31582. var vectlg;
  31583. var dist;
  31584. for (p = 0; p < pathArray.length; p++) {
  31585. uTotalDistance[p] = 0;
  31586. us[p] = [0];
  31587. path = pathArray[p];
  31588. l = path.length;
  31589. minlg = (minlg < l) ? minlg : l;
  31590. j = 0;
  31591. while (j < l) {
  31592. positions.push(path[j].x, path[j].y, path[j].z);
  31593. if (j > 0) {
  31594. vectlg = path[j].subtract(path[j - 1]).length();
  31595. dist = vectlg + uTotalDistance[p];
  31596. us[p].push(dist);
  31597. uTotalDistance[p] = dist;
  31598. }
  31599. j++;
  31600. }
  31601. if (closePath) {
  31602. j--;
  31603. positions.push(path[0].x, path[0].y, path[0].z);
  31604. vectlg = path[j].subtract(path[0]).length();
  31605. dist = vectlg + uTotalDistance[p];
  31606. us[p].push(dist);
  31607. uTotalDistance[p] = dist;
  31608. }
  31609. lg[p] = l + closePathCorr;
  31610. idx[p] = idc;
  31611. idc += (l + closePathCorr);
  31612. }
  31613. // vertical distances (v)
  31614. var path1;
  31615. var path2;
  31616. var vertex1;
  31617. var vertex2;
  31618. for (i = 0; i < minlg + closePathCorr; i++) {
  31619. vTotalDistance[i] = 0;
  31620. vs[i] = [0];
  31621. for (p = 0; p < pathArray.length - 1; p++) {
  31622. path1 = pathArray[p];
  31623. path2 = pathArray[p + 1];
  31624. if (i === minlg) {
  31625. vertex1 = path1[0];
  31626. vertex2 = path2[0];
  31627. }
  31628. else {
  31629. vertex1 = path1[i];
  31630. vertex2 = path2[i];
  31631. }
  31632. vectlg = vertex2.subtract(vertex1).length();
  31633. dist = vectlg + vTotalDistance[i];
  31634. vs[i].push(dist);
  31635. vTotalDistance[i] = dist;
  31636. }
  31637. if (closeArray) {
  31638. path1 = pathArray[p];
  31639. path2 = pathArray[0];
  31640. if (i === minlg) {
  31641. vertex2 = path2[0];
  31642. }
  31643. vectlg = vertex2.subtract(vertex1).length();
  31644. dist = vectlg + vTotalDistance[i];
  31645. vTotalDistance[i] = dist;
  31646. }
  31647. }
  31648. // uvs
  31649. var u;
  31650. var v;
  31651. for (p = 0; p < pathArray.length; p++) {
  31652. for (i = 0; i < minlg + closePathCorr; i++) {
  31653. u = us[p][i] / uTotalDistance[p];
  31654. v = vs[i][p] / vTotalDistance[i];
  31655. if (invertUV) {
  31656. uvs.push(v, u);
  31657. }
  31658. else {
  31659. uvs.push(u, v);
  31660. }
  31661. }
  31662. }
  31663. // indices
  31664. p = 0; // path index
  31665. var pi = 0; // positions array index
  31666. var l1 = lg[p] - 1; // path1 length
  31667. var l2 = lg[p + 1] - 1; // path2 length
  31668. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31669. var shft = idx[1] - idx[0]; // shift
  31670. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31671. while (pi <= min && p < path1nb) {
  31672. // 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
  31673. indices.push(pi, pi + shft, pi + 1);
  31674. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31675. pi += 1;
  31676. if (pi === min) {
  31677. p++;
  31678. if (p === lg.length - 1) {
  31679. shft = idx[0] - idx[p];
  31680. l1 = lg[p] - 1;
  31681. l2 = lg[0] - 1;
  31682. }
  31683. else {
  31684. shft = idx[p + 1] - idx[p];
  31685. l1 = lg[p] - 1;
  31686. l2 = lg[p + 1] - 1;
  31687. }
  31688. pi = idx[p];
  31689. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31690. }
  31691. }
  31692. // normals
  31693. VertexData.ComputeNormals(positions, indices, normals);
  31694. if (closePath) {
  31695. var indexFirst = 0;
  31696. var indexLast = 0;
  31697. for (p = 0; p < pathArray.length; p++) {
  31698. indexFirst = idx[p] * 3;
  31699. if (p + 1 < pathArray.length) {
  31700. indexLast = (idx[p + 1] - 1) * 3;
  31701. }
  31702. else {
  31703. indexLast = normals.length - 3;
  31704. }
  31705. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31706. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31707. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31708. normals[indexLast] = normals[indexFirst];
  31709. normals[indexLast + 1] = normals[indexFirst + 1];
  31710. normals[indexLast + 2] = normals[indexFirst + 2];
  31711. }
  31712. }
  31713. // sides
  31714. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31715. // Result
  31716. var vertexData = new VertexData();
  31717. vertexData.indices = indices;
  31718. vertexData.positions = positions;
  31719. vertexData.normals = normals;
  31720. vertexData.uvs = uvs;
  31721. if (closePath) {
  31722. vertexData._idx = idx;
  31723. }
  31724. return vertexData;
  31725. };
  31726. VertexData.CreateBox = function (options) {
  31727. var normalsSource = [
  31728. new BABYLON.Vector3(0, 0, 1),
  31729. new BABYLON.Vector3(0, 0, -1),
  31730. new BABYLON.Vector3(1, 0, 0),
  31731. new BABYLON.Vector3(-1, 0, 0),
  31732. new BABYLON.Vector3(0, 1, 0),
  31733. new BABYLON.Vector3(0, -1, 0)
  31734. ];
  31735. var indices = [];
  31736. var positions = [];
  31737. var normals = [];
  31738. var uvs = [];
  31739. var width = options.width || options.size || 1;
  31740. var height = options.height || options.size || 1;
  31741. var depth = options.depth || options.size || 1;
  31742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31743. var faceUV = options.faceUV || new Array(6);
  31744. var faceColors = options.faceColors;
  31745. var colors = [];
  31746. // default face colors and UV if undefined
  31747. for (var f = 0; f < 6; f++) {
  31748. if (faceUV[f] === undefined) {
  31749. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31750. }
  31751. if (faceColors && faceColors[f] === undefined) {
  31752. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31753. }
  31754. }
  31755. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31756. // Create each face in turn.
  31757. for (var index = 0; index < normalsSource.length; index++) {
  31758. var normal = normalsSource[index];
  31759. // Get two vectors perpendicular to the face normal and to each other.
  31760. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31761. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31762. // Six indices (two triangles) per face.
  31763. var verticesLength = positions.length / 3;
  31764. indices.push(verticesLength);
  31765. indices.push(verticesLength + 1);
  31766. indices.push(verticesLength + 2);
  31767. indices.push(verticesLength);
  31768. indices.push(verticesLength + 2);
  31769. indices.push(verticesLength + 3);
  31770. // Four vertices per face.
  31771. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31772. positions.push(vertex.x, vertex.y, vertex.z);
  31773. normals.push(normal.x, normal.y, normal.z);
  31774. uvs.push(faceUV[index].z, faceUV[index].w);
  31775. if (faceColors) {
  31776. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31777. }
  31778. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31779. positions.push(vertex.x, vertex.y, vertex.z);
  31780. normals.push(normal.x, normal.y, normal.z);
  31781. uvs.push(faceUV[index].x, faceUV[index].w);
  31782. if (faceColors) {
  31783. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31784. }
  31785. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31786. positions.push(vertex.x, vertex.y, vertex.z);
  31787. normals.push(normal.x, normal.y, normal.z);
  31788. uvs.push(faceUV[index].x, faceUV[index].y);
  31789. if (faceColors) {
  31790. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31791. }
  31792. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31793. positions.push(vertex.x, vertex.y, vertex.z);
  31794. normals.push(normal.x, normal.y, normal.z);
  31795. uvs.push(faceUV[index].z, faceUV[index].y);
  31796. if (faceColors) {
  31797. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31798. }
  31799. }
  31800. // sides
  31801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31802. // Result
  31803. var vertexData = new VertexData();
  31804. vertexData.indices = indices;
  31805. vertexData.positions = positions;
  31806. vertexData.normals = normals;
  31807. vertexData.uvs = uvs;
  31808. if (faceColors) {
  31809. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31810. vertexData.colors = totalColors;
  31811. }
  31812. return vertexData;
  31813. };
  31814. VertexData.CreateSphere = function (options) {
  31815. var segments = options.segments || 32;
  31816. var diameterX = options.diameterX || options.diameter || 1;
  31817. var diameterY = options.diameterY || options.diameter || 1;
  31818. var diameterZ = options.diameterZ || options.diameter || 1;
  31819. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31820. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31822. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31823. var totalZRotationSteps = 2 + segments;
  31824. var totalYRotationSteps = 2 * totalZRotationSteps;
  31825. var indices = [];
  31826. var positions = [];
  31827. var normals = [];
  31828. var uvs = [];
  31829. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31830. var normalizedZ = zRotationStep / totalZRotationSteps;
  31831. var angleZ = normalizedZ * Math.PI * slice;
  31832. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31833. var normalizedY = yRotationStep / totalYRotationSteps;
  31834. var angleY = normalizedY * Math.PI * 2 * arc;
  31835. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31836. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31837. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31838. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31839. var vertex = complete.multiply(radius);
  31840. var normal = complete.divide(radius).normalize();
  31841. positions.push(vertex.x, vertex.y, vertex.z);
  31842. normals.push(normal.x, normal.y, normal.z);
  31843. uvs.push(normalizedY, normalizedZ);
  31844. }
  31845. if (zRotationStep > 0) {
  31846. var verticesCount = positions.length / 3;
  31847. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31848. indices.push((firstIndex));
  31849. indices.push((firstIndex + 1));
  31850. indices.push(firstIndex + totalYRotationSteps + 1);
  31851. indices.push((firstIndex + totalYRotationSteps + 1));
  31852. indices.push((firstIndex + 1));
  31853. indices.push((firstIndex + totalYRotationSteps + 2));
  31854. }
  31855. }
  31856. }
  31857. // Sides
  31858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31859. // Result
  31860. var vertexData = new VertexData();
  31861. vertexData.indices = indices;
  31862. vertexData.positions = positions;
  31863. vertexData.normals = normals;
  31864. vertexData.uvs = uvs;
  31865. return vertexData;
  31866. };
  31867. // Cylinder and cone
  31868. VertexData.CreateCylinder = function (options) {
  31869. var height = options.height || 2;
  31870. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31871. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31872. var tessellation = options.tessellation || 24;
  31873. var subdivisions = options.subdivisions || 1;
  31874. var hasRings = options.hasRings;
  31875. var enclose = options.enclose;
  31876. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31877. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31878. var faceUV = options.faceUV || new Array(3);
  31879. var faceColors = options.faceColors;
  31880. // default face colors and UV if undefined
  31881. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31882. var ringNb = (hasRings) ? subdivisions : 1;
  31883. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31884. var f;
  31885. for (f = 0; f < surfaceNb; f++) {
  31886. if (faceColors && faceColors[f] === undefined) {
  31887. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31888. }
  31889. }
  31890. for (f = 0; f < surfaceNb; f++) {
  31891. if (faceUV && faceUV[f] === undefined) {
  31892. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31893. }
  31894. }
  31895. var indices = [];
  31896. var positions = [];
  31897. var normals = [];
  31898. var uvs = [];
  31899. var colors = [];
  31900. var angle_step = Math.PI * 2 * arc / tessellation;
  31901. var angle;
  31902. var h;
  31903. var radius;
  31904. var tan = (diameterBottom - diameterTop) / 2 / height;
  31905. var ringVertex = BABYLON.Vector3.Zero();
  31906. var ringNormal = BABYLON.Vector3.Zero();
  31907. var ringFirstVertex = BABYLON.Vector3.Zero();
  31908. var ringFirstNormal = BABYLON.Vector3.Zero();
  31909. var quadNormal = BABYLON.Vector3.Zero();
  31910. var Y = BABYLON.Axis.Y;
  31911. // positions, normals, uvs
  31912. var i;
  31913. var j;
  31914. var r;
  31915. var ringIdx = 1;
  31916. var s = 1; // surface index
  31917. var cs = 0;
  31918. var v = 0;
  31919. for (i = 0; i <= subdivisions; i++) {
  31920. h = i / subdivisions;
  31921. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31922. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31923. for (r = 0; r < ringIdx; r++) {
  31924. if (hasRings) {
  31925. s += r;
  31926. }
  31927. if (enclose) {
  31928. s += 2 * r;
  31929. }
  31930. for (j = 0; j <= tessellation; j++) {
  31931. angle = j * angle_step;
  31932. // position
  31933. ringVertex.x = Math.cos(-angle) * radius;
  31934. ringVertex.y = -height / 2 + h * height;
  31935. ringVertex.z = Math.sin(-angle) * radius;
  31936. // normal
  31937. if (diameterTop === 0 && i === subdivisions) {
  31938. // if no top cap, reuse former normals
  31939. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31940. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31941. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31942. }
  31943. else {
  31944. ringNormal.x = ringVertex.x;
  31945. ringNormal.z = ringVertex.z;
  31946. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31947. ringNormal.normalize();
  31948. }
  31949. // keep first ring vertex values for enclose
  31950. if (j === 0) {
  31951. ringFirstVertex.copyFrom(ringVertex);
  31952. ringFirstNormal.copyFrom(ringNormal);
  31953. }
  31954. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31955. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31956. if (hasRings) {
  31957. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31958. }
  31959. else {
  31960. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31961. }
  31962. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31963. if (faceColors) {
  31964. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31965. }
  31966. }
  31967. // if enclose, add four vertices and their dedicated normals
  31968. if (arc !== 1 && enclose) {
  31969. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31970. positions.push(0, ringVertex.y, 0);
  31971. positions.push(0, ringVertex.y, 0);
  31972. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31973. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31974. quadNormal.normalize();
  31975. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31976. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31977. quadNormal.normalize();
  31978. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31979. if (hasRings) {
  31980. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31981. }
  31982. else {
  31983. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31984. }
  31985. uvs.push(faceUV[s + 1].x, v);
  31986. uvs.push(faceUV[s + 1].z, v);
  31987. if (hasRings) {
  31988. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31989. }
  31990. else {
  31991. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31992. }
  31993. uvs.push(faceUV[s + 2].x, v);
  31994. uvs.push(faceUV[s + 2].z, v);
  31995. if (faceColors) {
  31996. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31997. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31998. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31999. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32000. }
  32001. }
  32002. if (cs !== s) {
  32003. cs = s;
  32004. }
  32005. }
  32006. }
  32007. // indices
  32008. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32009. var s;
  32010. i = 0;
  32011. for (s = 0; s < subdivisions; s++) {
  32012. for (j = 0; j < tessellation; j++) {
  32013. var i0 = i * (e + 1) + j;
  32014. var i1 = (i + 1) * (e + 1) + j;
  32015. var i2 = i * (e + 1) + (j + 1);
  32016. var i3 = (i + 1) * (e + 1) + (j + 1);
  32017. indices.push(i0, i1, i2);
  32018. indices.push(i3, i2, i1);
  32019. }
  32020. if (arc !== 1 && enclose) {
  32021. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32022. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32023. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32024. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32025. }
  32026. i = (hasRings) ? (i + 2) : (i + 1);
  32027. }
  32028. // Caps
  32029. var createCylinderCap = function (isTop) {
  32030. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32031. if (radius === 0) {
  32032. return;
  32033. }
  32034. // Cap positions, normals & uvs
  32035. var angle;
  32036. var circleVector;
  32037. var i;
  32038. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32039. var c;
  32040. if (faceColors) {
  32041. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32042. }
  32043. // cap center
  32044. var vbase = positions.length / 3;
  32045. var offset = isTop ? height / 2 : -height / 2;
  32046. var center = new BABYLON.Vector3(0, offset, 0);
  32047. positions.push(center.x, center.y, center.z);
  32048. normals.push(0, isTop ? 1 : -1, 0);
  32049. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32050. if (faceColors) {
  32051. colors.push(c.r, c.g, c.b, c.a);
  32052. }
  32053. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32054. for (i = 0; i <= tessellation; i++) {
  32055. angle = Math.PI * 2 * i * arc / tessellation;
  32056. var cos = Math.cos(-angle);
  32057. var sin = Math.sin(-angle);
  32058. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32059. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32060. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32061. normals.push(0, isTop ? 1 : -1, 0);
  32062. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32063. if (faceColors) {
  32064. colors.push(c.r, c.g, c.b, c.a);
  32065. }
  32066. }
  32067. // Cap indices
  32068. for (i = 0; i < tessellation; i++) {
  32069. if (!isTop) {
  32070. indices.push(vbase);
  32071. indices.push(vbase + (i + 1));
  32072. indices.push(vbase + (i + 2));
  32073. }
  32074. else {
  32075. indices.push(vbase);
  32076. indices.push(vbase + (i + 2));
  32077. indices.push(vbase + (i + 1));
  32078. }
  32079. }
  32080. };
  32081. // add caps to geometry
  32082. createCylinderCap(false);
  32083. createCylinderCap(true);
  32084. // Sides
  32085. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32086. var vertexData = new VertexData();
  32087. vertexData.indices = indices;
  32088. vertexData.positions = positions;
  32089. vertexData.normals = normals;
  32090. vertexData.uvs = uvs;
  32091. if (faceColors) {
  32092. vertexData.colors = colors;
  32093. }
  32094. return vertexData;
  32095. };
  32096. VertexData.CreateTorus = function (options) {
  32097. var indices = [];
  32098. var positions = [];
  32099. var normals = [];
  32100. var uvs = [];
  32101. var diameter = options.diameter || 1;
  32102. var thickness = options.thickness || 0.5;
  32103. var tessellation = options.tessellation || 16;
  32104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32105. var stride = tessellation + 1;
  32106. for (var i = 0; i <= tessellation; i++) {
  32107. var u = i / tessellation;
  32108. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32109. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32110. for (var j = 0; j <= tessellation; j++) {
  32111. var v = 1 - j / tessellation;
  32112. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32113. var dx = Math.cos(innerAngle);
  32114. var dy = Math.sin(innerAngle);
  32115. // Create a vertex.
  32116. var normal = new BABYLON.Vector3(dx, dy, 0);
  32117. var position = normal.scale(thickness / 2);
  32118. var textureCoordinate = new BABYLON.Vector2(u, v);
  32119. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32120. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32121. positions.push(position.x, position.y, position.z);
  32122. normals.push(normal.x, normal.y, normal.z);
  32123. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32124. // And create indices for two triangles.
  32125. var nextI = (i + 1) % stride;
  32126. var nextJ = (j + 1) % stride;
  32127. indices.push(i * stride + j);
  32128. indices.push(i * stride + nextJ);
  32129. indices.push(nextI * stride + j);
  32130. indices.push(i * stride + nextJ);
  32131. indices.push(nextI * stride + nextJ);
  32132. indices.push(nextI * stride + j);
  32133. }
  32134. }
  32135. // Sides
  32136. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32137. // Result
  32138. var vertexData = new VertexData();
  32139. vertexData.indices = indices;
  32140. vertexData.positions = positions;
  32141. vertexData.normals = normals;
  32142. vertexData.uvs = uvs;
  32143. return vertexData;
  32144. };
  32145. VertexData.CreateLineSystem = function (options) {
  32146. var indices = [];
  32147. var positions = [];
  32148. var lines = options.lines;
  32149. var idx = 0;
  32150. for (var l = 0; l < lines.length; l++) {
  32151. var points = lines[l];
  32152. for (var index = 0; index < points.length; index++) {
  32153. positions.push(points[index].x, points[index].y, points[index].z);
  32154. if (index > 0) {
  32155. indices.push(idx - 1);
  32156. indices.push(idx);
  32157. }
  32158. idx++;
  32159. }
  32160. }
  32161. var vertexData = new VertexData();
  32162. vertexData.indices = indices;
  32163. vertexData.positions = positions;
  32164. return vertexData;
  32165. };
  32166. VertexData.CreateDashedLines = function (options) {
  32167. var dashSize = options.dashSize || 3;
  32168. var gapSize = options.gapSize || 1;
  32169. var dashNb = options.dashNb || 200;
  32170. var points = options.points;
  32171. var positions = new Array();
  32172. var indices = new Array();
  32173. var curvect = BABYLON.Vector3.Zero();
  32174. var lg = 0;
  32175. var nb = 0;
  32176. var shft = 0;
  32177. var dashshft = 0;
  32178. var curshft = 0;
  32179. var idx = 0;
  32180. var i = 0;
  32181. for (i = 0; i < points.length - 1; i++) {
  32182. points[i + 1].subtractToRef(points[i], curvect);
  32183. lg += curvect.length();
  32184. }
  32185. shft = lg / dashNb;
  32186. dashshft = dashSize * shft / (dashSize + gapSize);
  32187. for (i = 0; i < points.length - 1; i++) {
  32188. points[i + 1].subtractToRef(points[i], curvect);
  32189. nb = Math.floor(curvect.length() / shft);
  32190. curvect.normalize();
  32191. for (var j = 0; j < nb; j++) {
  32192. curshft = shft * j;
  32193. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32194. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32195. indices.push(idx, idx + 1);
  32196. idx += 2;
  32197. }
  32198. }
  32199. // Result
  32200. var vertexData = new VertexData();
  32201. vertexData.positions = positions;
  32202. vertexData.indices = indices;
  32203. return vertexData;
  32204. };
  32205. VertexData.CreateGround = function (options) {
  32206. var indices = [];
  32207. var positions = [];
  32208. var normals = [];
  32209. var uvs = [];
  32210. var row, col;
  32211. var width = options.width || 1;
  32212. var height = options.height || 1;
  32213. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32214. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32215. for (row = 0; row <= subdivisionsY; row++) {
  32216. for (col = 0; col <= subdivisionsX; col++) {
  32217. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32218. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32219. positions.push(position.x, position.y, position.z);
  32220. normals.push(normal.x, normal.y, normal.z);
  32221. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  32222. }
  32223. }
  32224. for (row = 0; row < subdivisionsY; row++) {
  32225. for (col = 0; col < subdivisionsX; col++) {
  32226. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32227. indices.push(col + 1 + row * (subdivisionsX + 1));
  32228. indices.push(col + row * (subdivisionsX + 1));
  32229. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32230. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32231. indices.push(col + row * (subdivisionsX + 1));
  32232. }
  32233. }
  32234. // Result
  32235. var vertexData = new VertexData();
  32236. vertexData.indices = indices;
  32237. vertexData.positions = positions;
  32238. vertexData.normals = normals;
  32239. vertexData.uvs = uvs;
  32240. return vertexData;
  32241. };
  32242. VertexData.CreateTiledGround = function (options) {
  32243. var xmin = options.xmin || -1.0;
  32244. var zmin = options.zmin || -1.0;
  32245. var xmax = options.xmax || 1.0;
  32246. var zmax = options.zmax || 1.0;
  32247. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32248. var precision = options.precision || { w: 1, h: 1 };
  32249. var indices = [];
  32250. var positions = [];
  32251. var normals = [];
  32252. var uvs = [];
  32253. var row, col, tileRow, tileCol;
  32254. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32255. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32256. precision.w = (precision.w < 1) ? 1 : precision.w;
  32257. precision.h = (precision.h < 1) ? 1 : precision.h;
  32258. var tileSize = {
  32259. 'w': (xmax - xmin) / subdivisions.w,
  32260. 'h': (zmax - zmin) / subdivisions.h
  32261. };
  32262. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32263. // Indices
  32264. var base = positions.length / 3;
  32265. var rowLength = precision.w + 1;
  32266. for (row = 0; row < precision.h; row++) {
  32267. for (col = 0; col < precision.w; col++) {
  32268. var square = [
  32269. base + col + row * rowLength,
  32270. base + (col + 1) + row * rowLength,
  32271. base + (col + 1) + (row + 1) * rowLength,
  32272. base + col + (row + 1) * rowLength
  32273. ];
  32274. indices.push(square[1]);
  32275. indices.push(square[2]);
  32276. indices.push(square[3]);
  32277. indices.push(square[0]);
  32278. indices.push(square[1]);
  32279. indices.push(square[3]);
  32280. }
  32281. }
  32282. // Position, normals and uvs
  32283. var position = BABYLON.Vector3.Zero();
  32284. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32285. for (row = 0; row <= precision.h; row++) {
  32286. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32287. for (col = 0; col <= precision.w; col++) {
  32288. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32289. position.y = 0;
  32290. positions.push(position.x, position.y, position.z);
  32291. normals.push(normal.x, normal.y, normal.z);
  32292. uvs.push(col / precision.w, row / precision.h);
  32293. }
  32294. }
  32295. }
  32296. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32297. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32298. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32299. }
  32300. }
  32301. // Result
  32302. var vertexData = new VertexData();
  32303. vertexData.indices = indices;
  32304. vertexData.positions = positions;
  32305. vertexData.normals = normals;
  32306. vertexData.uvs = uvs;
  32307. return vertexData;
  32308. };
  32309. VertexData.CreateGroundFromHeightMap = function (options) {
  32310. var indices = [];
  32311. var positions = [];
  32312. var normals = [];
  32313. var uvs = [];
  32314. var row, col;
  32315. // Vertices
  32316. for (row = 0; row <= options.subdivisions; row++) {
  32317. for (col = 0; col <= options.subdivisions; col++) {
  32318. 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));
  32319. // Compute height
  32320. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32321. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32322. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32323. var r = options.buffer[pos] / 255.0;
  32324. var g = options.buffer[pos + 1] / 255.0;
  32325. var b = options.buffer[pos + 2] / 255.0;
  32326. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32327. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32328. // Add vertex
  32329. positions.push(position.x, position.y, position.z);
  32330. normals.push(0, 0, 0);
  32331. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32332. }
  32333. }
  32334. // Indices
  32335. for (row = 0; row < options.subdivisions; row++) {
  32336. for (col = 0; col < options.subdivisions; col++) {
  32337. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32338. indices.push(col + 1 + row * (options.subdivisions + 1));
  32339. indices.push(col + row * (options.subdivisions + 1));
  32340. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32341. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32342. indices.push(col + row * (options.subdivisions + 1));
  32343. }
  32344. }
  32345. // Normals
  32346. VertexData.ComputeNormals(positions, indices, normals);
  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. VertexData.CreatePlane = function (options) {
  32356. var indices = [];
  32357. var positions = [];
  32358. var normals = [];
  32359. var uvs = [];
  32360. var width = options.width || options.size || 1;
  32361. var height = options.height || options.size || 1;
  32362. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32363. // Vertices
  32364. var halfWidth = width / 2.0;
  32365. var halfHeight = height / 2.0;
  32366. positions.push(-halfWidth, -halfHeight, 0);
  32367. normals.push(0, 0, -1.0);
  32368. uvs.push(0.0, 0.0);
  32369. positions.push(halfWidth, -halfHeight, 0);
  32370. normals.push(0, 0, -1.0);
  32371. uvs.push(1.0, 0.0);
  32372. positions.push(halfWidth, halfHeight, 0);
  32373. normals.push(0, 0, -1.0);
  32374. uvs.push(1.0, 1.0);
  32375. positions.push(-halfWidth, halfHeight, 0);
  32376. normals.push(0, 0, -1.0);
  32377. uvs.push(0.0, 1.0);
  32378. // Indices
  32379. indices.push(0);
  32380. indices.push(1);
  32381. indices.push(2);
  32382. indices.push(0);
  32383. indices.push(2);
  32384. indices.push(3);
  32385. // Sides
  32386. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32387. // Result
  32388. var vertexData = new VertexData();
  32389. vertexData.indices = indices;
  32390. vertexData.positions = positions;
  32391. vertexData.normals = normals;
  32392. vertexData.uvs = uvs;
  32393. return vertexData;
  32394. };
  32395. VertexData.CreateDisc = function (options) {
  32396. var positions = [];
  32397. var indices = [];
  32398. var normals = [];
  32399. var uvs = [];
  32400. var radius = options.radius || 0.5;
  32401. var tessellation = options.tessellation || 64;
  32402. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32403. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32404. // positions and uvs
  32405. positions.push(0, 0, 0); // disc center first
  32406. uvs.push(0.5, 0.5);
  32407. var theta = Math.PI * 2 * arc;
  32408. var step = theta / tessellation;
  32409. for (var a = 0; a < theta; a += step) {
  32410. var x = Math.cos(a);
  32411. var y = Math.sin(a);
  32412. var u = (x + 1) / 2;
  32413. var v = (1 - y) / 2;
  32414. positions.push(radius * x, radius * y, 0);
  32415. uvs.push(u, v);
  32416. }
  32417. if (arc === 1) {
  32418. positions.push(positions[3], positions[4], positions[5]); // close the circle
  32419. uvs.push(uvs[2], uvs[3]);
  32420. }
  32421. //indices
  32422. var vertexNb = positions.length / 3;
  32423. for (var i = 1; i < vertexNb - 1; i++) {
  32424. indices.push(i + 1, 0, i);
  32425. }
  32426. // result
  32427. VertexData.ComputeNormals(positions, indices, normals);
  32428. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32429. var vertexData = new VertexData();
  32430. vertexData.indices = indices;
  32431. vertexData.positions = positions;
  32432. vertexData.normals = normals;
  32433. vertexData.uvs = uvs;
  32434. return vertexData;
  32435. };
  32436. VertexData.CreateIcoSphere = function (options) {
  32437. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32438. var radius = options.radius || 1;
  32439. var flat = (options.flat === undefined) ? true : options.flat;
  32440. var subdivisions = options.subdivisions || 4;
  32441. var radiusX = options.radiusX || radius;
  32442. var radiusY = options.radiusY || radius;
  32443. var radiusZ = options.radiusZ || radius;
  32444. var t = (1 + Math.sqrt(5)) / 2;
  32445. // 12 vertex x,y,z
  32446. var ico_vertices = [
  32447. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  32448. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  32449. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  32450. ];
  32451. // index of 3 vertex makes a face of icopshere
  32452. var ico_indices = [
  32453. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  32454. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  32455. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  32456. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  32457. ];
  32458. // vertex for uv have aliased position, not for UV
  32459. var vertices_unalias_id = [
  32460. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  32461. // vertex alias
  32462. 0,
  32463. 2,
  32464. 3,
  32465. 3,
  32466. 3,
  32467. 4,
  32468. 7,
  32469. 8,
  32470. 9,
  32471. 9,
  32472. 10,
  32473. 11 // 23: B + 12
  32474. ];
  32475. // uv as integer step (not pixels !)
  32476. var ico_vertexuv = [
  32477. 5, 1, 3, 1, 6, 4, 0, 0,
  32478. 5, 3, 4, 2, 2, 2, 4, 0,
  32479. 2, 0, 1, 1, 6, 0, 6, 2,
  32480. // vertex alias (for same vertex on different faces)
  32481. 0, 4,
  32482. 3, 3,
  32483. 4, 4,
  32484. 3, 1,
  32485. 4, 2,
  32486. 4, 4,
  32487. 0, 2,
  32488. 1, 1,
  32489. 2, 2,
  32490. 3, 3,
  32491. 1, 3,
  32492. 2, 4 // 23: B + 12
  32493. ];
  32494. // Vertices[0, 1, ...9, A, B] : position on UV plane
  32495. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  32496. // First island of uv mapping
  32497. // v = 4h 3+ 2
  32498. // v = 3h 9+ 4
  32499. // v = 2h 9+ 5 B
  32500. // v = 1h 9 1 0
  32501. // v = 0h 3 8 7 A
  32502. // u = 0 1 2 3 4 5 6 *a
  32503. // Second island of uv mapping
  32504. // v = 4h 0+ B+ 4+
  32505. // v = 3h A+ 2+
  32506. // v = 2h 7+ 6 3+
  32507. // v = 1h 8+ 3+
  32508. // v = 0h
  32509. // u = 0 1 2 3 4 5 6 *a
  32510. // Face layout on texture UV mapping
  32511. // ============
  32512. // \ 4 /\ 16 / ======
  32513. // \ / \ / /\ 11 /
  32514. // \/ 7 \/ / \ /
  32515. // ======= / 10 \/
  32516. // /\ 17 /\ =======
  32517. // / \ / \ \ 15 /\
  32518. // / 8 \/ 12 \ \ / \
  32519. // ============ \/ 6 \
  32520. // \ 18 /\ ============
  32521. // \ / \ \ 5 /\ 0 /
  32522. // \/ 13 \ \ / \ /
  32523. // ======= \/ 1 \/
  32524. // =============
  32525. // /\ 19 /\ 2 /\
  32526. // / \ / \ / \
  32527. // / 14 \/ 9 \/ 3 \
  32528. // ===================
  32529. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32530. var ustep = 138 / 1024;
  32531. var vstep = 239 / 1024;
  32532. var uoffset = 60 / 1024;
  32533. var voffset = 26 / 1024;
  32534. // Second island should have margin, not to touch the first island
  32535. // avoid any borderline artefact in pixel rounding
  32536. var island_u_offset = -40 / 1024;
  32537. var island_v_offset = +20 / 1024;
  32538. // face is either island 0 or 1 :
  32539. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32540. var island = [
  32541. 0, 0, 0, 0, 1,
  32542. 0, 0, 1, 1, 0,
  32543. 0, 0, 1, 1, 0,
  32544. 0, 1, 1, 1, 0 // 15 - 19
  32545. ];
  32546. var indices = [];
  32547. var positions = [];
  32548. var normals = [];
  32549. var uvs = [];
  32550. var current_indice = 0;
  32551. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32552. var face_vertex_pos = new Array(3);
  32553. var face_vertex_uv = new Array(3);
  32554. var v012;
  32555. for (v012 = 0; v012 < 3; v012++) {
  32556. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32557. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32558. }
  32559. // create all with normals
  32560. for (var face = 0; face < 20; face++) {
  32561. // 3 vertex per face
  32562. for (v012 = 0; v012 < 3; v012++) {
  32563. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32564. var v_id = ico_indices[3 * face + v012];
  32565. // vertex have 3D position (x,y,z)
  32566. 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]);
  32567. // Normalize to get normal, then scale to radius
  32568. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32569. // uv Coordinates from vertex ID
  32570. 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);
  32571. }
  32572. // Subdivide the face (interpolate pos, norm, uv)
  32573. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32574. // - norm is linear interpolation of vertex corner normal
  32575. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32576. // - uv is linear interpolation
  32577. //
  32578. // Topology is as below for sub-divide by 2
  32579. // vertex shown as v0,v1,v2
  32580. // interp index is i1 to progress in range [v0,v1[
  32581. // interp index is i2 to progress in range [v0,v2[
  32582. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32583. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32584. //
  32585. //
  32586. // i2 v2
  32587. // ^ ^
  32588. // / / \
  32589. // / / \
  32590. // / / \
  32591. // / / (0,1) \
  32592. // / #---------\
  32593. // / / \ (0,0)'/ \
  32594. // / / \ / \
  32595. // / / \ / \
  32596. // / / (0,0) \ / (1,0) \
  32597. // / #---------#---------\
  32598. // v0 v1
  32599. //
  32600. // --------------------> i1
  32601. //
  32602. // interp of (i1,i2):
  32603. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32604. // along i1 : lerp(x0,x1, i1/(S-i2))
  32605. //
  32606. // centroid of triangle is needed to get help normal computation
  32607. // (c1,c2) are used for centroid location
  32608. var interp_vertex = function (i1, i2, c1, c2) {
  32609. // vertex is interpolated from
  32610. // - face_vertex_pos[0..2]
  32611. // - face_vertex_uv[0..2]
  32612. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32613. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32614. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32615. pos_interp.normalize();
  32616. var vertex_normal;
  32617. if (flat) {
  32618. // in flat mode, recalculate normal as face centroid normal
  32619. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32620. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32621. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32622. }
  32623. else {
  32624. // in smooth mode, recalculate normal from each single vertex position
  32625. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32626. }
  32627. // Vertex normal need correction due to X,Y,Z radius scaling
  32628. vertex_normal.x /= radiusX;
  32629. vertex_normal.y /= radiusY;
  32630. vertex_normal.z /= radiusZ;
  32631. vertex_normal.normalize();
  32632. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32633. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32634. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32635. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32636. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32637. uvs.push(uv_interp.x, uv_interp.y);
  32638. // push each vertex has member of a face
  32639. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32640. indices.push(current_indice);
  32641. current_indice++;
  32642. };
  32643. for (var i2 = 0; i2 < subdivisions; i2++) {
  32644. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32645. // face : (i1,i2) for /\ :
  32646. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32647. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32648. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32649. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32650. if (i1 + i2 + 1 < subdivisions) {
  32651. // face : (i1,i2)' for \/ :
  32652. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32653. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32654. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32655. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32656. }
  32657. }
  32658. }
  32659. }
  32660. // Sides
  32661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32662. // Result
  32663. var vertexData = new VertexData();
  32664. vertexData.indices = indices;
  32665. vertexData.positions = positions;
  32666. vertexData.normals = normals;
  32667. vertexData.uvs = uvs;
  32668. return vertexData;
  32669. };
  32670. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32671. VertexData.CreatePolyhedron = function (options) {
  32672. // provided polyhedron types :
  32673. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32674. // 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)
  32675. var polyhedra = [];
  32676. 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]] };
  32677. 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]] };
  32678. polyhedra[2] = {
  32679. 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]],
  32680. 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]]
  32681. };
  32682. polyhedra[3] = {
  32683. 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]],
  32684. 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]]
  32685. };
  32686. polyhedra[4] = {
  32687. 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]],
  32688. 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]]
  32689. };
  32690. 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]] };
  32691. 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]] };
  32692. 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]] };
  32693. 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]] };
  32694. 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]] };
  32695. 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]] };
  32696. 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]] };
  32697. 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]] };
  32698. 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]] };
  32699. polyhedra[14] = {
  32700. 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]],
  32701. 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]]
  32702. };
  32703. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32704. var size = options.size;
  32705. var sizeX = options.sizeX || size || 1;
  32706. var sizeY = options.sizeY || size || 1;
  32707. var sizeZ = options.sizeZ || size || 1;
  32708. var data = options.custom || polyhedra[type];
  32709. var nbfaces = data.face.length;
  32710. var faceUV = options.faceUV || new Array(nbfaces);
  32711. var faceColors = options.faceColors;
  32712. var flat = (options.flat === undefined) ? true : options.flat;
  32713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32714. var positions = [];
  32715. var indices = [];
  32716. var normals = [];
  32717. var uvs = [];
  32718. var colors = [];
  32719. var index = 0;
  32720. var faceIdx = 0; // face cursor in the array "indexes"
  32721. var indexes = [];
  32722. var i = 0;
  32723. var f = 0;
  32724. var u, v, ang, x, y, tmp;
  32725. // default face colors and UV if undefined
  32726. if (flat) {
  32727. for (f = 0; f < nbfaces; f++) {
  32728. if (faceColors && faceColors[f] === undefined) {
  32729. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32730. }
  32731. if (faceUV && faceUV[f] === undefined) {
  32732. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32733. }
  32734. }
  32735. }
  32736. if (!flat) {
  32737. for (i = 0; i < data.vertex.length; i++) {
  32738. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32739. uvs.push(0, 0);
  32740. }
  32741. for (f = 0; f < nbfaces; f++) {
  32742. for (i = 0; i < data.face[f].length - 2; i++) {
  32743. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32744. }
  32745. }
  32746. }
  32747. else {
  32748. for (f = 0; f < nbfaces; f++) {
  32749. var fl = data.face[f].length; // number of vertices of the current face
  32750. ang = 2 * Math.PI / fl;
  32751. x = 0.5 * Math.tan(ang / 2);
  32752. y = 0.5;
  32753. // positions, uvs, colors
  32754. for (i = 0; i < fl; i++) {
  32755. // positions
  32756. 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);
  32757. indexes.push(index);
  32758. index++;
  32759. // uvs
  32760. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32761. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32762. uvs.push(u, v);
  32763. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32764. y = x * Math.sin(ang) + y * Math.cos(ang);
  32765. x = tmp;
  32766. // colors
  32767. if (faceColors) {
  32768. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32769. }
  32770. }
  32771. // indices from indexes
  32772. for (i = 0; i < fl - 2; i++) {
  32773. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32774. }
  32775. faceIdx += fl;
  32776. }
  32777. }
  32778. VertexData.ComputeNormals(positions, indices, normals);
  32779. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32780. var vertexData = new VertexData();
  32781. vertexData.positions = positions;
  32782. vertexData.indices = indices;
  32783. vertexData.normals = normals;
  32784. vertexData.uvs = uvs;
  32785. if (faceColors && flat) {
  32786. vertexData.colors = colors;
  32787. }
  32788. return vertexData;
  32789. };
  32790. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32791. VertexData.CreateTorusKnot = function (options) {
  32792. var indices = [];
  32793. var positions = [];
  32794. var normals = [];
  32795. var uvs = [];
  32796. var radius = options.radius || 2;
  32797. var tube = options.tube || 0.5;
  32798. var radialSegments = options.radialSegments || 32;
  32799. var tubularSegments = options.tubularSegments || 32;
  32800. var p = options.p || 2;
  32801. var q = options.q || 3;
  32802. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32803. // Helper
  32804. var getPos = function (angle) {
  32805. var cu = Math.cos(angle);
  32806. var su = Math.sin(angle);
  32807. var quOverP = q / p * angle;
  32808. var cs = Math.cos(quOverP);
  32809. var tx = radius * (2 + cs) * 0.5 * cu;
  32810. var ty = radius * (2 + cs) * su * 0.5;
  32811. var tz = radius * Math.sin(quOverP) * 0.5;
  32812. return new BABYLON.Vector3(tx, ty, tz);
  32813. };
  32814. // Vertices
  32815. var i;
  32816. var j;
  32817. for (i = 0; i <= radialSegments; i++) {
  32818. var modI = i % radialSegments;
  32819. var u = modI / radialSegments * 2 * p * Math.PI;
  32820. var p1 = getPos(u);
  32821. var p2 = getPos(u + 0.01);
  32822. var tang = p2.subtract(p1);
  32823. var n = p2.add(p1);
  32824. var bitan = BABYLON.Vector3.Cross(tang, n);
  32825. n = BABYLON.Vector3.Cross(bitan, tang);
  32826. bitan.normalize();
  32827. n.normalize();
  32828. for (j = 0; j < tubularSegments; j++) {
  32829. var modJ = j % tubularSegments;
  32830. var v = modJ / tubularSegments * 2 * Math.PI;
  32831. var cx = -tube * Math.cos(v);
  32832. var cy = tube * Math.sin(v);
  32833. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32834. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32835. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32836. uvs.push(i / radialSegments);
  32837. uvs.push(j / tubularSegments);
  32838. }
  32839. }
  32840. for (i = 0; i < radialSegments; i++) {
  32841. for (j = 0; j < tubularSegments; j++) {
  32842. var jNext = (j + 1) % tubularSegments;
  32843. var a = i * tubularSegments + j;
  32844. var b = (i + 1) * tubularSegments + j;
  32845. var c = (i + 1) * tubularSegments + jNext;
  32846. var d = i * tubularSegments + jNext;
  32847. indices.push(d);
  32848. indices.push(b);
  32849. indices.push(a);
  32850. indices.push(d);
  32851. indices.push(c);
  32852. indices.push(b);
  32853. }
  32854. }
  32855. // Normals
  32856. VertexData.ComputeNormals(positions, indices, normals);
  32857. // Sides
  32858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32859. // Result
  32860. var vertexData = new VertexData();
  32861. vertexData.indices = indices;
  32862. vertexData.positions = positions;
  32863. vertexData.normals = normals;
  32864. vertexData.uvs = uvs;
  32865. return vertexData;
  32866. };
  32867. // Tools
  32868. /**
  32869. * @param {any} - positions (number[] or Float32Array)
  32870. * @param {any} - indices (number[] or Uint16Array)
  32871. * @param {any} - normals (number[] or Float32Array)
  32872. */
  32873. VertexData.ComputeNormals = function (positions, indices, normals) {
  32874. var index = 0;
  32875. var p1p2x = 0.0;
  32876. var p1p2y = 0.0;
  32877. var p1p2z = 0.0;
  32878. var p3p2x = 0.0;
  32879. var p3p2y = 0.0;
  32880. var p3p2z = 0.0;
  32881. var faceNormalx = 0.0;
  32882. var faceNormaly = 0.0;
  32883. var faceNormalz = 0.0;
  32884. var length = 0.0;
  32885. var i1 = 0;
  32886. var i2 = 0;
  32887. var i3 = 0;
  32888. for (index = 0; index < positions.length; index++) {
  32889. normals[index] = 0.0;
  32890. }
  32891. // indice triplet = 1 face
  32892. var nbFaces = indices.length / 3;
  32893. for (index = 0; index < nbFaces; index++) {
  32894. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32895. i2 = indices[index * 3 + 1];
  32896. i3 = indices[index * 3 + 2];
  32897. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32898. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32899. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32900. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32901. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32902. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32903. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32904. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32905. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32906. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32907. length = (length === 0) ? 1.0 : length;
  32908. faceNormalx /= length; // normalize this normal
  32909. faceNormaly /= length;
  32910. faceNormalz /= length;
  32911. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32912. normals[i1 * 3 + 1] += faceNormaly;
  32913. normals[i1 * 3 + 2] += faceNormalz;
  32914. normals[i2 * 3] += faceNormalx;
  32915. normals[i2 * 3 + 1] += faceNormaly;
  32916. normals[i2 * 3 + 2] += faceNormalz;
  32917. normals[i3 * 3] += faceNormalx;
  32918. normals[i3 * 3 + 1] += faceNormaly;
  32919. normals[i3 * 3 + 2] += faceNormalz;
  32920. }
  32921. // last normalization of each normal
  32922. for (index = 0; index < normals.length / 3; index++) {
  32923. faceNormalx = normals[index * 3];
  32924. faceNormaly = normals[index * 3 + 1];
  32925. faceNormalz = normals[index * 3 + 2];
  32926. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32927. length = (length === 0) ? 1.0 : length;
  32928. faceNormalx /= length;
  32929. faceNormaly /= length;
  32930. faceNormalz /= length;
  32931. normals[index * 3] = faceNormalx;
  32932. normals[index * 3 + 1] = faceNormaly;
  32933. normals[index * 3 + 2] = faceNormalz;
  32934. }
  32935. };
  32936. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32937. var li = indices.length;
  32938. var ln = normals.length;
  32939. var i;
  32940. var n;
  32941. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32942. switch (sideOrientation) {
  32943. case BABYLON.Mesh.FRONTSIDE:
  32944. // nothing changed
  32945. break;
  32946. case BABYLON.Mesh.BACKSIDE:
  32947. var tmp;
  32948. // indices
  32949. for (i = 0; i < li; i += 3) {
  32950. tmp = indices[i];
  32951. indices[i] = indices[i + 2];
  32952. indices[i + 2] = tmp;
  32953. }
  32954. // normals
  32955. for (n = 0; n < ln; n++) {
  32956. normals[n] = -normals[n];
  32957. }
  32958. break;
  32959. case BABYLON.Mesh.DOUBLESIDE:
  32960. // positions
  32961. var lp = positions.length;
  32962. var l = lp / 3;
  32963. for (var p = 0; p < lp; p++) {
  32964. positions[lp + p] = positions[p];
  32965. }
  32966. // indices
  32967. for (i = 0; i < li; i += 3) {
  32968. indices[i + li] = indices[i + 2] + l;
  32969. indices[i + 1 + li] = indices[i + 1] + l;
  32970. indices[i + 2 + li] = indices[i] + l;
  32971. }
  32972. // normals
  32973. for (n = 0; n < ln; n++) {
  32974. normals[ln + n] = -normals[n];
  32975. }
  32976. // uvs
  32977. var lu = uvs.length;
  32978. for (var u = 0; u < lu; u++) {
  32979. uvs[u + lu] = uvs[u];
  32980. }
  32981. break;
  32982. }
  32983. };
  32984. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32985. var vertexData = new VertexData();
  32986. // positions
  32987. var positions = parsedVertexData.positions;
  32988. if (positions) {
  32989. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32990. }
  32991. // normals
  32992. var normals = parsedVertexData.normals;
  32993. if (normals) {
  32994. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32995. }
  32996. // uvs
  32997. var uvs = parsedVertexData.uvs;
  32998. if (uvs) {
  32999. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33000. }
  33001. // uv2s
  33002. var uv2s = parsedVertexData.uv2s;
  33003. if (uv2s) {
  33004. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33005. }
  33006. // uv3s
  33007. var uv3s = parsedVertexData.uv3s;
  33008. if (uv3s) {
  33009. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33010. }
  33011. // uv4s
  33012. var uv4s = parsedVertexData.uv4s;
  33013. if (uv4s) {
  33014. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33015. }
  33016. // uv5s
  33017. var uv5s = parsedVertexData.uv5s;
  33018. if (uv5s) {
  33019. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33020. }
  33021. // uv6s
  33022. var uv6s = parsedVertexData.uv6s;
  33023. if (uv6s) {
  33024. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33025. }
  33026. // colors
  33027. var colors = parsedVertexData.colors;
  33028. if (colors) {
  33029. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33030. }
  33031. // matricesIndices
  33032. var matricesIndices = parsedVertexData.matricesIndices;
  33033. if (matricesIndices) {
  33034. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33035. }
  33036. // matricesWeights
  33037. var matricesWeights = parsedVertexData.matricesWeights;
  33038. if (matricesWeights) {
  33039. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33040. }
  33041. // indices
  33042. var indices = parsedVertexData.indices;
  33043. if (indices) {
  33044. vertexData.indices = indices;
  33045. }
  33046. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33047. };
  33048. return VertexData;
  33049. }());
  33050. BABYLON.VertexData = VertexData;
  33051. })(BABYLON || (BABYLON = {}));
  33052. var BABYLON;
  33053. (function (BABYLON) {
  33054. var Tags = (function () {
  33055. function Tags() {
  33056. }
  33057. Tags.EnableFor = function (obj) {
  33058. obj._tags = obj._tags || {};
  33059. obj.hasTags = function () {
  33060. return Tags.HasTags(obj);
  33061. };
  33062. obj.addTags = function (tagsString) {
  33063. return Tags.AddTagsTo(obj, tagsString);
  33064. };
  33065. obj.removeTags = function (tagsString) {
  33066. return Tags.RemoveTagsFrom(obj, tagsString);
  33067. };
  33068. obj.matchesTagsQuery = function (tagsQuery) {
  33069. return Tags.MatchesQuery(obj, tagsQuery);
  33070. };
  33071. };
  33072. Tags.DisableFor = function (obj) {
  33073. delete obj._tags;
  33074. delete obj.hasTags;
  33075. delete obj.addTags;
  33076. delete obj.removeTags;
  33077. delete obj.matchesTagsQuery;
  33078. };
  33079. Tags.HasTags = function (obj) {
  33080. if (!obj._tags) {
  33081. return false;
  33082. }
  33083. return !BABYLON.Tools.IsEmpty(obj._tags);
  33084. };
  33085. Tags.GetTags = function (obj, asString) {
  33086. if (asString === void 0) { asString = true; }
  33087. if (!obj._tags) {
  33088. return null;
  33089. }
  33090. if (asString) {
  33091. var tagsArray = [];
  33092. for (var tag in obj._tags) {
  33093. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  33094. tagsArray.push(tag);
  33095. }
  33096. }
  33097. return tagsArray.join(" ");
  33098. }
  33099. else {
  33100. return obj._tags;
  33101. }
  33102. };
  33103. // the tags 'true' and 'false' are reserved and cannot be used as tags
  33104. // a tag cannot start with '||', '&&', and '!'
  33105. // it cannot contain whitespaces
  33106. Tags.AddTagsTo = function (obj, tagsString) {
  33107. if (!tagsString) {
  33108. return;
  33109. }
  33110. if (typeof tagsString !== "string") {
  33111. return;
  33112. }
  33113. var tags = tagsString.split(" ");
  33114. tags.forEach(function (tag, index, array) {
  33115. Tags._AddTagTo(obj, tag);
  33116. });
  33117. };
  33118. Tags._AddTagTo = function (obj, tag) {
  33119. tag = tag.trim();
  33120. if (tag === "" || tag === "true" || tag === "false") {
  33121. return;
  33122. }
  33123. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  33124. return;
  33125. }
  33126. Tags.EnableFor(obj);
  33127. obj._tags[tag] = true;
  33128. };
  33129. Tags.RemoveTagsFrom = function (obj, tagsString) {
  33130. if (!Tags.HasTags(obj)) {
  33131. return;
  33132. }
  33133. var tags = tagsString.split(" ");
  33134. for (var t in tags) {
  33135. Tags._RemoveTagFrom(obj, tags[t]);
  33136. }
  33137. };
  33138. Tags._RemoveTagFrom = function (obj, tag) {
  33139. delete obj._tags[tag];
  33140. };
  33141. Tags.MatchesQuery = function (obj, tagsQuery) {
  33142. if (tagsQuery === undefined) {
  33143. return true;
  33144. }
  33145. if (tagsQuery === "") {
  33146. return Tags.HasTags(obj);
  33147. }
  33148. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  33149. };
  33150. return Tags;
  33151. }());
  33152. BABYLON.Tags = Tags;
  33153. })(BABYLON || (BABYLON = {}));
  33154. var BABYLON;
  33155. (function (BABYLON) {
  33156. var Internals;
  33157. (function (Internals) {
  33158. var AndOrNotEvaluator = (function () {
  33159. function AndOrNotEvaluator() {
  33160. }
  33161. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  33162. if (!query.match(/\([^\(\)]*\)/g)) {
  33163. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  33164. }
  33165. else {
  33166. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  33167. // remove parenthesis
  33168. r = r.slice(1, r.length - 1);
  33169. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  33170. });
  33171. }
  33172. if (query === "true") {
  33173. return true;
  33174. }
  33175. if (query === "false") {
  33176. return false;
  33177. }
  33178. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  33179. };
  33180. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  33181. evaluateCallback = evaluateCallback || (function (r) {
  33182. return r === "true" ? true : false;
  33183. });
  33184. var result;
  33185. var or = parenthesisContent.split("||");
  33186. for (var i in or) {
  33187. if (or.hasOwnProperty(i)) {
  33188. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  33189. var and = ori.split("&&");
  33190. if (and.length > 1) {
  33191. for (var j = 0; j < and.length; ++j) {
  33192. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  33193. if (andj !== "true" && andj !== "false") {
  33194. if (andj[0] === "!") {
  33195. result = !evaluateCallback(andj.substring(1));
  33196. }
  33197. else {
  33198. result = evaluateCallback(andj);
  33199. }
  33200. }
  33201. else {
  33202. result = andj === "true" ? true : false;
  33203. }
  33204. if (!result) {
  33205. ori = "false";
  33206. break;
  33207. }
  33208. }
  33209. }
  33210. if (result || ori === "true") {
  33211. result = true;
  33212. break;
  33213. }
  33214. // result equals false (or undefined)
  33215. if (ori !== "true" && ori !== "false") {
  33216. if (ori[0] === "!") {
  33217. result = !evaluateCallback(ori.substring(1));
  33218. }
  33219. else {
  33220. result = evaluateCallback(ori);
  33221. }
  33222. }
  33223. else {
  33224. result = ori === "true" ? true : false;
  33225. }
  33226. }
  33227. }
  33228. // the whole parenthesis scope is replaced by 'true' or 'false'
  33229. return result ? "true" : "false";
  33230. };
  33231. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  33232. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  33233. // remove whitespaces
  33234. r = r.replace(/[\s]/g, function () { return ""; });
  33235. return r.length % 2 ? "!" : "";
  33236. });
  33237. booleanString = booleanString.trim();
  33238. if (booleanString === "!true") {
  33239. booleanString = "false";
  33240. }
  33241. else if (booleanString === "!false") {
  33242. booleanString = "true";
  33243. }
  33244. return booleanString;
  33245. };
  33246. return AndOrNotEvaluator;
  33247. }());
  33248. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  33249. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33250. })(BABYLON || (BABYLON = {}));
  33251. var BABYLON;
  33252. (function (BABYLON) {
  33253. var PostProcessRenderPass = (function () {
  33254. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  33255. this._enabled = true;
  33256. this._refCount = 0;
  33257. this._name = name;
  33258. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  33259. this.setRenderList(renderList);
  33260. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  33261. this._renderTexture.onAfterRenderObservable.add(afterRender);
  33262. this._scene = scene;
  33263. this._renderList = renderList;
  33264. }
  33265. // private
  33266. PostProcessRenderPass.prototype._incRefCount = function () {
  33267. if (this._refCount === 0) {
  33268. this._scene.customRenderTargets.push(this._renderTexture);
  33269. }
  33270. return ++this._refCount;
  33271. };
  33272. PostProcessRenderPass.prototype._decRefCount = function () {
  33273. this._refCount--;
  33274. if (this._refCount <= 0) {
  33275. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  33276. }
  33277. return this._refCount;
  33278. };
  33279. PostProcessRenderPass.prototype._update = function () {
  33280. this.setRenderList(this._renderList);
  33281. };
  33282. // public
  33283. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  33284. this._renderTexture.renderList = renderList;
  33285. };
  33286. PostProcessRenderPass.prototype.getRenderTexture = function () {
  33287. return this._renderTexture;
  33288. };
  33289. return PostProcessRenderPass;
  33290. }());
  33291. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  33292. })(BABYLON || (BABYLON = {}));
  33293. var BABYLON;
  33294. (function (BABYLON) {
  33295. var PostProcessRenderEffect = (function () {
  33296. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  33297. this._engine = engine;
  33298. this._name = name;
  33299. this._singleInstance = singleInstance || true;
  33300. this._getPostProcess = getPostProcess;
  33301. this._cameras = [];
  33302. this._indicesForCamera = [];
  33303. this._postProcesses = {};
  33304. this._renderPasses = {};
  33305. this._renderEffectAsPasses = {};
  33306. }
  33307. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  33308. get: function () {
  33309. for (var index in this._postProcesses) {
  33310. if (!this._postProcesses[index].isSupported) {
  33311. return false;
  33312. }
  33313. }
  33314. return true;
  33315. },
  33316. enumerable: true,
  33317. configurable: true
  33318. });
  33319. PostProcessRenderEffect.prototype._update = function () {
  33320. for (var renderPassName in this._renderPasses) {
  33321. this._renderPasses[renderPassName]._update();
  33322. }
  33323. };
  33324. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  33325. this._renderPasses[renderPass._name] = renderPass;
  33326. this._linkParameters();
  33327. };
  33328. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  33329. delete this._renderPasses[renderPass._name];
  33330. this._linkParameters();
  33331. };
  33332. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  33333. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  33334. this._linkParameters();
  33335. };
  33336. PostProcessRenderEffect.prototype.getPass = function (passName) {
  33337. for (var renderPassName in this._renderPasses) {
  33338. if (renderPassName === passName) {
  33339. return this._renderPasses[passName];
  33340. }
  33341. }
  33342. };
  33343. PostProcessRenderEffect.prototype.emptyPasses = function () {
  33344. this._renderPasses = {};
  33345. this._linkParameters();
  33346. };
  33347. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  33348. var cameraKey;
  33349. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33350. for (var i = 0; i < _cam.length; i++) {
  33351. var camera = _cam[i];
  33352. var cameraName = camera.name;
  33353. if (this._singleInstance) {
  33354. cameraKey = 0;
  33355. }
  33356. else {
  33357. cameraKey = cameraName;
  33358. }
  33359. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  33360. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  33361. if (!this._indicesForCamera[cameraName]) {
  33362. this._indicesForCamera[cameraName] = [];
  33363. }
  33364. this._indicesForCamera[cameraName].push(index);
  33365. if (this._cameras.indexOf(camera) === -1) {
  33366. this._cameras[cameraName] = camera;
  33367. }
  33368. for (var passName in this._renderPasses) {
  33369. this._renderPasses[passName]._incRefCount();
  33370. }
  33371. }
  33372. this._linkParameters();
  33373. };
  33374. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  33375. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33376. for (var i = 0; i < _cam.length; i++) {
  33377. var camera = _cam[i];
  33378. var cameraName = camera.name;
  33379. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33380. var index = this._cameras.indexOf(cameraName);
  33381. this._indicesForCamera.splice(index, 1);
  33382. this._cameras.splice(index, 1);
  33383. for (var passName in this._renderPasses) {
  33384. this._renderPasses[passName]._decRefCount();
  33385. }
  33386. }
  33387. };
  33388. PostProcessRenderEffect.prototype._enable = function (cameras) {
  33389. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33390. for (var i = 0; i < _cam.length; i++) {
  33391. var camera = _cam[i];
  33392. var cameraName = camera.name;
  33393. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  33394. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  33395. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  33396. }
  33397. }
  33398. for (var passName in this._renderPasses) {
  33399. this._renderPasses[passName]._incRefCount();
  33400. }
  33401. }
  33402. };
  33403. PostProcessRenderEffect.prototype._disable = function (cameras) {
  33404. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33405. for (var i = 0; i < _cam.length; i++) {
  33406. var camera = _cam[i];
  33407. var cameraName = camera.Name;
  33408. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33409. for (var passName in this._renderPasses) {
  33410. this._renderPasses[passName]._decRefCount();
  33411. }
  33412. }
  33413. };
  33414. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  33415. if (this._singleInstance) {
  33416. return this._postProcesses[0];
  33417. }
  33418. else {
  33419. return this._postProcesses[camera.name];
  33420. }
  33421. };
  33422. PostProcessRenderEffect.prototype._linkParameters = function () {
  33423. var _this = this;
  33424. for (var index in this._postProcesses) {
  33425. if (this.applyParameters) {
  33426. this.applyParameters(this._postProcesses[index]);
  33427. }
  33428. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  33429. _this._linkTextures(effect);
  33430. });
  33431. }
  33432. };
  33433. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  33434. for (var renderPassName in this._renderPasses) {
  33435. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  33436. }
  33437. for (var renderEffectName in this._renderEffectAsPasses) {
  33438. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  33439. }
  33440. };
  33441. return PostProcessRenderEffect;
  33442. }());
  33443. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  33444. })(BABYLON || (BABYLON = {}));
  33445. var BABYLON;
  33446. (function (BABYLON) {
  33447. var PostProcessRenderPipeline = (function () {
  33448. function PostProcessRenderPipeline(engine, name) {
  33449. this._engine = engine;
  33450. this._name = name;
  33451. this._renderEffects = {};
  33452. this._renderEffectsForIsolatedPass = {};
  33453. this._cameras = [];
  33454. }
  33455. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  33456. get: function () {
  33457. for (var renderEffectName in this._renderEffects) {
  33458. if (!this._renderEffects[renderEffectName].isSupported) {
  33459. return false;
  33460. }
  33461. }
  33462. return true;
  33463. },
  33464. enumerable: true,
  33465. configurable: true
  33466. });
  33467. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  33468. this._renderEffects[renderEffect._name] = renderEffect;
  33469. };
  33470. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  33471. var renderEffects = this._renderEffects[renderEffectName];
  33472. if (!renderEffects) {
  33473. return;
  33474. }
  33475. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33476. };
  33477. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  33478. var renderEffects = this._renderEffects[renderEffectName];
  33479. if (!renderEffects) {
  33480. return;
  33481. }
  33482. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33483. };
  33484. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  33485. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33486. var indicesToDelete = [];
  33487. var i;
  33488. for (i = 0; i < _cam.length; i++) {
  33489. var camera = _cam[i];
  33490. var cameraName = camera.name;
  33491. if (this._cameras.indexOf(camera) === -1) {
  33492. this._cameras[cameraName] = camera;
  33493. }
  33494. else if (unique) {
  33495. indicesToDelete.push(i);
  33496. }
  33497. }
  33498. for (i = 0; i < indicesToDelete.length; i++) {
  33499. cameras.splice(indicesToDelete[i], 1);
  33500. }
  33501. for (var renderEffectName in this._renderEffects) {
  33502. this._renderEffects[renderEffectName]._attachCameras(_cam);
  33503. }
  33504. };
  33505. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  33506. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33507. for (var renderEffectName in this._renderEffects) {
  33508. this._renderEffects[renderEffectName]._detachCameras(_cam);
  33509. }
  33510. for (var i = 0; i < _cam.length; i++) {
  33511. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  33512. }
  33513. };
  33514. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  33515. var _this = this;
  33516. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33517. var pass = null;
  33518. var renderEffectName;
  33519. for (renderEffectName in this._renderEffects) {
  33520. pass = this._renderEffects[renderEffectName].getPass(passName);
  33521. if (pass != null) {
  33522. break;
  33523. }
  33524. }
  33525. if (pass === null) {
  33526. return;
  33527. }
  33528. for (renderEffectName in this._renderEffects) {
  33529. this._renderEffects[renderEffectName]._disable(_cam);
  33530. }
  33531. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  33532. for (var i = 0; i < _cam.length; i++) {
  33533. var camera = _cam[i];
  33534. var cameraName = camera.name;
  33535. 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); });
  33536. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  33537. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  33538. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  33539. }
  33540. };
  33541. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  33542. var _this = this;
  33543. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33544. for (var i = 0; i < _cam.length; i++) {
  33545. var camera = _cam[i];
  33546. var cameraName = camera.name;
  33547. 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); });
  33548. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  33549. }
  33550. for (var renderEffectName in this._renderEffects) {
  33551. this._renderEffects[renderEffectName]._enable(_cam);
  33552. }
  33553. };
  33554. PostProcessRenderPipeline.prototype._update = function () {
  33555. for (var renderEffectName in this._renderEffects) {
  33556. this._renderEffects[renderEffectName]._update();
  33557. }
  33558. for (var i = 0; i < this._cameras.length; i++) {
  33559. var cameraName = this._cameras[i].name;
  33560. if (this._renderEffectsForIsolatedPass[cameraName]) {
  33561. this._renderEffectsForIsolatedPass[cameraName]._update();
  33562. }
  33563. }
  33564. };
  33565. PostProcessRenderPipeline.prototype.dispose = function () {
  33566. // Must be implemented by children
  33567. };
  33568. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33569. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33570. return PostProcessRenderPipeline;
  33571. }());
  33572. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33573. })(BABYLON || (BABYLON = {}));
  33574. var BABYLON;
  33575. (function (BABYLON) {
  33576. var PostProcessRenderPipelineManager = (function () {
  33577. function PostProcessRenderPipelineManager() {
  33578. this._renderPipelines = {};
  33579. }
  33580. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33581. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33582. };
  33583. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33584. var renderPipeline = this._renderPipelines[renderPipelineName];
  33585. if (!renderPipeline) {
  33586. return;
  33587. }
  33588. renderPipeline._attachCameras(cameras, unique);
  33589. };
  33590. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33591. var renderPipeline = this._renderPipelines[renderPipelineName];
  33592. if (!renderPipeline) {
  33593. return;
  33594. }
  33595. renderPipeline._detachCameras(cameras);
  33596. };
  33597. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33598. var renderPipeline = this._renderPipelines[renderPipelineName];
  33599. if (!renderPipeline) {
  33600. return;
  33601. }
  33602. renderPipeline._enableEffect(renderEffectName, cameras);
  33603. };
  33604. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33605. var renderPipeline = this._renderPipelines[renderPipelineName];
  33606. if (!renderPipeline) {
  33607. return;
  33608. }
  33609. renderPipeline._disableEffect(renderEffectName, cameras);
  33610. };
  33611. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33612. var renderPipeline = this._renderPipelines[renderPipelineName];
  33613. if (!renderPipeline) {
  33614. return;
  33615. }
  33616. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33617. };
  33618. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33619. var renderPipeline = this._renderPipelines[renderPipelineName];
  33620. if (!renderPipeline) {
  33621. return;
  33622. }
  33623. renderPipeline._disableDisplayOnlyPass(cameras);
  33624. };
  33625. PostProcessRenderPipelineManager.prototype.update = function () {
  33626. for (var renderPipelineName in this._renderPipelines) {
  33627. var pipeline = this._renderPipelines[renderPipelineName];
  33628. if (!pipeline.isSupported) {
  33629. pipeline.dispose();
  33630. delete this._renderPipelines[renderPipelineName];
  33631. }
  33632. else {
  33633. pipeline._update();
  33634. }
  33635. }
  33636. };
  33637. return PostProcessRenderPipelineManager;
  33638. }());
  33639. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33640. })(BABYLON || (BABYLON = {}));
  33641. var BABYLON;
  33642. (function (BABYLON) {
  33643. var BoundingBoxRenderer = (function () {
  33644. function BoundingBoxRenderer(scene) {
  33645. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33646. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33647. this.showBackLines = true;
  33648. this.renderList = new BABYLON.SmartArray(32);
  33649. this._vertexBuffers = {};
  33650. this._scene = scene;
  33651. }
  33652. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33653. if (this._colorShader) {
  33654. return;
  33655. }
  33656. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33657. attributes: [BABYLON.VertexBuffer.PositionKind],
  33658. uniforms: ["worldViewProjection", "color"]
  33659. });
  33660. var engine = this._scene.getEngine();
  33661. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33662. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33663. 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]);
  33664. };
  33665. BoundingBoxRenderer.prototype.reset = function () {
  33666. this.renderList.reset();
  33667. };
  33668. BoundingBoxRenderer.prototype.render = function () {
  33669. if (this.renderList.length === 0) {
  33670. return;
  33671. }
  33672. this._prepareRessources();
  33673. if (!this._colorShader.isReady()) {
  33674. return;
  33675. }
  33676. var engine = this._scene.getEngine();
  33677. engine.setDepthWrite(false);
  33678. this._colorShader._preBind();
  33679. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33680. var boundingBox = this.renderList.data[boundingBoxIndex];
  33681. var min = boundingBox.minimum;
  33682. var max = boundingBox.maximum;
  33683. var diff = max.subtract(min);
  33684. var median = min.add(diff.scale(0.5));
  33685. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33686. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33687. .multiply(boundingBox.getWorldMatrix());
  33688. // VBOs
  33689. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33690. if (this.showBackLines) {
  33691. // Back
  33692. engine.setDepthFunctionToGreaterOrEqual();
  33693. this._scene.resetCachedMaterial();
  33694. this._colorShader.setColor4("color", this.backColor.toColor4());
  33695. this._colorShader.bind(worldMatrix);
  33696. // Draw order
  33697. engine.draw(false, 0, 24);
  33698. }
  33699. // Front
  33700. engine.setDepthFunctionToLess();
  33701. this._scene.resetCachedMaterial();
  33702. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33703. this._colorShader.bind(worldMatrix);
  33704. // Draw order
  33705. engine.draw(false, 0, 24);
  33706. }
  33707. this._colorShader.unbind();
  33708. engine.setDepthFunctionToLessOrEqual();
  33709. engine.setDepthWrite(true);
  33710. };
  33711. BoundingBoxRenderer.prototype.dispose = function () {
  33712. if (!this._colorShader) {
  33713. return;
  33714. }
  33715. this._colorShader.dispose();
  33716. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33717. if (buffer) {
  33718. buffer.dispose();
  33719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33720. }
  33721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33722. };
  33723. return BoundingBoxRenderer;
  33724. }());
  33725. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33726. })(BABYLON || (BABYLON = {}));
  33727. var BABYLON;
  33728. (function (BABYLON) {
  33729. var Condition = (function () {
  33730. function Condition(actionManager) {
  33731. this._actionManager = actionManager;
  33732. }
  33733. Condition.prototype.isValid = function () {
  33734. return true;
  33735. };
  33736. Condition.prototype._getProperty = function (propertyPath) {
  33737. return this._actionManager._getProperty(propertyPath);
  33738. };
  33739. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33740. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33741. };
  33742. Condition.prototype.serialize = function () {
  33743. };
  33744. Condition.prototype._serialize = function (serializedCondition) {
  33745. return {
  33746. type: 2,
  33747. children: [],
  33748. name: serializedCondition.name,
  33749. properties: serializedCondition.properties
  33750. };
  33751. };
  33752. return Condition;
  33753. }());
  33754. BABYLON.Condition = Condition;
  33755. var ValueCondition = (function (_super) {
  33756. __extends(ValueCondition, _super);
  33757. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33758. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33759. _super.call(this, actionManager);
  33760. this.propertyPath = propertyPath;
  33761. this.value = value;
  33762. this.operator = operator;
  33763. this._target = target;
  33764. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33765. this._property = this._getProperty(this.propertyPath);
  33766. }
  33767. Object.defineProperty(ValueCondition, "IsEqual", {
  33768. get: function () {
  33769. return ValueCondition._IsEqual;
  33770. },
  33771. enumerable: true,
  33772. configurable: true
  33773. });
  33774. Object.defineProperty(ValueCondition, "IsDifferent", {
  33775. get: function () {
  33776. return ValueCondition._IsDifferent;
  33777. },
  33778. enumerable: true,
  33779. configurable: true
  33780. });
  33781. Object.defineProperty(ValueCondition, "IsGreater", {
  33782. get: function () {
  33783. return ValueCondition._IsGreater;
  33784. },
  33785. enumerable: true,
  33786. configurable: true
  33787. });
  33788. Object.defineProperty(ValueCondition, "IsLesser", {
  33789. get: function () {
  33790. return ValueCondition._IsLesser;
  33791. },
  33792. enumerable: true,
  33793. configurable: true
  33794. });
  33795. // Methods
  33796. ValueCondition.prototype.isValid = function () {
  33797. switch (this.operator) {
  33798. case ValueCondition.IsGreater:
  33799. return this._effectiveTarget[this._property] > this.value;
  33800. case ValueCondition.IsLesser:
  33801. return this._effectiveTarget[this._property] < this.value;
  33802. case ValueCondition.IsEqual:
  33803. case ValueCondition.IsDifferent:
  33804. var check;
  33805. if (this.value.equals) {
  33806. check = this.value.equals(this._effectiveTarget[this._property]);
  33807. }
  33808. else {
  33809. check = this.value === this._effectiveTarget[this._property];
  33810. }
  33811. return this.operator === ValueCondition.IsEqual ? check : !check;
  33812. }
  33813. return false;
  33814. };
  33815. ValueCondition.prototype.serialize = function () {
  33816. return this._serialize({
  33817. name: "ValueCondition",
  33818. properties: [
  33819. BABYLON.Action._GetTargetProperty(this._target),
  33820. { name: "propertyPath", value: this.propertyPath },
  33821. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33822. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33823. ]
  33824. });
  33825. };
  33826. ValueCondition.GetOperatorName = function (operator) {
  33827. switch (operator) {
  33828. case ValueCondition._IsEqual: return "IsEqual";
  33829. case ValueCondition._IsDifferent: return "IsDifferent";
  33830. case ValueCondition._IsGreater: return "IsGreater";
  33831. case ValueCondition._IsLesser: return "IsLesser";
  33832. default: return "";
  33833. }
  33834. };
  33835. // Statics
  33836. ValueCondition._IsEqual = 0;
  33837. ValueCondition._IsDifferent = 1;
  33838. ValueCondition._IsGreater = 2;
  33839. ValueCondition._IsLesser = 3;
  33840. return ValueCondition;
  33841. }(Condition));
  33842. BABYLON.ValueCondition = ValueCondition;
  33843. var PredicateCondition = (function (_super) {
  33844. __extends(PredicateCondition, _super);
  33845. function PredicateCondition(actionManager, predicate) {
  33846. _super.call(this, actionManager);
  33847. this.predicate = predicate;
  33848. }
  33849. PredicateCondition.prototype.isValid = function () {
  33850. return this.predicate();
  33851. };
  33852. return PredicateCondition;
  33853. }(Condition));
  33854. BABYLON.PredicateCondition = PredicateCondition;
  33855. var StateCondition = (function (_super) {
  33856. __extends(StateCondition, _super);
  33857. function StateCondition(actionManager, target, value) {
  33858. _super.call(this, actionManager);
  33859. this.value = value;
  33860. this._target = target;
  33861. }
  33862. // Methods
  33863. StateCondition.prototype.isValid = function () {
  33864. return this._target.state === this.value;
  33865. };
  33866. StateCondition.prototype.serialize = function () {
  33867. return this._serialize({
  33868. name: "StateCondition",
  33869. properties: [
  33870. BABYLON.Action._GetTargetProperty(this._target),
  33871. { name: "value", value: this.value }
  33872. ]
  33873. });
  33874. };
  33875. return StateCondition;
  33876. }(Condition));
  33877. BABYLON.StateCondition = StateCondition;
  33878. })(BABYLON || (BABYLON = {}));
  33879. var BABYLON;
  33880. (function (BABYLON) {
  33881. var Action = (function () {
  33882. function Action(triggerOptions, condition) {
  33883. this.triggerOptions = triggerOptions;
  33884. if (triggerOptions.parameter) {
  33885. this.trigger = triggerOptions.trigger;
  33886. this._triggerParameter = triggerOptions.parameter;
  33887. }
  33888. else {
  33889. this.trigger = triggerOptions;
  33890. }
  33891. this._nextActiveAction = this;
  33892. this._condition = condition;
  33893. }
  33894. // Methods
  33895. Action.prototype._prepare = function () {
  33896. };
  33897. Action.prototype.getTriggerParameter = function () {
  33898. return this._triggerParameter;
  33899. };
  33900. Action.prototype._executeCurrent = function (evt) {
  33901. if (this._nextActiveAction._condition) {
  33902. var condition = this._nextActiveAction._condition;
  33903. var currentRenderId = this._actionManager.getScene().getRenderId();
  33904. // We cache the current evaluation for the current frame
  33905. if (condition._evaluationId === currentRenderId) {
  33906. if (!condition._currentResult) {
  33907. return;
  33908. }
  33909. }
  33910. else {
  33911. condition._evaluationId = currentRenderId;
  33912. if (!condition.isValid()) {
  33913. condition._currentResult = false;
  33914. return;
  33915. }
  33916. condition._currentResult = true;
  33917. }
  33918. }
  33919. this._nextActiveAction.execute(evt);
  33920. this.skipToNextActiveAction();
  33921. };
  33922. Action.prototype.execute = function (evt) {
  33923. };
  33924. Action.prototype.skipToNextActiveAction = function () {
  33925. if (this._nextActiveAction._child) {
  33926. if (!this._nextActiveAction._child._actionManager) {
  33927. this._nextActiveAction._child._actionManager = this._actionManager;
  33928. }
  33929. this._nextActiveAction = this._nextActiveAction._child;
  33930. }
  33931. else {
  33932. this._nextActiveAction = this;
  33933. }
  33934. };
  33935. Action.prototype.then = function (action) {
  33936. this._child = action;
  33937. action._actionManager = this._actionManager;
  33938. action._prepare();
  33939. return action;
  33940. };
  33941. Action.prototype._getProperty = function (propertyPath) {
  33942. return this._actionManager._getProperty(propertyPath);
  33943. };
  33944. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33945. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33946. };
  33947. Action.prototype.serialize = function (parent) {
  33948. };
  33949. // Called by BABYLON.Action objects in serialize(...). Internal use
  33950. Action.prototype._serialize = function (serializedAction, parent) {
  33951. var serializationObject = {
  33952. type: 1,
  33953. children: [],
  33954. name: serializedAction.name,
  33955. properties: serializedAction.properties || []
  33956. };
  33957. // Serialize child
  33958. if (this._child) {
  33959. this._child.serialize(serializationObject);
  33960. }
  33961. // Check if "this" has a condition
  33962. if (this._condition) {
  33963. var serializedCondition = this._condition.serialize();
  33964. serializedCondition.children.push(serializationObject);
  33965. if (parent) {
  33966. parent.children.push(serializedCondition);
  33967. }
  33968. return serializedCondition;
  33969. }
  33970. if (parent) {
  33971. parent.children.push(serializationObject);
  33972. }
  33973. return serializationObject;
  33974. };
  33975. Action._SerializeValueAsString = function (value) {
  33976. if (typeof value === "number") {
  33977. return value.toString();
  33978. }
  33979. if (typeof value === "boolean") {
  33980. return value ? "true" : "false";
  33981. }
  33982. if (value instanceof BABYLON.Vector2) {
  33983. return value.x + ", " + value.y;
  33984. }
  33985. if (value instanceof BABYLON.Vector3) {
  33986. return value.x + ", " + value.y + ", " + value.z;
  33987. }
  33988. if (value instanceof BABYLON.Color3) {
  33989. return value.r + ", " + value.g + ", " + value.b;
  33990. }
  33991. if (value instanceof BABYLON.Color4) {
  33992. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33993. }
  33994. return value; // string
  33995. };
  33996. Action._GetTargetProperty = function (target) {
  33997. return {
  33998. name: "target",
  33999. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  34000. : target instanceof BABYLON.Light ? "LightProperties"
  34001. : target instanceof BABYLON.Camera ? "CameraProperties"
  34002. : "SceneProperties",
  34003. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  34004. };
  34005. };
  34006. return Action;
  34007. }());
  34008. BABYLON.Action = Action;
  34009. })(BABYLON || (BABYLON = {}));
  34010. var BABYLON;
  34011. (function (BABYLON) {
  34012. /**
  34013. * ActionEvent is the event beint sent when an action is triggered.
  34014. */
  34015. var ActionEvent = (function () {
  34016. /**
  34017. * @constructor
  34018. * @param source The mesh or sprite that triggered the action.
  34019. * @param pointerX The X mouse cursor position at the time of the event
  34020. * @param pointerY The Y mouse cursor position at the time of the event
  34021. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  34022. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  34023. */
  34024. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  34025. this.source = source;
  34026. this.pointerX = pointerX;
  34027. this.pointerY = pointerY;
  34028. this.meshUnderPointer = meshUnderPointer;
  34029. this.sourceEvent = sourceEvent;
  34030. this.additionalData = additionalData;
  34031. }
  34032. /**
  34033. * Helper function to auto-create an ActionEvent from a source mesh.
  34034. * @param source The source mesh that triggered the event
  34035. * @param evt {Event} The original (browser) event
  34036. */
  34037. ActionEvent.CreateNew = function (source, evt, additionalData) {
  34038. var scene = source.getScene();
  34039. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34040. };
  34041. /**
  34042. * Helper function to auto-create an ActionEvent from a source mesh.
  34043. * @param source The source sprite that triggered the event
  34044. * @param scene Scene associated with the sprite
  34045. * @param evt {Event} The original (browser) event
  34046. */
  34047. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  34048. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34049. };
  34050. /**
  34051. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  34052. * @param scene the scene where the event occurred
  34053. * @param evt {Event} The original (browser) event
  34054. */
  34055. ActionEvent.CreateNewFromScene = function (scene, evt) {
  34056. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  34057. };
  34058. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  34059. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  34060. };
  34061. return ActionEvent;
  34062. }());
  34063. BABYLON.ActionEvent = ActionEvent;
  34064. /**
  34065. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  34066. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  34067. */
  34068. var ActionManager = (function () {
  34069. function ActionManager(scene) {
  34070. // Members
  34071. this.actions = new Array();
  34072. this.hoverCursor = '';
  34073. this._scene = scene;
  34074. scene._actionManagers.push(this);
  34075. }
  34076. Object.defineProperty(ActionManager, "NothingTrigger", {
  34077. get: function () {
  34078. return ActionManager._NothingTrigger;
  34079. },
  34080. enumerable: true,
  34081. configurable: true
  34082. });
  34083. Object.defineProperty(ActionManager, "OnPickTrigger", {
  34084. get: function () {
  34085. return ActionManager._OnPickTrigger;
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  34091. get: function () {
  34092. return ActionManager._OnLeftPickTrigger;
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  34098. get: function () {
  34099. return ActionManager._OnRightPickTrigger;
  34100. },
  34101. enumerable: true,
  34102. configurable: true
  34103. });
  34104. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  34105. get: function () {
  34106. return ActionManager._OnCenterPickTrigger;
  34107. },
  34108. enumerable: true,
  34109. configurable: true
  34110. });
  34111. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  34112. get: function () {
  34113. return ActionManager._OnPickDownTrigger;
  34114. },
  34115. enumerable: true,
  34116. configurable: true
  34117. });
  34118. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  34119. get: function () {
  34120. return ActionManager._OnPickUpTrigger;
  34121. },
  34122. enumerable: true,
  34123. configurable: true
  34124. });
  34125. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  34126. /// This trigger will only be raised if you also declared a OnPickDown
  34127. get: function () {
  34128. return ActionManager._OnPickOutTrigger;
  34129. },
  34130. enumerable: true,
  34131. configurable: true
  34132. });
  34133. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  34134. get: function () {
  34135. return ActionManager._OnLongPressTrigger;
  34136. },
  34137. enumerable: true,
  34138. configurable: true
  34139. });
  34140. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  34141. get: function () {
  34142. return ActionManager._OnPointerOverTrigger;
  34143. },
  34144. enumerable: true,
  34145. configurable: true
  34146. });
  34147. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  34148. get: function () {
  34149. return ActionManager._OnPointerOutTrigger;
  34150. },
  34151. enumerable: true,
  34152. configurable: true
  34153. });
  34154. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  34155. get: function () {
  34156. return ActionManager._OnEveryFrameTrigger;
  34157. },
  34158. enumerable: true,
  34159. configurable: true
  34160. });
  34161. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  34162. get: function () {
  34163. return ActionManager._OnIntersectionEnterTrigger;
  34164. },
  34165. enumerable: true,
  34166. configurable: true
  34167. });
  34168. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  34169. get: function () {
  34170. return ActionManager._OnIntersectionExitTrigger;
  34171. },
  34172. enumerable: true,
  34173. configurable: true
  34174. });
  34175. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  34176. get: function () {
  34177. return ActionManager._OnKeyDownTrigger;
  34178. },
  34179. enumerable: true,
  34180. configurable: true
  34181. });
  34182. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  34183. get: function () {
  34184. return ActionManager._OnKeyUpTrigger;
  34185. },
  34186. enumerable: true,
  34187. configurable: true
  34188. });
  34189. // Methods
  34190. ActionManager.prototype.dispose = function () {
  34191. var index = this._scene._actionManagers.indexOf(this);
  34192. if (index > -1) {
  34193. this._scene._actionManagers.splice(index, 1);
  34194. }
  34195. };
  34196. ActionManager.prototype.getScene = function () {
  34197. return this._scene;
  34198. };
  34199. /**
  34200. * Does this action manager handles actions of any of the given triggers
  34201. * @param {number[]} triggers - the triggers to be tested
  34202. * @return {boolean} whether one (or more) of the triggers is handeled
  34203. */
  34204. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34205. for (var index = 0; index < this.actions.length; index++) {
  34206. var action = this.actions[index];
  34207. if (triggers.indexOf(action.trigger) > -1) {
  34208. return true;
  34209. }
  34210. }
  34211. return false;
  34212. };
  34213. /**
  34214. * Does this action manager handles actions of a given trigger
  34215. * @param {number} trigger - the trigger to be tested
  34216. * @return {boolean} whether the trigger is handeled
  34217. */
  34218. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34219. for (var index = 0; index < this.actions.length; index++) {
  34220. var action = this.actions[index];
  34221. if (action.trigger === trigger) {
  34222. return true;
  34223. }
  34224. }
  34225. return false;
  34226. };
  34227. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34228. /**
  34229. * Does this action manager has pointer triggers
  34230. * @return {boolean} whether or not it has pointer triggers
  34231. */
  34232. get: function () {
  34233. for (var index = 0; index < this.actions.length; index++) {
  34234. var action = this.actions[index];
  34235. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34236. return true;
  34237. }
  34238. }
  34239. return false;
  34240. },
  34241. enumerable: true,
  34242. configurable: true
  34243. });
  34244. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34245. /**
  34246. * Does this action manager has pick triggers
  34247. * @return {boolean} whether or not it has pick triggers
  34248. */
  34249. get: function () {
  34250. for (var index = 0; index < this.actions.length; index++) {
  34251. var action = this.actions[index];
  34252. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  34253. return true;
  34254. }
  34255. }
  34256. return false;
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. /**
  34262. * Registers an action to this action manager
  34263. * @param {BABYLON.Action} action - the action to be registered
  34264. * @return {BABYLON.Action} the action amended (prepared) after registration
  34265. */
  34266. ActionManager.prototype.registerAction = function (action) {
  34267. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34268. if (this.getScene().actionManager !== this) {
  34269. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34270. return null;
  34271. }
  34272. }
  34273. this.actions.push(action);
  34274. action._actionManager = this;
  34275. action._prepare();
  34276. return action;
  34277. };
  34278. /**
  34279. * Process a specific trigger
  34280. * @param {number} trigger - the trigger to process
  34281. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34282. */
  34283. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34284. for (var index = 0; index < this.actions.length; index++) {
  34285. var action = this.actions[index];
  34286. if (action.trigger === trigger) {
  34287. if (trigger === ActionManager.OnKeyUpTrigger
  34288. || trigger === ActionManager.OnKeyDownTrigger) {
  34289. var parameter = action.getTriggerParameter();
  34290. if (parameter) {
  34291. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34292. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34293. if (actualkey !== parameter.toLowerCase()) {
  34294. continue;
  34295. }
  34296. }
  34297. }
  34298. action._executeCurrent(evt);
  34299. }
  34300. }
  34301. };
  34302. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34303. var properties = propertyPath.split(".");
  34304. for (var index = 0; index < properties.length - 1; index++) {
  34305. target = target[properties[index]];
  34306. }
  34307. return target;
  34308. };
  34309. ActionManager.prototype._getProperty = function (propertyPath) {
  34310. var properties = propertyPath.split(".");
  34311. return properties[properties.length - 1];
  34312. };
  34313. ActionManager.prototype.serialize = function (name) {
  34314. var root = {
  34315. children: [],
  34316. name: name,
  34317. type: 3,
  34318. properties: [] // Empty for root but required
  34319. };
  34320. for (var i = 0; i < this.actions.length; i++) {
  34321. var triggerObject = {
  34322. type: 0,
  34323. children: [],
  34324. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34325. properties: []
  34326. };
  34327. var triggerOptions = this.actions[i].triggerOptions;
  34328. if (triggerOptions && typeof triggerOptions !== "number") {
  34329. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34330. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34331. }
  34332. else {
  34333. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  34334. }
  34335. }
  34336. // Serialize child action, recursively
  34337. this.actions[i].serialize(triggerObject);
  34338. // Add serialized trigger
  34339. root.children.push(triggerObject);
  34340. }
  34341. return root;
  34342. };
  34343. ActionManager.Parse = function (parsedActions, object, scene) {
  34344. var actionManager = new BABYLON.ActionManager(scene);
  34345. if (object === null)
  34346. scene.actionManager = actionManager;
  34347. else
  34348. object.actionManager = actionManager;
  34349. // instanciate a new object
  34350. var instanciate = function (name, params) {
  34351. var newInstance = Object.create(BABYLON[name].prototype);
  34352. newInstance.constructor.apply(newInstance, params);
  34353. return newInstance;
  34354. };
  34355. var parseParameter = function (name, value, target, propertyPath) {
  34356. if (propertyPath === null) {
  34357. // String, boolean or float
  34358. var floatValue = parseFloat(value);
  34359. if (value === "true" || value === "false")
  34360. return value === "true";
  34361. else
  34362. return isNaN(floatValue) ? value : floatValue;
  34363. }
  34364. var effectiveTarget = propertyPath.split(".");
  34365. var values = value.split(",");
  34366. // Get effective Target
  34367. for (var i = 0; i < effectiveTarget.length; i++) {
  34368. target = target[effectiveTarget[i]];
  34369. }
  34370. // Return appropriate value with its type
  34371. if (typeof (target) === "boolean")
  34372. return values[0] === "true";
  34373. if (typeof (target) === "string")
  34374. return values[0];
  34375. // Parameters with multiple values such as Vector3 etc.
  34376. var split = new Array();
  34377. for (var i = 0; i < values.length; i++)
  34378. split.push(parseFloat(values[i]));
  34379. if (target instanceof BABYLON.Vector3)
  34380. return BABYLON.Vector3.FromArray(split);
  34381. if (target instanceof BABYLON.Vector4)
  34382. return BABYLON.Vector4.FromArray(split);
  34383. if (target instanceof BABYLON.Color3)
  34384. return BABYLON.Color3.FromArray(split);
  34385. if (target instanceof BABYLON.Color4)
  34386. return BABYLON.Color4.FromArray(split);
  34387. return parseFloat(values[0]);
  34388. };
  34389. // traverse graph per trigger
  34390. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34391. if (combineArray === void 0) { combineArray = null; }
  34392. if (parsedAction.detached)
  34393. return;
  34394. var parameters = new Array();
  34395. var target = null;
  34396. var propertyPath = null;
  34397. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34398. // Parameters
  34399. if (parsedAction.type === 2)
  34400. parameters.push(actionManager);
  34401. else
  34402. parameters.push(trigger);
  34403. if (combine) {
  34404. var actions = new Array();
  34405. for (var j = 0; j < parsedAction.combine.length; j++) {
  34406. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34407. }
  34408. parameters.push(actions);
  34409. }
  34410. else {
  34411. for (var i = 0; i < parsedAction.properties.length; i++) {
  34412. var value = parsedAction.properties[i].value;
  34413. var name = parsedAction.properties[i].name;
  34414. var targetType = parsedAction.properties[i].targetType;
  34415. if (name === "target")
  34416. if (targetType !== null && targetType === "SceneProperties")
  34417. value = target = scene;
  34418. else
  34419. value = target = scene.getNodeByName(value);
  34420. else if (name === "parent")
  34421. value = scene.getNodeByName(value);
  34422. else if (name === "sound")
  34423. value = scene.getSoundByName(value);
  34424. else if (name !== "propertyPath") {
  34425. if (parsedAction.type === 2 && name === "operator")
  34426. value = BABYLON.ValueCondition[value];
  34427. else
  34428. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34429. }
  34430. else {
  34431. propertyPath = value;
  34432. }
  34433. parameters.push(value);
  34434. }
  34435. }
  34436. if (combineArray === null) {
  34437. parameters.push(condition);
  34438. }
  34439. else {
  34440. parameters.push(null);
  34441. }
  34442. // If interpolate value action
  34443. if (parsedAction.name === "InterpolateValueAction") {
  34444. var param = parameters[parameters.length - 2];
  34445. parameters[parameters.length - 1] = param;
  34446. parameters[parameters.length - 2] = condition;
  34447. }
  34448. // Action or condition(s) and not CombineAction
  34449. var newAction = instanciate(parsedAction.name, parameters);
  34450. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34451. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34452. if (action)
  34453. action.then(nothing);
  34454. else
  34455. actionManager.registerAction(nothing);
  34456. action = nothing;
  34457. }
  34458. if (combineArray === null) {
  34459. if (newAction instanceof BABYLON.Condition) {
  34460. condition = newAction;
  34461. newAction = action;
  34462. }
  34463. else {
  34464. condition = null;
  34465. if (action)
  34466. action.then(newAction);
  34467. else
  34468. actionManager.registerAction(newAction);
  34469. }
  34470. }
  34471. else {
  34472. combineArray.push(newAction);
  34473. }
  34474. for (var i = 0; i < parsedAction.children.length; i++)
  34475. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34476. };
  34477. // triggers
  34478. for (var i = 0; i < parsedActions.children.length; i++) {
  34479. var triggerParams;
  34480. var trigger = parsedActions.children[i];
  34481. if (trigger.properties.length > 0) {
  34482. var param = trigger.properties[0].value;
  34483. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34484. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34485. }
  34486. else
  34487. triggerParams = BABYLON.ActionManager[trigger.name];
  34488. for (var j = 0; j < trigger.children.length; j++) {
  34489. if (!trigger.detached)
  34490. traverse(trigger.children[j], triggerParams, null, null);
  34491. }
  34492. }
  34493. };
  34494. ActionManager.GetTriggerName = function (trigger) {
  34495. switch (trigger) {
  34496. case 0: return "NothingTrigger";
  34497. case 1: return "OnPickTrigger";
  34498. case 2: return "OnLeftPickTrigger";
  34499. case 3: return "OnRightPickTrigger";
  34500. case 4: return "OnCenterPickTrigger";
  34501. case 5: return "OnPickDownTrigger";
  34502. case 6: return "OnPickUpTrigger";
  34503. case 7: return "OnLongPressTrigger";
  34504. case 8: return "OnPointerOverTrigger";
  34505. case 9: return "OnPointerOutTrigger";
  34506. case 10: return "OnEveryFrameTrigger";
  34507. case 11: return "OnIntersectionEnterTrigger";
  34508. case 12: return "OnIntersectionExitTrigger";
  34509. case 13: return "OnKeyDownTrigger";
  34510. case 14: return "OnKeyUpTrigger";
  34511. case 15: return "OnPickOutTrigger";
  34512. default: return "";
  34513. }
  34514. };
  34515. // Statics
  34516. ActionManager._NothingTrigger = 0;
  34517. ActionManager._OnPickTrigger = 1;
  34518. ActionManager._OnLeftPickTrigger = 2;
  34519. ActionManager._OnRightPickTrigger = 3;
  34520. ActionManager._OnCenterPickTrigger = 4;
  34521. ActionManager._OnPickDownTrigger = 5;
  34522. ActionManager._OnPickUpTrigger = 6;
  34523. ActionManager._OnLongPressTrigger = 7;
  34524. ActionManager._OnPointerOverTrigger = 8;
  34525. ActionManager._OnPointerOutTrigger = 9;
  34526. ActionManager._OnEveryFrameTrigger = 10;
  34527. ActionManager._OnIntersectionEnterTrigger = 11;
  34528. ActionManager._OnIntersectionExitTrigger = 12;
  34529. ActionManager._OnKeyDownTrigger = 13;
  34530. ActionManager._OnKeyUpTrigger = 14;
  34531. ActionManager._OnPickOutTrigger = 15;
  34532. ActionManager.DragMovementThreshold = 10; // in pixels
  34533. ActionManager.LongPressDelay = 500; // in milliseconds
  34534. return ActionManager;
  34535. }());
  34536. BABYLON.ActionManager = ActionManager;
  34537. })(BABYLON || (BABYLON = {}));
  34538. var BABYLON;
  34539. (function (BABYLON) {
  34540. var InterpolateValueAction = (function (_super) {
  34541. __extends(InterpolateValueAction, _super);
  34542. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34543. if (duration === void 0) { duration = 1000; }
  34544. _super.call(this, triggerOptions, condition);
  34545. this.propertyPath = propertyPath;
  34546. this.value = value;
  34547. this.duration = duration;
  34548. this.stopOtherAnimations = stopOtherAnimations;
  34549. this.onInterpolationDone = onInterpolationDone;
  34550. this._target = this._effectiveTarget = target;
  34551. }
  34552. InterpolateValueAction.prototype._prepare = function () {
  34553. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34554. this._property = this._getProperty(this.propertyPath);
  34555. };
  34556. InterpolateValueAction.prototype.execute = function () {
  34557. var scene = this._actionManager.getScene();
  34558. var keys = [
  34559. {
  34560. frame: 0,
  34561. value: this._effectiveTarget[this._property]
  34562. }, {
  34563. frame: 100,
  34564. value: this.value
  34565. }
  34566. ];
  34567. var dataType;
  34568. if (typeof this.value === "number") {
  34569. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34570. }
  34571. else if (this.value instanceof BABYLON.Color3) {
  34572. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34573. }
  34574. else if (this.value instanceof BABYLON.Vector3) {
  34575. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34576. }
  34577. else if (this.value instanceof BABYLON.Matrix) {
  34578. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34579. }
  34580. else if (this.value instanceof BABYLON.Quaternion) {
  34581. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34582. }
  34583. else {
  34584. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34585. return;
  34586. }
  34587. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34588. animation.setKeys(keys);
  34589. if (this.stopOtherAnimations) {
  34590. scene.stopAnimation(this._effectiveTarget);
  34591. }
  34592. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34593. };
  34594. InterpolateValueAction.prototype.serialize = function (parent) {
  34595. return _super.prototype._serialize.call(this, {
  34596. name: "InterpolateValueAction",
  34597. properties: [
  34598. BABYLON.Action._GetTargetProperty(this._target),
  34599. { name: "propertyPath", value: this.propertyPath },
  34600. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34601. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34602. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34603. ]
  34604. }, parent);
  34605. };
  34606. return InterpolateValueAction;
  34607. }(BABYLON.Action));
  34608. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34609. })(BABYLON || (BABYLON = {}));
  34610. var BABYLON;
  34611. (function (BABYLON) {
  34612. var SwitchBooleanAction = (function (_super) {
  34613. __extends(SwitchBooleanAction, _super);
  34614. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34615. _super.call(this, triggerOptions, condition);
  34616. this.propertyPath = propertyPath;
  34617. this._target = this._effectiveTarget = target;
  34618. }
  34619. SwitchBooleanAction.prototype._prepare = function () {
  34620. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34621. this._property = this._getProperty(this.propertyPath);
  34622. };
  34623. SwitchBooleanAction.prototype.execute = function () {
  34624. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34625. };
  34626. SwitchBooleanAction.prototype.serialize = function (parent) {
  34627. return _super.prototype._serialize.call(this, {
  34628. name: "SwitchBooleanAction",
  34629. properties: [
  34630. BABYLON.Action._GetTargetProperty(this._target),
  34631. { name: "propertyPath", value: this.propertyPath }
  34632. ]
  34633. }, parent);
  34634. };
  34635. return SwitchBooleanAction;
  34636. }(BABYLON.Action));
  34637. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34638. var SetStateAction = (function (_super) {
  34639. __extends(SetStateAction, _super);
  34640. function SetStateAction(triggerOptions, target, value, condition) {
  34641. _super.call(this, triggerOptions, condition);
  34642. this.value = value;
  34643. this._target = target;
  34644. }
  34645. SetStateAction.prototype.execute = function () {
  34646. this._target.state = this.value;
  34647. };
  34648. SetStateAction.prototype.serialize = function (parent) {
  34649. return _super.prototype._serialize.call(this, {
  34650. name: "SetStateAction",
  34651. properties: [
  34652. BABYLON.Action._GetTargetProperty(this._target),
  34653. { name: "value", value: this.value }
  34654. ]
  34655. }, parent);
  34656. };
  34657. return SetStateAction;
  34658. }(BABYLON.Action));
  34659. BABYLON.SetStateAction = SetStateAction;
  34660. var SetValueAction = (function (_super) {
  34661. __extends(SetValueAction, _super);
  34662. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34663. _super.call(this, triggerOptions, condition);
  34664. this.propertyPath = propertyPath;
  34665. this.value = value;
  34666. this._target = this._effectiveTarget = target;
  34667. }
  34668. SetValueAction.prototype._prepare = function () {
  34669. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34670. this._property = this._getProperty(this.propertyPath);
  34671. };
  34672. SetValueAction.prototype.execute = function () {
  34673. this._effectiveTarget[this._property] = this.value;
  34674. if (this._target.markAsDirty) {
  34675. this._target.markAsDirty(this._property);
  34676. }
  34677. };
  34678. SetValueAction.prototype.serialize = function (parent) {
  34679. return _super.prototype._serialize.call(this, {
  34680. name: "SetValueAction",
  34681. properties: [
  34682. BABYLON.Action._GetTargetProperty(this._target),
  34683. { name: "propertyPath", value: this.propertyPath },
  34684. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34685. ]
  34686. }, parent);
  34687. };
  34688. return SetValueAction;
  34689. }(BABYLON.Action));
  34690. BABYLON.SetValueAction = SetValueAction;
  34691. var IncrementValueAction = (function (_super) {
  34692. __extends(IncrementValueAction, _super);
  34693. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34694. _super.call(this, triggerOptions, condition);
  34695. this.propertyPath = propertyPath;
  34696. this.value = value;
  34697. this._target = this._effectiveTarget = target;
  34698. }
  34699. IncrementValueAction.prototype._prepare = function () {
  34700. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34701. this._property = this._getProperty(this.propertyPath);
  34702. if (typeof this._effectiveTarget[this._property] !== "number") {
  34703. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34704. }
  34705. };
  34706. IncrementValueAction.prototype.execute = function () {
  34707. this._effectiveTarget[this._property] += this.value;
  34708. if (this._target.markAsDirty) {
  34709. this._target.markAsDirty(this._property);
  34710. }
  34711. };
  34712. IncrementValueAction.prototype.serialize = function (parent) {
  34713. return _super.prototype._serialize.call(this, {
  34714. name: "IncrementValueAction",
  34715. properties: [
  34716. BABYLON.Action._GetTargetProperty(this._target),
  34717. { name: "propertyPath", value: this.propertyPath },
  34718. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34719. ]
  34720. }, parent);
  34721. };
  34722. return IncrementValueAction;
  34723. }(BABYLON.Action));
  34724. BABYLON.IncrementValueAction = IncrementValueAction;
  34725. var PlayAnimationAction = (function (_super) {
  34726. __extends(PlayAnimationAction, _super);
  34727. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34728. _super.call(this, triggerOptions, condition);
  34729. this.from = from;
  34730. this.to = to;
  34731. this.loop = loop;
  34732. this._target = target;
  34733. }
  34734. PlayAnimationAction.prototype._prepare = function () {
  34735. };
  34736. PlayAnimationAction.prototype.execute = function () {
  34737. var scene = this._actionManager.getScene();
  34738. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34739. };
  34740. PlayAnimationAction.prototype.serialize = function (parent) {
  34741. return _super.prototype._serialize.call(this, {
  34742. name: "PlayAnimationAction",
  34743. properties: [
  34744. BABYLON.Action._GetTargetProperty(this._target),
  34745. { name: "from", value: String(this.from) },
  34746. { name: "to", value: String(this.to) },
  34747. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34748. ]
  34749. }, parent);
  34750. };
  34751. return PlayAnimationAction;
  34752. }(BABYLON.Action));
  34753. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34754. var StopAnimationAction = (function (_super) {
  34755. __extends(StopAnimationAction, _super);
  34756. function StopAnimationAction(triggerOptions, target, condition) {
  34757. _super.call(this, triggerOptions, condition);
  34758. this._target = target;
  34759. }
  34760. StopAnimationAction.prototype._prepare = function () {
  34761. };
  34762. StopAnimationAction.prototype.execute = function () {
  34763. var scene = this._actionManager.getScene();
  34764. scene.stopAnimation(this._target);
  34765. };
  34766. StopAnimationAction.prototype.serialize = function (parent) {
  34767. return _super.prototype._serialize.call(this, {
  34768. name: "StopAnimationAction",
  34769. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34770. }, parent);
  34771. };
  34772. return StopAnimationAction;
  34773. }(BABYLON.Action));
  34774. BABYLON.StopAnimationAction = StopAnimationAction;
  34775. var DoNothingAction = (function (_super) {
  34776. __extends(DoNothingAction, _super);
  34777. function DoNothingAction(triggerOptions, condition) {
  34778. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34779. _super.call(this, triggerOptions, condition);
  34780. }
  34781. DoNothingAction.prototype.execute = function () {
  34782. };
  34783. DoNothingAction.prototype.serialize = function (parent) {
  34784. return _super.prototype._serialize.call(this, {
  34785. name: "DoNothingAction",
  34786. properties: []
  34787. }, parent);
  34788. };
  34789. return DoNothingAction;
  34790. }(BABYLON.Action));
  34791. BABYLON.DoNothingAction = DoNothingAction;
  34792. var CombineAction = (function (_super) {
  34793. __extends(CombineAction, _super);
  34794. function CombineAction(triggerOptions, children, condition) {
  34795. _super.call(this, triggerOptions, condition);
  34796. this.children = children;
  34797. }
  34798. CombineAction.prototype._prepare = function () {
  34799. for (var index = 0; index < this.children.length; index++) {
  34800. this.children[index]._actionManager = this._actionManager;
  34801. this.children[index]._prepare();
  34802. }
  34803. };
  34804. CombineAction.prototype.execute = function (evt) {
  34805. for (var index = 0; index < this.children.length; index++) {
  34806. this.children[index].execute(evt);
  34807. }
  34808. };
  34809. CombineAction.prototype.serialize = function (parent) {
  34810. var serializationObject = _super.prototype._serialize.call(this, {
  34811. name: "CombineAction",
  34812. properties: [],
  34813. combine: []
  34814. }, parent);
  34815. for (var i = 0; i < this.children.length; i++) {
  34816. serializationObject.combine.push(this.children[i].serialize(null));
  34817. }
  34818. return serializationObject;
  34819. };
  34820. return CombineAction;
  34821. }(BABYLON.Action));
  34822. BABYLON.CombineAction = CombineAction;
  34823. var ExecuteCodeAction = (function (_super) {
  34824. __extends(ExecuteCodeAction, _super);
  34825. function ExecuteCodeAction(triggerOptions, func, condition) {
  34826. _super.call(this, triggerOptions, condition);
  34827. this.func = func;
  34828. }
  34829. ExecuteCodeAction.prototype.execute = function (evt) {
  34830. this.func(evt);
  34831. };
  34832. return ExecuteCodeAction;
  34833. }(BABYLON.Action));
  34834. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34835. var SetParentAction = (function (_super) {
  34836. __extends(SetParentAction, _super);
  34837. function SetParentAction(triggerOptions, target, parent, condition) {
  34838. _super.call(this, triggerOptions, condition);
  34839. this._target = target;
  34840. this._parent = parent;
  34841. }
  34842. SetParentAction.prototype._prepare = function () {
  34843. };
  34844. SetParentAction.prototype.execute = function () {
  34845. if (this._target.parent === this._parent) {
  34846. return;
  34847. }
  34848. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34849. invertParentWorldMatrix.invert();
  34850. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34851. this._target.parent = this._parent;
  34852. };
  34853. SetParentAction.prototype.serialize = function (parent) {
  34854. return _super.prototype._serialize.call(this, {
  34855. name: "SetParentAction",
  34856. properties: [
  34857. BABYLON.Action._GetTargetProperty(this._target),
  34858. BABYLON.Action._GetTargetProperty(this._parent),
  34859. ]
  34860. }, parent);
  34861. };
  34862. return SetParentAction;
  34863. }(BABYLON.Action));
  34864. BABYLON.SetParentAction = SetParentAction;
  34865. var PlaySoundAction = (function (_super) {
  34866. __extends(PlaySoundAction, _super);
  34867. function PlaySoundAction(triggerOptions, sound, condition) {
  34868. _super.call(this, triggerOptions, condition);
  34869. this._sound = sound;
  34870. }
  34871. PlaySoundAction.prototype._prepare = function () {
  34872. };
  34873. PlaySoundAction.prototype.execute = function () {
  34874. if (this._sound !== undefined)
  34875. this._sound.play();
  34876. };
  34877. PlaySoundAction.prototype.serialize = function (parent) {
  34878. return _super.prototype._serialize.call(this, {
  34879. name: "PlaySoundAction",
  34880. properties: [{ name: "sound", value: this._sound.name }]
  34881. }, parent);
  34882. };
  34883. return PlaySoundAction;
  34884. }(BABYLON.Action));
  34885. BABYLON.PlaySoundAction = PlaySoundAction;
  34886. var StopSoundAction = (function (_super) {
  34887. __extends(StopSoundAction, _super);
  34888. function StopSoundAction(triggerOptions, sound, condition) {
  34889. _super.call(this, triggerOptions, condition);
  34890. this._sound = sound;
  34891. }
  34892. StopSoundAction.prototype._prepare = function () {
  34893. };
  34894. StopSoundAction.prototype.execute = function () {
  34895. if (this._sound !== undefined)
  34896. this._sound.stop();
  34897. };
  34898. StopSoundAction.prototype.serialize = function (parent) {
  34899. return _super.prototype._serialize.call(this, {
  34900. name: "StopSoundAction",
  34901. properties: [{ name: "sound", value: this._sound.name }]
  34902. }, parent);
  34903. };
  34904. return StopSoundAction;
  34905. }(BABYLON.Action));
  34906. BABYLON.StopSoundAction = StopSoundAction;
  34907. })(BABYLON || (BABYLON = {}));
  34908. var BABYLON;
  34909. (function (BABYLON) {
  34910. var Geometry = (function () {
  34911. function Geometry(id, scene, vertexData, updatable, mesh) {
  34912. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34913. this._totalVertices = 0;
  34914. this._isDisposed = false;
  34915. this.id = id;
  34916. this._engine = scene.getEngine();
  34917. this._meshes = [];
  34918. this._scene = scene;
  34919. //Init vertex buffer cache
  34920. this._vertexBuffers = {};
  34921. this._indices = [];
  34922. // vertexData
  34923. if (vertexData) {
  34924. this.setAllVerticesData(vertexData, updatable);
  34925. }
  34926. else {
  34927. this._totalVertices = 0;
  34928. this._indices = [];
  34929. }
  34930. // applyToMesh
  34931. if (mesh) {
  34932. if (mesh instanceof BABYLON.LinesMesh) {
  34933. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34934. this.updateExtend();
  34935. }
  34936. this.applyToMesh(mesh);
  34937. mesh.computeWorldMatrix(true);
  34938. }
  34939. }
  34940. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34941. /**
  34942. * 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
  34943. * @returns The Bias Vector
  34944. */
  34945. get: function () {
  34946. return this._boundingBias;
  34947. },
  34948. set: function (value) {
  34949. if (this._boundingBias && this._boundingBias.equals(value)) {
  34950. return;
  34951. }
  34952. this._boundingBias = value.clone();
  34953. this.updateBoundingInfo(true, null);
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(Geometry.prototype, "extend", {
  34959. get: function () {
  34960. return this._extend;
  34961. },
  34962. enumerable: true,
  34963. configurable: true
  34964. });
  34965. Geometry.prototype.getScene = function () {
  34966. return this._scene;
  34967. };
  34968. Geometry.prototype.getEngine = function () {
  34969. return this._engine;
  34970. };
  34971. Geometry.prototype.isReady = function () {
  34972. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34973. };
  34974. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34975. vertexData.applyToGeometry(this, updatable);
  34976. this.notifyUpdate();
  34977. };
  34978. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34979. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34980. this.setVerticesBuffer(buffer);
  34981. };
  34982. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34983. var kind = buffer.getKind();
  34984. if (this._vertexBuffers[kind]) {
  34985. this._vertexBuffers[kind].dispose();
  34986. }
  34987. this._vertexBuffers[kind] = buffer;
  34988. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34989. var data = buffer.getData();
  34990. var stride = buffer.getStrideSize();
  34991. this._totalVertices = data.length / stride;
  34992. this.updateExtend(data, stride);
  34993. var meshes = this._meshes;
  34994. var numOfMeshes = meshes.length;
  34995. for (var index = 0; index < numOfMeshes; index++) {
  34996. var mesh = meshes[index];
  34997. mesh._resetPointsArrayCache();
  34998. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34999. mesh._createGlobalSubMesh();
  35000. mesh.computeWorldMatrix(true);
  35001. }
  35002. }
  35003. this.notifyUpdate(kind);
  35004. };
  35005. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35006. var vertexBuffer = this.getVertexBuffer(kind);
  35007. if (!vertexBuffer) {
  35008. return;
  35009. }
  35010. vertexBuffer.updateDirectly(data, offset);
  35011. this.notifyUpdate(kind);
  35012. };
  35013. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35014. var vertexBuffer = this.getVertexBuffer(kind);
  35015. if (!vertexBuffer) {
  35016. return;
  35017. }
  35018. vertexBuffer.update(data);
  35019. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35020. var stride = vertexBuffer.getStrideSize();
  35021. this._totalVertices = data.length / stride;
  35022. this.updateBoundingInfo(updateExtends, data);
  35023. }
  35024. this.notifyUpdate(kind);
  35025. };
  35026. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35027. if (updateExtends) {
  35028. this.updateExtend(data);
  35029. }
  35030. var meshes = this._meshes;
  35031. var numOfMeshes = meshes.length;
  35032. for (var index = 0; index < numOfMeshes; index++) {
  35033. var mesh = meshes[index];
  35034. mesh._resetPointsArrayCache();
  35035. if (updateExtends) {
  35036. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35037. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35038. var subMesh = mesh.subMeshes[subIndex];
  35039. subMesh.refreshBoundingInfo();
  35040. }
  35041. }
  35042. }
  35043. };
  35044. Geometry.prototype.getTotalVertices = function () {
  35045. if (!this.isReady()) {
  35046. return 0;
  35047. }
  35048. return this._totalVertices;
  35049. };
  35050. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  35051. var vertexBuffer = this.getVertexBuffer(kind);
  35052. if (!vertexBuffer) {
  35053. return null;
  35054. }
  35055. var orig = vertexBuffer.getData();
  35056. if (!copyWhenShared || this._meshes.length === 1) {
  35057. return orig;
  35058. }
  35059. else {
  35060. var len = orig.length;
  35061. var copy = [];
  35062. for (var i = 0; i < len; i++) {
  35063. copy.push(orig[i]);
  35064. }
  35065. return copy;
  35066. }
  35067. };
  35068. Geometry.prototype.getVertexBuffer = function (kind) {
  35069. if (!this.isReady()) {
  35070. return null;
  35071. }
  35072. return this._vertexBuffers[kind];
  35073. };
  35074. Geometry.prototype.getVertexBuffers = function () {
  35075. if (!this.isReady()) {
  35076. return null;
  35077. }
  35078. return this._vertexBuffers;
  35079. };
  35080. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35081. if (!this._vertexBuffers) {
  35082. if (this._delayInfo) {
  35083. return this._delayInfo.indexOf(kind) !== -1;
  35084. }
  35085. return false;
  35086. }
  35087. return this._vertexBuffers[kind] !== undefined;
  35088. };
  35089. Geometry.prototype.getVerticesDataKinds = function () {
  35090. var result = [];
  35091. var kind;
  35092. if (!this._vertexBuffers && this._delayInfo) {
  35093. for (kind in this._delayInfo) {
  35094. result.push(kind);
  35095. }
  35096. }
  35097. else {
  35098. for (kind in this._vertexBuffers) {
  35099. result.push(kind);
  35100. }
  35101. }
  35102. return result;
  35103. };
  35104. Geometry.prototype.setIndices = function (indices, totalVertices) {
  35105. if (this._indexBuffer) {
  35106. this._engine._releaseBuffer(this._indexBuffer);
  35107. }
  35108. this._indices = indices;
  35109. if (this._meshes.length !== 0 && this._indices) {
  35110. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35111. }
  35112. if (totalVertices !== undefined) {
  35113. this._totalVertices = totalVertices;
  35114. }
  35115. var meshes = this._meshes;
  35116. var numOfMeshes = meshes.length;
  35117. for (var index = 0; index < numOfMeshes; index++) {
  35118. meshes[index]._createGlobalSubMesh();
  35119. }
  35120. this.notifyUpdate();
  35121. };
  35122. Geometry.prototype.getTotalIndices = function () {
  35123. if (!this.isReady()) {
  35124. return 0;
  35125. }
  35126. return this._indices.length;
  35127. };
  35128. Geometry.prototype.getIndices = function (copyWhenShared) {
  35129. if (!this.isReady()) {
  35130. return null;
  35131. }
  35132. var orig = this._indices;
  35133. if (!copyWhenShared || this._meshes.length === 1) {
  35134. return orig;
  35135. }
  35136. else {
  35137. var len = orig.length;
  35138. var copy = [];
  35139. for (var i = 0; i < len; i++) {
  35140. copy.push(orig[i]);
  35141. }
  35142. return copy;
  35143. }
  35144. };
  35145. Geometry.prototype.getIndexBuffer = function () {
  35146. if (!this.isReady()) {
  35147. return null;
  35148. }
  35149. return this._indexBuffer;
  35150. };
  35151. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35152. var meshes = this._meshes;
  35153. var index = meshes.indexOf(mesh);
  35154. if (index === -1) {
  35155. return;
  35156. }
  35157. for (var kind in this._vertexBuffers) {
  35158. this._vertexBuffers[kind].dispose();
  35159. }
  35160. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  35161. this._indexBuffer = null;
  35162. }
  35163. meshes.splice(index, 1);
  35164. mesh._geometry = null;
  35165. if (meshes.length === 0 && shouldDispose) {
  35166. this.dispose();
  35167. }
  35168. };
  35169. Geometry.prototype.applyToMesh = function (mesh) {
  35170. if (mesh._geometry === this) {
  35171. return;
  35172. }
  35173. var previousGeometry = mesh._geometry;
  35174. if (previousGeometry) {
  35175. previousGeometry.releaseForMesh(mesh);
  35176. }
  35177. var meshes = this._meshes;
  35178. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35179. mesh._geometry = this;
  35180. this._scene.pushGeometry(this);
  35181. meshes.push(mesh);
  35182. if (this.isReady()) {
  35183. this._applyToMesh(mesh);
  35184. }
  35185. else {
  35186. mesh._boundingInfo = this._boundingInfo;
  35187. }
  35188. };
  35189. Geometry.prototype.updateExtend = function (data, stride) {
  35190. if (data === void 0) { data = null; }
  35191. if (!data) {
  35192. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35193. }
  35194. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35195. };
  35196. Geometry.prototype._applyToMesh = function (mesh) {
  35197. var numOfMeshes = this._meshes.length;
  35198. // vertexBuffers
  35199. for (var kind in this._vertexBuffers) {
  35200. if (numOfMeshes === 1) {
  35201. this._vertexBuffers[kind].create();
  35202. }
  35203. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  35204. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35205. mesh._resetPointsArrayCache();
  35206. if (!this._extend) {
  35207. this.updateExtend(this._vertexBuffers[kind].getData());
  35208. }
  35209. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35210. mesh._createGlobalSubMesh();
  35211. //bounding info was just created again, world matrix should be applied again.
  35212. mesh._updateBoundingInfo();
  35213. }
  35214. }
  35215. // indexBuffer
  35216. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35217. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35218. }
  35219. if (this._indexBuffer) {
  35220. this._indexBuffer.references = numOfMeshes;
  35221. }
  35222. };
  35223. Geometry.prototype.notifyUpdate = function (kind) {
  35224. if (this.onGeometryUpdated) {
  35225. this.onGeometryUpdated(this, kind);
  35226. }
  35227. };
  35228. Geometry.prototype.load = function (scene, onLoaded) {
  35229. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35230. return;
  35231. }
  35232. if (this.isReady()) {
  35233. if (onLoaded) {
  35234. onLoaded();
  35235. }
  35236. return;
  35237. }
  35238. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35239. this._queueLoad(scene, onLoaded);
  35240. };
  35241. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35242. var _this = this;
  35243. scene._addPendingData(this);
  35244. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  35245. _this._delayLoadingFunction(JSON.parse(data), _this);
  35246. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35247. _this._delayInfo = [];
  35248. scene._removePendingData(_this);
  35249. var meshes = _this._meshes;
  35250. var numOfMeshes = meshes.length;
  35251. for (var index = 0; index < numOfMeshes; index++) {
  35252. _this._applyToMesh(meshes[index]);
  35253. }
  35254. if (onLoaded) {
  35255. onLoaded();
  35256. }
  35257. }, function () { }, scene.database);
  35258. };
  35259. /**
  35260. * Invert the geometry to move from a right handed system to a left handed one.
  35261. */
  35262. Geometry.prototype.toLeftHanded = function () {
  35263. // Flip faces
  35264. var tIndices = this.getIndices(false);
  35265. if (tIndices != null && tIndices.length > 0) {
  35266. for (var i = 0; i < tIndices.length; i += 3) {
  35267. var tTemp = tIndices[i + 0];
  35268. tIndices[i + 0] = tIndices[i + 2];
  35269. tIndices[i + 2] = tTemp;
  35270. }
  35271. this.setIndices(tIndices);
  35272. }
  35273. // Negate position.z
  35274. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35275. if (tPositions != null && tPositions.length > 0) {
  35276. for (var i = 0; i < tPositions.length; i += 3) {
  35277. tPositions[i + 2] = -tPositions[i + 2];
  35278. }
  35279. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35280. }
  35281. // Negate normal.z
  35282. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35283. if (tNormals != null && tNormals.length > 0) {
  35284. for (var i = 0; i < tNormals.length; i += 3) {
  35285. tNormals[i + 2] = -tNormals[i + 2];
  35286. }
  35287. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35288. }
  35289. };
  35290. Geometry.prototype.isDisposed = function () {
  35291. return this._isDisposed;
  35292. };
  35293. Geometry.prototype.dispose = function () {
  35294. var meshes = this._meshes;
  35295. var numOfMeshes = meshes.length;
  35296. var index;
  35297. for (index = 0; index < numOfMeshes; index++) {
  35298. this.releaseForMesh(meshes[index]);
  35299. }
  35300. this._meshes = [];
  35301. for (var kind in this._vertexBuffers) {
  35302. this._vertexBuffers[kind].dispose();
  35303. }
  35304. this._vertexBuffers = {};
  35305. this._totalVertices = 0;
  35306. if (this._indexBuffer) {
  35307. this._engine._releaseBuffer(this._indexBuffer);
  35308. }
  35309. this._indexBuffer = null;
  35310. this._indices = [];
  35311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35312. this.delayLoadingFile = null;
  35313. this._delayLoadingFunction = null;
  35314. this._delayInfo = [];
  35315. this._boundingInfo = null;
  35316. this._scene.removeGeometry(this);
  35317. this._isDisposed = true;
  35318. };
  35319. Geometry.prototype.copy = function (id) {
  35320. var vertexData = new BABYLON.VertexData();
  35321. vertexData.indices = [];
  35322. var indices = this.getIndices();
  35323. for (var index = 0; index < indices.length; index++) {
  35324. vertexData.indices.push(indices[index]);
  35325. }
  35326. var updatable = false;
  35327. var stopChecking = false;
  35328. var kind;
  35329. for (kind in this._vertexBuffers) {
  35330. // using slice() to make a copy of the array and not just reference it
  35331. var data = this.getVerticesData(kind);
  35332. if (data instanceof Float32Array) {
  35333. vertexData.set(new Float32Array(data), kind);
  35334. }
  35335. else {
  35336. vertexData.set(data.slice(0), kind);
  35337. }
  35338. if (!stopChecking) {
  35339. updatable = this.getVertexBuffer(kind).isUpdatable();
  35340. stopChecking = !updatable;
  35341. }
  35342. }
  35343. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  35344. geometry.delayLoadState = this.delayLoadState;
  35345. geometry.delayLoadingFile = this.delayLoadingFile;
  35346. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35347. for (kind in this._delayInfo) {
  35348. geometry._delayInfo = geometry._delayInfo || [];
  35349. geometry._delayInfo.push(kind);
  35350. }
  35351. // Bounding info
  35352. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35353. return geometry;
  35354. };
  35355. Geometry.prototype.serialize = function () {
  35356. var serializationObject = {};
  35357. serializationObject.id = this.id;
  35358. if (BABYLON.Tags.HasTags(this)) {
  35359. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35360. }
  35361. return serializationObject;
  35362. };
  35363. Geometry.prototype.serializeVerticeData = function () {
  35364. var serializationObject = this.serialize();
  35365. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35366. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35367. }
  35368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35369. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35370. }
  35371. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35372. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35373. }
  35374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35375. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  35376. }
  35377. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35378. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  35379. }
  35380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35381. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  35382. }
  35383. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35384. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  35385. }
  35386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35387. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  35388. }
  35389. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35390. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35391. }
  35392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35393. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35394. serializationObject.matricesIndices._isExpanded = true;
  35395. }
  35396. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35397. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35398. }
  35399. serializationObject.indices = this.getIndices();
  35400. return serializationObject;
  35401. };
  35402. // Statics
  35403. Geometry.ExtractFromMesh = function (mesh, id) {
  35404. var geometry = mesh._geometry;
  35405. if (!geometry) {
  35406. return null;
  35407. }
  35408. return geometry.copy(id);
  35409. };
  35410. /**
  35411. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35412. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35413. * Be aware Math.random() could cause collisions, but:
  35414. * "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"
  35415. */
  35416. Geometry.RandomId = function () {
  35417. return BABYLON.Tools.RandomId();
  35418. };
  35419. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  35420. var scene = mesh.getScene();
  35421. // Geometry
  35422. var geometryId = parsedGeometry.geometryId;
  35423. if (geometryId) {
  35424. var geometry = scene.getGeometryByID(geometryId);
  35425. if (geometry) {
  35426. geometry.applyToMesh(mesh);
  35427. }
  35428. }
  35429. else if (parsedGeometry instanceof ArrayBuffer) {
  35430. var binaryInfo = mesh._binaryInfo;
  35431. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35432. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35433. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35434. }
  35435. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35436. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35437. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35438. }
  35439. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35440. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35441. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35442. }
  35443. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35444. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35445. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35446. }
  35447. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35448. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35449. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35450. }
  35451. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35452. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35453. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35454. }
  35455. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35456. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35457. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35458. }
  35459. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35460. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35461. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35462. }
  35463. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35464. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35465. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35466. }
  35467. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35468. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35469. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35470. }
  35471. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35472. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35473. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35474. }
  35475. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35476. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35477. mesh.setIndices(indicesData);
  35478. }
  35479. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35480. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35481. mesh.subMeshes = [];
  35482. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35483. var materialIndex = subMeshesData[(i * 5) + 0];
  35484. var verticesStart = subMeshesData[(i * 5) + 1];
  35485. var verticesCount = subMeshesData[(i * 5) + 2];
  35486. var indexStart = subMeshesData[(i * 5) + 3];
  35487. var indexCount = subMeshesData[(i * 5) + 4];
  35488. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35489. }
  35490. }
  35491. }
  35492. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35493. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  35494. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  35495. if (parsedGeometry.uvs) {
  35496. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  35497. }
  35498. if (parsedGeometry.uvs2) {
  35499. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  35500. }
  35501. if (parsedGeometry.uvs3) {
  35502. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  35503. }
  35504. if (parsedGeometry.uvs4) {
  35505. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  35506. }
  35507. if (parsedGeometry.uvs5) {
  35508. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  35509. }
  35510. if (parsedGeometry.uvs6) {
  35511. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  35512. }
  35513. if (parsedGeometry.colors) {
  35514. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  35515. }
  35516. if (parsedGeometry.matricesIndices) {
  35517. if (!parsedGeometry.matricesIndices._isExpanded) {
  35518. var floatIndices = [];
  35519. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35520. var matricesIndex = parsedGeometry.matricesIndices[i];
  35521. floatIndices.push(matricesIndex & 0x000000FF);
  35522. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35523. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35524. floatIndices.push(matricesIndex >> 24);
  35525. }
  35526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  35527. }
  35528. else {
  35529. delete parsedGeometry.matricesIndices._isExpanded;
  35530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  35531. }
  35532. }
  35533. if (parsedGeometry.matricesIndicesExtra) {
  35534. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35535. var floatIndices = [];
  35536. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35537. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35538. floatIndices.push(matricesIndex & 0x000000FF);
  35539. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35540. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35541. floatIndices.push(matricesIndex >> 24);
  35542. }
  35543. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  35544. }
  35545. else {
  35546. delete parsedGeometry.matricesIndices._isExpanded;
  35547. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  35548. }
  35549. }
  35550. if (parsedGeometry.matricesWeights) {
  35551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  35552. }
  35553. if (parsedGeometry.matricesWeightsExtra) {
  35554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  35555. }
  35556. mesh.setIndices(parsedGeometry.indices);
  35557. }
  35558. // SubMeshes
  35559. if (parsedGeometry.subMeshes) {
  35560. mesh.subMeshes = [];
  35561. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35562. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35563. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35564. }
  35565. }
  35566. // Flat shading
  35567. if (mesh._shouldGenerateFlatShading) {
  35568. mesh.convertToFlatShadedMesh();
  35569. delete mesh._shouldGenerateFlatShading;
  35570. }
  35571. // Update
  35572. mesh.computeWorldMatrix(true);
  35573. // Octree
  35574. if (scene['_selectionOctree']) {
  35575. scene['_selectionOctree'].addMesh(mesh);
  35576. }
  35577. };
  35578. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35579. if (scene.getGeometryByID(parsedVertexData.id)) {
  35580. return null; // null since geometry could be something else than a box...
  35581. }
  35582. var geometry = new Geometry(parsedVertexData.id, scene);
  35583. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35584. if (parsedVertexData.delayLoadingFile) {
  35585. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35586. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35587. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35588. geometry._delayInfo = [];
  35589. if (parsedVertexData.hasUVs) {
  35590. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35591. }
  35592. if (parsedVertexData.hasUVs2) {
  35593. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35594. }
  35595. if (parsedVertexData.hasUVs3) {
  35596. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35597. }
  35598. if (parsedVertexData.hasUVs4) {
  35599. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35600. }
  35601. if (parsedVertexData.hasUVs5) {
  35602. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35603. }
  35604. if (parsedVertexData.hasUVs6) {
  35605. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35606. }
  35607. if (parsedVertexData.hasColors) {
  35608. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35609. }
  35610. if (parsedVertexData.hasMatricesIndices) {
  35611. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35612. }
  35613. if (parsedVertexData.hasMatricesWeights) {
  35614. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35615. }
  35616. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35617. }
  35618. else {
  35619. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35620. }
  35621. scene.pushGeometry(geometry, true);
  35622. return geometry;
  35623. };
  35624. return Geometry;
  35625. }());
  35626. BABYLON.Geometry = Geometry;
  35627. /////// Primitives //////////////////////////////////////////////
  35628. var Geometry;
  35629. (function (Geometry) {
  35630. var Primitives;
  35631. (function (Primitives) {
  35632. /// Abstract class
  35633. var _Primitive = (function (_super) {
  35634. __extends(_Primitive, _super);
  35635. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35636. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35637. this._canBeRegenerated = _canBeRegenerated;
  35638. this._beingRegenerated = true;
  35639. this.regenerate();
  35640. this._beingRegenerated = false;
  35641. }
  35642. _Primitive.prototype.canBeRegenerated = function () {
  35643. return this._canBeRegenerated;
  35644. };
  35645. _Primitive.prototype.regenerate = function () {
  35646. if (!this._canBeRegenerated) {
  35647. return;
  35648. }
  35649. this._beingRegenerated = true;
  35650. this.setAllVerticesData(this._regenerateVertexData(), false);
  35651. this._beingRegenerated = false;
  35652. };
  35653. _Primitive.prototype.asNewGeometry = function (id) {
  35654. return _super.prototype.copy.call(this, id);
  35655. };
  35656. // overrides
  35657. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35658. if (!this._beingRegenerated) {
  35659. return;
  35660. }
  35661. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35662. };
  35663. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35664. if (!this._beingRegenerated) {
  35665. return;
  35666. }
  35667. _super.prototype.setVerticesData.call(this, kind, data, false);
  35668. };
  35669. // to override
  35670. // protected
  35671. _Primitive.prototype._regenerateVertexData = function () {
  35672. throw new Error("Abstract method");
  35673. };
  35674. _Primitive.prototype.copy = function (id) {
  35675. throw new Error("Must be overriden in sub-classes.");
  35676. };
  35677. _Primitive.prototype.serialize = function () {
  35678. var serializationObject = _super.prototype.serialize.call(this);
  35679. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35680. return serializationObject;
  35681. };
  35682. return _Primitive;
  35683. }(Geometry));
  35684. Primitives._Primitive = _Primitive;
  35685. var Ribbon = (function (_super) {
  35686. __extends(Ribbon, _super);
  35687. // Members
  35688. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35689. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35690. _super.call(this, id, scene, canBeRegenerated, mesh);
  35691. this.pathArray = pathArray;
  35692. this.closeArray = closeArray;
  35693. this.closePath = closePath;
  35694. this.offset = offset;
  35695. this.side = side;
  35696. }
  35697. Ribbon.prototype._regenerateVertexData = function () {
  35698. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35699. };
  35700. Ribbon.prototype.copy = function (id) {
  35701. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35702. };
  35703. return Ribbon;
  35704. }(_Primitive));
  35705. Primitives.Ribbon = Ribbon;
  35706. var Box = (function (_super) {
  35707. __extends(Box, _super);
  35708. // Members
  35709. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35711. _super.call(this, id, scene, canBeRegenerated, mesh);
  35712. this.size = size;
  35713. this.side = side;
  35714. }
  35715. Box.prototype._regenerateVertexData = function () {
  35716. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35717. };
  35718. Box.prototype.copy = function (id) {
  35719. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35720. };
  35721. Box.prototype.serialize = function () {
  35722. var serializationObject = _super.prototype.serialize.call(this);
  35723. serializationObject.size = this.size;
  35724. return serializationObject;
  35725. };
  35726. Box.Parse = function (parsedBox, scene) {
  35727. if (scene.getGeometryByID(parsedBox.id)) {
  35728. return null; // null since geometry could be something else than a box...
  35729. }
  35730. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35731. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35732. scene.pushGeometry(box, true);
  35733. return box;
  35734. };
  35735. return Box;
  35736. }(_Primitive));
  35737. Primitives.Box = Box;
  35738. var Sphere = (function (_super) {
  35739. __extends(Sphere, _super);
  35740. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35741. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35742. _super.call(this, id, scene, canBeRegenerated, mesh);
  35743. this.segments = segments;
  35744. this.diameter = diameter;
  35745. this.side = side;
  35746. }
  35747. Sphere.prototype._regenerateVertexData = function () {
  35748. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35749. };
  35750. Sphere.prototype.copy = function (id) {
  35751. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35752. };
  35753. Sphere.prototype.serialize = function () {
  35754. var serializationObject = _super.prototype.serialize.call(this);
  35755. serializationObject.segments = this.segments;
  35756. serializationObject.diameter = this.diameter;
  35757. return serializationObject;
  35758. };
  35759. Sphere.Parse = function (parsedSphere, scene) {
  35760. if (scene.getGeometryByID(parsedSphere.id)) {
  35761. return null; // null since geometry could be something else than a sphere...
  35762. }
  35763. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35764. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35765. scene.pushGeometry(sphere, true);
  35766. return sphere;
  35767. };
  35768. return Sphere;
  35769. }(_Primitive));
  35770. Primitives.Sphere = Sphere;
  35771. var Disc = (function (_super) {
  35772. __extends(Disc, _super);
  35773. // Members
  35774. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35775. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35776. _super.call(this, id, scene, canBeRegenerated, mesh);
  35777. this.radius = radius;
  35778. this.tessellation = tessellation;
  35779. this.side = side;
  35780. }
  35781. Disc.prototype._regenerateVertexData = function () {
  35782. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35783. };
  35784. Disc.prototype.copy = function (id) {
  35785. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35786. };
  35787. return Disc;
  35788. }(_Primitive));
  35789. Primitives.Disc = Disc;
  35790. var Cylinder = (function (_super) {
  35791. __extends(Cylinder, _super);
  35792. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35793. if (subdivisions === void 0) { subdivisions = 1; }
  35794. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35795. _super.call(this, id, scene, canBeRegenerated, mesh);
  35796. this.height = height;
  35797. this.diameterTop = diameterTop;
  35798. this.diameterBottom = diameterBottom;
  35799. this.tessellation = tessellation;
  35800. this.subdivisions = subdivisions;
  35801. this.side = side;
  35802. }
  35803. Cylinder.prototype._regenerateVertexData = function () {
  35804. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35805. };
  35806. Cylinder.prototype.copy = function (id) {
  35807. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35808. };
  35809. Cylinder.prototype.serialize = function () {
  35810. var serializationObject = _super.prototype.serialize.call(this);
  35811. serializationObject.height = this.height;
  35812. serializationObject.diameterTop = this.diameterTop;
  35813. serializationObject.diameterBottom = this.diameterBottom;
  35814. serializationObject.tessellation = this.tessellation;
  35815. return serializationObject;
  35816. };
  35817. Cylinder.Parse = function (parsedCylinder, scene) {
  35818. if (scene.getGeometryByID(parsedCylinder.id)) {
  35819. return null; // null since geometry could be something else than a cylinder...
  35820. }
  35821. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35822. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35823. scene.pushGeometry(cylinder, true);
  35824. return cylinder;
  35825. };
  35826. return Cylinder;
  35827. }(_Primitive));
  35828. Primitives.Cylinder = Cylinder;
  35829. var Torus = (function (_super) {
  35830. __extends(Torus, _super);
  35831. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35832. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35833. _super.call(this, id, scene, canBeRegenerated, mesh);
  35834. this.diameter = diameter;
  35835. this.thickness = thickness;
  35836. this.tessellation = tessellation;
  35837. this.side = side;
  35838. }
  35839. Torus.prototype._regenerateVertexData = function () {
  35840. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35841. };
  35842. Torus.prototype.copy = function (id) {
  35843. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35844. };
  35845. Torus.prototype.serialize = function () {
  35846. var serializationObject = _super.prototype.serialize.call(this);
  35847. serializationObject.diameter = this.diameter;
  35848. serializationObject.thickness = this.thickness;
  35849. serializationObject.tessellation = this.tessellation;
  35850. return serializationObject;
  35851. };
  35852. Torus.Parse = function (parsedTorus, scene) {
  35853. if (scene.getGeometryByID(parsedTorus.id)) {
  35854. return null; // null since geometry could be something else than a torus...
  35855. }
  35856. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35857. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35858. scene.pushGeometry(torus, true);
  35859. return torus;
  35860. };
  35861. return Torus;
  35862. }(_Primitive));
  35863. Primitives.Torus = Torus;
  35864. var Ground = (function (_super) {
  35865. __extends(Ground, _super);
  35866. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35867. _super.call(this, id, scene, canBeRegenerated, mesh);
  35868. this.width = width;
  35869. this.height = height;
  35870. this.subdivisions = subdivisions;
  35871. }
  35872. Ground.prototype._regenerateVertexData = function () {
  35873. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35874. };
  35875. Ground.prototype.copy = function (id) {
  35876. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35877. };
  35878. Ground.prototype.serialize = function () {
  35879. var serializationObject = _super.prototype.serialize.call(this);
  35880. serializationObject.width = this.width;
  35881. serializationObject.height = this.height;
  35882. serializationObject.subdivisions = this.subdivisions;
  35883. return serializationObject;
  35884. };
  35885. Ground.Parse = function (parsedGround, scene) {
  35886. if (scene.getGeometryByID(parsedGround.id)) {
  35887. return null; // null since geometry could be something else than a ground...
  35888. }
  35889. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35890. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35891. scene.pushGeometry(ground, true);
  35892. return ground;
  35893. };
  35894. return Ground;
  35895. }(_Primitive));
  35896. Primitives.Ground = Ground;
  35897. var TiledGround = (function (_super) {
  35898. __extends(TiledGround, _super);
  35899. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35900. _super.call(this, id, scene, canBeRegenerated, mesh);
  35901. this.xmin = xmin;
  35902. this.zmin = zmin;
  35903. this.xmax = xmax;
  35904. this.zmax = zmax;
  35905. this.subdivisions = subdivisions;
  35906. this.precision = precision;
  35907. }
  35908. TiledGround.prototype._regenerateVertexData = function () {
  35909. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35910. };
  35911. TiledGround.prototype.copy = function (id) {
  35912. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35913. };
  35914. return TiledGround;
  35915. }(_Primitive));
  35916. Primitives.TiledGround = TiledGround;
  35917. var Plane = (function (_super) {
  35918. __extends(Plane, _super);
  35919. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35920. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35921. _super.call(this, id, scene, canBeRegenerated, mesh);
  35922. this.size = size;
  35923. this.side = side;
  35924. }
  35925. Plane.prototype._regenerateVertexData = function () {
  35926. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35927. };
  35928. Plane.prototype.copy = function (id) {
  35929. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35930. };
  35931. Plane.prototype.serialize = function () {
  35932. var serializationObject = _super.prototype.serialize.call(this);
  35933. serializationObject.size = this.size;
  35934. return serializationObject;
  35935. };
  35936. Plane.Parse = function (parsedPlane, scene) {
  35937. if (scene.getGeometryByID(parsedPlane.id)) {
  35938. return null; // null since geometry could be something else than a ground...
  35939. }
  35940. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35941. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35942. scene.pushGeometry(plane, true);
  35943. return plane;
  35944. };
  35945. return Plane;
  35946. }(_Primitive));
  35947. Primitives.Plane = Plane;
  35948. var TorusKnot = (function (_super) {
  35949. __extends(TorusKnot, _super);
  35950. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35951. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35952. _super.call(this, id, scene, canBeRegenerated, mesh);
  35953. this.radius = radius;
  35954. this.tube = tube;
  35955. this.radialSegments = radialSegments;
  35956. this.tubularSegments = tubularSegments;
  35957. this.p = p;
  35958. this.q = q;
  35959. this.side = side;
  35960. }
  35961. TorusKnot.prototype._regenerateVertexData = function () {
  35962. 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 });
  35963. };
  35964. TorusKnot.prototype.copy = function (id) {
  35965. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35966. };
  35967. TorusKnot.prototype.serialize = function () {
  35968. var serializationObject = _super.prototype.serialize.call(this);
  35969. serializationObject.radius = this.radius;
  35970. serializationObject.tube = this.tube;
  35971. serializationObject.radialSegments = this.radialSegments;
  35972. serializationObject.tubularSegments = this.tubularSegments;
  35973. serializationObject.p = this.p;
  35974. serializationObject.q = this.q;
  35975. return serializationObject;
  35976. };
  35977. ;
  35978. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35979. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35980. return null; // null since geometry could be something else than a ground...
  35981. }
  35982. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35983. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35984. scene.pushGeometry(torusKnot, true);
  35985. return torusKnot;
  35986. };
  35987. return TorusKnot;
  35988. }(_Primitive));
  35989. Primitives.TorusKnot = TorusKnot;
  35990. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35991. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35992. })(BABYLON || (BABYLON = {}));
  35993. var BABYLON;
  35994. (function (BABYLON) {
  35995. var GroundMesh = (function (_super) {
  35996. __extends(GroundMesh, _super);
  35997. function GroundMesh(name, scene) {
  35998. _super.call(this, name, scene);
  35999. this.generateOctree = false;
  36000. this._worldInverse = new BABYLON.Matrix();
  36001. }
  36002. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  36003. get: function () {
  36004. return Math.min(this._subdivisionsX, this._subdivisionsY);
  36005. },
  36006. enumerable: true,
  36007. configurable: true
  36008. });
  36009. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  36010. get: function () {
  36011. return this._subdivisionsX;
  36012. },
  36013. enumerable: true,
  36014. configurable: true
  36015. });
  36016. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  36017. get: function () {
  36018. return this._subdivisionsY;
  36019. },
  36020. enumerable: true,
  36021. configurable: true
  36022. });
  36023. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  36024. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  36025. this._subdivisionsX = chunksCount;
  36026. this._subdivisionsY = chunksCount;
  36027. this.subdivide(chunksCount);
  36028. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  36029. };
  36030. /**
  36031. * Returns a height (y) value in the Worl system :
  36032. * the ground altitude at the coordinates (x, z) expressed in the World system.
  36033. * Returns the ground y position if (x, z) are outside the ground surface.
  36034. * Not pertinent if the ground is rotated.
  36035. */
  36036. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  36037. // express x and y in the ground local system
  36038. x -= this.position.x;
  36039. z -= this.position.z;
  36040. x /= this.scaling.x;
  36041. z /= this.scaling.z;
  36042. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36043. return this.position.y;
  36044. }
  36045. if (!this._heightQuads || this._heightQuads.length == 0) {
  36046. this._initHeightQuads();
  36047. this._computeHeightQuads();
  36048. }
  36049. var facet = this._getFacetAt(x, z);
  36050. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  36051. // return y in the World system
  36052. return y * this.scaling.y + this.position.y;
  36053. };
  36054. /**
  36055. * Returns a normalized vector (Vector3) orthogonal to the ground
  36056. * at the ground coordinates (x, z) expressed in the World system.
  36057. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  36058. * Not pertinent if the ground is rotated.
  36059. */
  36060. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  36061. var normal = new BABYLON.Vector3(0, 1, 0);
  36062. this.getNormalAtCoordinatesToRef(x, z, normal);
  36063. return normal;
  36064. };
  36065. /**
  36066. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36067. * at the ground coordinates (x, z) expressed in the World system.
  36068. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36069. * Not pertinent if the ground is rotated.
  36070. */
  36071. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36072. // express x and y in the ground local system
  36073. x -= this.position.x;
  36074. z -= this.position.z;
  36075. x /= this.scaling.x;
  36076. z /= this.scaling.z;
  36077. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36078. return;
  36079. }
  36080. if (!this._heightQuads || this._heightQuads.length == 0) {
  36081. this._initHeightQuads();
  36082. this._computeHeightQuads();
  36083. }
  36084. var facet = this._getFacetAt(x, z);
  36085. ref.x = facet.x;
  36086. ref.y = facet.y;
  36087. ref.z = facet.z;
  36088. };
  36089. /**
  36090. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36091. * if the ground has been updated.
  36092. * This can be used in the render loop
  36093. */
  36094. GroundMesh.prototype.updateCoordinateHeights = function () {
  36095. if (!this._heightQuads || this._heightQuads.length == 0) {
  36096. this._initHeightQuads();
  36097. }
  36098. this._computeHeightQuads();
  36099. };
  36100. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36101. GroundMesh.prototype._getFacetAt = function (x, z) {
  36102. // retrieve col and row from x, z coordinates in the ground local system
  36103. var subdivisionsX = this._subdivisionsX;
  36104. var subdivisionsY = this._subdivisionsY;
  36105. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36106. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36107. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36108. var facet;
  36109. if (z < quad.slope.x * x + quad.slope.y) {
  36110. facet = quad.facet1;
  36111. }
  36112. else {
  36113. facet = quad.facet2;
  36114. }
  36115. return facet;
  36116. };
  36117. // Creates and populates the heightMap array with "facet" elements :
  36118. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36119. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36120. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36121. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36122. GroundMesh.prototype._initHeightQuads = function () {
  36123. var subdivisionsX = this._subdivisionsX;
  36124. var subdivisionsY = this._subdivisionsY;
  36125. this._heightQuads = new Array();
  36126. for (var row = 0; row < subdivisionsY; row++) {
  36127. for (var col = 0; col < subdivisionsX; col++) {
  36128. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  36129. this._heightQuads[row * subdivisionsX + col] = quad;
  36130. }
  36131. }
  36132. };
  36133. // Compute each quad element values and update the the heightMap array :
  36134. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36135. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36136. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36137. GroundMesh.prototype._computeHeightQuads = function () {
  36138. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36139. var v1 = BABYLON.Tmp.Vector3[3];
  36140. var v2 = BABYLON.Tmp.Vector3[2];
  36141. var v3 = BABYLON.Tmp.Vector3[1];
  36142. var v4 = BABYLON.Tmp.Vector3[0];
  36143. var v1v2 = BABYLON.Tmp.Vector3[4];
  36144. var v1v3 = BABYLON.Tmp.Vector3[5];
  36145. var v1v4 = BABYLON.Tmp.Vector3[6];
  36146. var norm1 = BABYLON.Tmp.Vector3[7];
  36147. var norm2 = BABYLON.Tmp.Vector3[8];
  36148. var i = 0;
  36149. var j = 0;
  36150. var k = 0;
  36151. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36152. var h = 0;
  36153. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36154. var d2 = 0;
  36155. var subdivisionsX = this._subdivisionsX;
  36156. var subdivisionsY = this._subdivisionsY;
  36157. for (var row = 0; row < subdivisionsY; row++) {
  36158. for (var col = 0; col < subdivisionsX; col++) {
  36159. i = col * 3;
  36160. j = row * (subdivisionsX + 1) * 3;
  36161. k = (row + 1) * (subdivisionsX + 1) * 3;
  36162. v1.x = positions[j + i];
  36163. v1.y = positions[j + i + 1];
  36164. v1.z = positions[j + i + 2];
  36165. v2.x = positions[j + i + 3];
  36166. v2.y = positions[j + i + 4];
  36167. v2.z = positions[j + i + 5];
  36168. v3.x = positions[k + i];
  36169. v3.y = positions[k + i + 1];
  36170. v3.z = positions[k + i + 2];
  36171. v4.x = positions[k + i + 3];
  36172. v4.y = positions[k + i + 4];
  36173. v4.z = positions[k + i + 5];
  36174. // 2D slope V1V4
  36175. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36176. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36177. // facet equations :
  36178. // we compute each facet normal vector
  36179. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36180. // we compute the value d by applying the equation to v1 which belongs to the plane
  36181. // then we store the facet equation in a Vector4
  36182. v2.subtractToRef(v1, v1v2);
  36183. v3.subtractToRef(v1, v1v3);
  36184. v4.subtractToRef(v1, v1v4);
  36185. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36186. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36187. norm1.normalize();
  36188. norm2.normalize();
  36189. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36190. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36191. var quad = this._heightQuads[row * subdivisionsX + col];
  36192. quad.slope.copyFromFloats(cd, h);
  36193. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36194. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36195. }
  36196. }
  36197. };
  36198. return GroundMesh;
  36199. }(BABYLON.Mesh));
  36200. BABYLON.GroundMesh = GroundMesh;
  36201. })(BABYLON || (BABYLON = {}));
  36202. var BABYLON;
  36203. (function (BABYLON) {
  36204. var LinesMesh = (function (_super) {
  36205. __extends(LinesMesh, _super);
  36206. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  36207. if (parent === void 0) { parent = null; }
  36208. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  36209. this.color = new BABYLON.Color3(1, 1, 1);
  36210. this.alpha = 1;
  36211. this._positionBuffer = {};
  36212. if (source) {
  36213. this.color = source.color.clone();
  36214. this.alpha = source.alpha;
  36215. }
  36216. this._intersectionThreshold = 0.1;
  36217. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  36218. attributes: [BABYLON.VertexBuffer.PositionKind],
  36219. uniforms: ["worldViewProjection", "color"],
  36220. needAlphaBlending: true
  36221. });
  36222. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  36223. }
  36224. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  36225. /**
  36226. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36227. * This margin is expressed in world space coordinates, so its value may vary.
  36228. * Default value is 0.1
  36229. * @returns the intersection Threshold value.
  36230. */
  36231. get: function () {
  36232. return this._intersectionThreshold;
  36233. },
  36234. /**
  36235. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36236. * This margin is expressed in world space coordinates, so its value may vary.
  36237. * @param value the new threshold to apply
  36238. */
  36239. set: function (value) {
  36240. if (this._intersectionThreshold === value) {
  36241. return;
  36242. }
  36243. this._intersectionThreshold = value;
  36244. if (this.geometry) {
  36245. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  36246. }
  36247. },
  36248. enumerable: true,
  36249. configurable: true
  36250. });
  36251. Object.defineProperty(LinesMesh.prototype, "material", {
  36252. get: function () {
  36253. return this._colorShader;
  36254. },
  36255. enumerable: true,
  36256. configurable: true
  36257. });
  36258. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  36259. get: function () {
  36260. return false;
  36261. },
  36262. enumerable: true,
  36263. configurable: true
  36264. });
  36265. LinesMesh.prototype.createInstance = function (name) {
  36266. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  36267. return null;
  36268. };
  36269. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  36270. var engine = this.getScene().getEngine();
  36271. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  36272. // VBOs
  36273. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  36274. // Color
  36275. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  36276. };
  36277. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  36278. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  36279. return;
  36280. }
  36281. var engine = this.getScene().getEngine();
  36282. // Draw order
  36283. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  36284. };
  36285. LinesMesh.prototype.dispose = function (doNotRecurse) {
  36286. this._colorShader.dispose();
  36287. _super.prototype.dispose.call(this, doNotRecurse);
  36288. };
  36289. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  36290. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  36291. };
  36292. return LinesMesh;
  36293. }(BABYLON.Mesh));
  36294. BABYLON.LinesMesh = LinesMesh;
  36295. })(BABYLON || (BABYLON = {}));
  36296. var BABYLON;
  36297. (function (BABYLON) {
  36298. var DefaultLoadingScreen = (function () {
  36299. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  36300. var _this = this;
  36301. if (_loadingText === void 0) { _loadingText = ""; }
  36302. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  36303. this._renderingCanvas = _renderingCanvas;
  36304. this._loadingText = _loadingText;
  36305. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  36306. // Resize
  36307. this._resizeLoadingUI = function () {
  36308. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  36309. _this._loadingDiv.style.position = "absolute";
  36310. _this._loadingDiv.style.left = canvasRect.left + "px";
  36311. _this._loadingDiv.style.top = canvasRect.top + "px";
  36312. _this._loadingDiv.style.width = canvasRect.width + "px";
  36313. _this._loadingDiv.style.height = canvasRect.height + "px";
  36314. };
  36315. }
  36316. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  36317. var _this = this;
  36318. if (this._loadingDiv) {
  36319. // Do not add a loading screen if there is already one
  36320. return;
  36321. }
  36322. this._loadingDiv = document.createElement("div");
  36323. this._loadingDiv.id = "babylonjsLoadingDiv";
  36324. this._loadingDiv.style.opacity = "0";
  36325. this._loadingDiv.style.transition = "opacity 1.5s ease";
  36326. // Loading text
  36327. this._loadingTextDiv = document.createElement("div");
  36328. this._loadingTextDiv.style.position = "absolute";
  36329. this._loadingTextDiv.style.left = "0";
  36330. this._loadingTextDiv.style.top = "50%";
  36331. this._loadingTextDiv.style.marginTop = "80px";
  36332. this._loadingTextDiv.style.width = "100%";
  36333. this._loadingTextDiv.style.height = "20px";
  36334. this._loadingTextDiv.style.fontFamily = "Arial";
  36335. this._loadingTextDiv.style.fontSize = "14px";
  36336. this._loadingTextDiv.style.color = "white";
  36337. this._loadingTextDiv.style.textAlign = "center";
  36338. this._loadingTextDiv.innerHTML = "Loading";
  36339. this._loadingDiv.appendChild(this._loadingTextDiv);
  36340. //set the predefined text
  36341. this._loadingTextDiv.innerHTML = this._loadingText;
  36342. // Loading img
  36343. var imgBack = new Image();
  36344. 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==";
  36345. imgBack.style.position = "absolute";
  36346. imgBack.style.left = "50%";
  36347. imgBack.style.top = "50%";
  36348. imgBack.style.marginLeft = "-50px";
  36349. imgBack.style.marginTop = "-50px";
  36350. imgBack.style.transition = "transform 1.0s ease";
  36351. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  36352. var deg = 360;
  36353. var onTransitionEnd = function () {
  36354. deg += 360;
  36355. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  36356. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  36357. };
  36358. imgBack.addEventListener("transitionend", onTransitionEnd);
  36359. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  36360. this._loadingDiv.appendChild(imgBack);
  36361. // front image
  36362. var imgFront = new Image();
  36363. 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=";
  36364. imgFront.style.position = "absolute";
  36365. imgFront.style.left = "50%";
  36366. imgFront.style.top = "50%";
  36367. imgFront.style.marginLeft = "-50px";
  36368. imgFront.style.marginTop = "-50px";
  36369. this._loadingDiv.appendChild(imgFront);
  36370. this._resizeLoadingUI();
  36371. window.addEventListener("resize", this._resizeLoadingUI);
  36372. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36373. document.body.appendChild(this._loadingDiv);
  36374. setTimeout(function () {
  36375. _this._loadingDiv.style.opacity = "1";
  36376. imgBack.style.transform = "rotateZ(360deg)";
  36377. imgBack.style.webkitTransform = "rotateZ(360deg)";
  36378. }, 0);
  36379. };
  36380. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  36381. var _this = this;
  36382. if (!this._loadingDiv) {
  36383. return;
  36384. }
  36385. var onTransitionEnd = function () {
  36386. if (!_this._loadingDiv) {
  36387. return;
  36388. }
  36389. document.body.removeChild(_this._loadingDiv);
  36390. window.removeEventListener("resize", _this._resizeLoadingUI);
  36391. _this._loadingDiv = null;
  36392. };
  36393. this._loadingDiv.style.opacity = "0";
  36394. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  36395. };
  36396. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  36397. set: function (text) {
  36398. this._loadingText = text;
  36399. if (this._loadingTextDiv) {
  36400. this._loadingTextDiv.innerHTML = this._loadingText;
  36401. }
  36402. },
  36403. enumerable: true,
  36404. configurable: true
  36405. });
  36406. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  36407. get: function () {
  36408. return this._loadingDivBackgroundColor;
  36409. },
  36410. set: function (color) {
  36411. this._loadingDivBackgroundColor = color;
  36412. if (!this._loadingDiv) {
  36413. return;
  36414. }
  36415. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36416. },
  36417. enumerable: true,
  36418. configurable: true
  36419. });
  36420. return DefaultLoadingScreen;
  36421. }());
  36422. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  36423. })(BABYLON || (BABYLON = {}));
  36424. var BABYLON;
  36425. (function (BABYLON) {
  36426. var AudioEngine = (function () {
  36427. function AudioEngine() {
  36428. this._audioContext = null;
  36429. this._audioContextInitialized = false;
  36430. this.canUseWebAudio = false;
  36431. this.WarnedWebAudioUnsupported = false;
  36432. this.unlocked = false;
  36433. this.isMP3supported = false;
  36434. this.isOGGsupported = false;
  36435. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  36436. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  36437. this.canUseWebAudio = true;
  36438. }
  36439. var audioElem = document.createElement('audio');
  36440. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  36441. this.isMP3supported = true;
  36442. }
  36443. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  36444. this.isOGGsupported = true;
  36445. }
  36446. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  36447. this._unlockiOSaudio();
  36448. }
  36449. else {
  36450. this.unlocked = true;
  36451. }
  36452. }
  36453. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  36454. get: function () {
  36455. if (!this._audioContextInitialized) {
  36456. this._initializeAudioContext();
  36457. }
  36458. return this._audioContext;
  36459. },
  36460. enumerable: true,
  36461. configurable: true
  36462. });
  36463. AudioEngine.prototype._unlockiOSaudio = function () {
  36464. var _this = this;
  36465. var unlockaudio = function () {
  36466. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  36467. var source = _this.audioContext.createBufferSource();
  36468. source.buffer = buffer;
  36469. source.connect(_this.audioContext.destination);
  36470. source.start(0);
  36471. setTimeout(function () {
  36472. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  36473. _this.unlocked = true;
  36474. window.removeEventListener('touchend', unlockaudio, false);
  36475. if (_this.onAudioUnlocked) {
  36476. _this.onAudioUnlocked();
  36477. }
  36478. }
  36479. }, 0);
  36480. };
  36481. window.addEventListener('touchend', unlockaudio, false);
  36482. };
  36483. AudioEngine.prototype._initializeAudioContext = function () {
  36484. try {
  36485. if (this.canUseWebAudio) {
  36486. this._audioContext = new AudioContext();
  36487. // create a global volume gain node
  36488. this.masterGain = this._audioContext.createGain();
  36489. this.masterGain.gain.value = 1;
  36490. this.masterGain.connect(this._audioContext.destination);
  36491. this._audioContextInitialized = true;
  36492. }
  36493. }
  36494. catch (e) {
  36495. this.canUseWebAudio = false;
  36496. BABYLON.Tools.Error("Web Audio: " + e.message);
  36497. }
  36498. };
  36499. AudioEngine.prototype.dispose = function () {
  36500. if (this.canUseWebAudio && this._audioContextInitialized) {
  36501. if (this._connectedAnalyser) {
  36502. this._connectedAnalyser.stopDebugCanvas();
  36503. this._connectedAnalyser.dispose();
  36504. this.masterGain.disconnect();
  36505. this.masterGain.connect(this._audioContext.destination);
  36506. this._connectedAnalyser = null;
  36507. }
  36508. this.masterGain.gain.value = 1;
  36509. }
  36510. this.WarnedWebAudioUnsupported = false;
  36511. };
  36512. AudioEngine.prototype.getGlobalVolume = function () {
  36513. if (this.canUseWebAudio && this._audioContextInitialized) {
  36514. return this.masterGain.gain.value;
  36515. }
  36516. else {
  36517. return -1;
  36518. }
  36519. };
  36520. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  36521. if (this.canUseWebAudio && this._audioContextInitialized) {
  36522. this.masterGain.gain.value = newVolume;
  36523. }
  36524. };
  36525. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  36526. if (this._connectedAnalyser) {
  36527. this._connectedAnalyser.stopDebugCanvas();
  36528. }
  36529. if (this.canUseWebAudio && this._audioContextInitialized) {
  36530. this._connectedAnalyser = analyser;
  36531. this.masterGain.disconnect();
  36532. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  36533. }
  36534. };
  36535. return AudioEngine;
  36536. }());
  36537. BABYLON.AudioEngine = AudioEngine;
  36538. })(BABYLON || (BABYLON = {}));
  36539. var BABYLON;
  36540. (function (BABYLON) {
  36541. var Sound = (function () {
  36542. /**
  36543. * Create a sound and attach it to a scene
  36544. * @param name Name of your sound
  36545. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  36546. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  36547. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  36548. */
  36549. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  36550. var _this = this;
  36551. this.autoplay = false;
  36552. this.loop = false;
  36553. this.useCustomAttenuation = false;
  36554. this.spatialSound = false;
  36555. this.refDistance = 1;
  36556. this.rolloffFactor = 1;
  36557. this.maxDistance = 100;
  36558. this.distanceModel = "linear";
  36559. this._panningModel = "equalpower";
  36560. this._playbackRate = 1;
  36561. this._streaming = false;
  36562. this._startTime = 0;
  36563. this._startOffset = 0;
  36564. this._position = BABYLON.Vector3.Zero();
  36565. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  36566. this._volume = 1;
  36567. this._isLoaded = false;
  36568. this._isReadyToPlay = false;
  36569. this.isPlaying = false;
  36570. this.isPaused = false;
  36571. this._isDirectional = false;
  36572. // Used if you'd like to create a directional sound.
  36573. // If not set, the sound will be omnidirectional
  36574. this._coneInnerAngle = 360;
  36575. this._coneOuterAngle = 360;
  36576. this._coneOuterGain = 0;
  36577. this._isOutputConnected = false;
  36578. this._urlType = "Unknown";
  36579. this.name = name;
  36580. this._scene = scene;
  36581. this._readyToPlayCallback = readyToPlayCallback;
  36582. // Default custom attenuation function is a linear attenuation
  36583. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36584. if (currentDistance < maxDistance) {
  36585. return currentVolume * (1 - currentDistance / maxDistance);
  36586. }
  36587. else {
  36588. return 0;
  36589. }
  36590. };
  36591. if (options) {
  36592. this.autoplay = options.autoplay || false;
  36593. this.loop = options.loop || false;
  36594. // if volume === 0, we need another way to check this option
  36595. if (options.volume !== undefined) {
  36596. this._volume = options.volume;
  36597. }
  36598. this.spatialSound = options.spatialSound || false;
  36599. this.maxDistance = options.maxDistance || 100;
  36600. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36601. this.rolloffFactor = options.rolloffFactor || 1;
  36602. this.refDistance = options.refDistance || 1;
  36603. this.distanceModel = options.distanceModel || "linear";
  36604. this._playbackRate = options.playbackRate || 1;
  36605. this._streaming = options.streaming || false;
  36606. }
  36607. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36608. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36609. this._soundGain.gain.value = this._volume;
  36610. this._inputAudioNode = this._soundGain;
  36611. this._ouputAudioNode = this._soundGain;
  36612. if (this.spatialSound) {
  36613. this._createSpatialParameters();
  36614. }
  36615. this._scene.mainSoundTrack.AddSound(this);
  36616. var validParameter = true;
  36617. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36618. if (urlOrArrayBuffer) {
  36619. if (typeof (urlOrArrayBuffer) === "string")
  36620. this._urlType = "String";
  36621. if (Array.isArray(urlOrArrayBuffer))
  36622. this._urlType = "Array";
  36623. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36624. this._urlType = "ArrayBuffer";
  36625. var urls = [];
  36626. var codecSupportedFound = false;
  36627. switch (this._urlType) {
  36628. case "ArrayBuffer":
  36629. if (urlOrArrayBuffer.byteLength > 0) {
  36630. codecSupportedFound = true;
  36631. this._soundLoaded(urlOrArrayBuffer);
  36632. }
  36633. break;
  36634. case "String":
  36635. urls.push(urlOrArrayBuffer);
  36636. case "Array":
  36637. if (urls.length === 0)
  36638. urls = urlOrArrayBuffer;
  36639. // If we found a supported format, we load it immediately and stop the loop
  36640. for (var i = 0; i < urls.length; i++) {
  36641. var url = urls[i];
  36642. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36643. codecSupportedFound = true;
  36644. }
  36645. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36646. codecSupportedFound = true;
  36647. }
  36648. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36649. codecSupportedFound = true;
  36650. }
  36651. if (codecSupportedFound) {
  36652. // Loading sound using XHR2
  36653. if (!this._streaming) {
  36654. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36655. }
  36656. else {
  36657. this._htmlAudioElement = new Audio(url);
  36658. this._htmlAudioElement.controls = false;
  36659. this._htmlAudioElement.loop = this.loop;
  36660. this._htmlAudioElement.crossOrigin = "anonymous";
  36661. this._htmlAudioElement.preload = "auto";
  36662. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36663. _this._isReadyToPlay = true;
  36664. if (_this.autoplay) {
  36665. _this.play();
  36666. }
  36667. if (_this._readyToPlayCallback) {
  36668. _this._readyToPlayCallback();
  36669. }
  36670. });
  36671. document.body.appendChild(this._htmlAudioElement);
  36672. }
  36673. break;
  36674. }
  36675. }
  36676. break;
  36677. default:
  36678. validParameter = false;
  36679. break;
  36680. }
  36681. if (!validParameter) {
  36682. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36683. }
  36684. else {
  36685. if (!codecSupportedFound) {
  36686. this._isReadyToPlay = true;
  36687. // Simulating a ready to play event to avoid breaking code path
  36688. if (this._readyToPlayCallback) {
  36689. window.setTimeout(function () {
  36690. _this._readyToPlayCallback();
  36691. }, 1000);
  36692. }
  36693. }
  36694. }
  36695. }
  36696. }
  36697. else {
  36698. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36699. this._scene.mainSoundTrack.AddSound(this);
  36700. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36701. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36702. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36703. }
  36704. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36705. if (this._readyToPlayCallback) {
  36706. window.setTimeout(function () {
  36707. _this._readyToPlayCallback();
  36708. }, 1000);
  36709. }
  36710. }
  36711. }
  36712. Sound.prototype.dispose = function () {
  36713. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36714. if (this.isPlaying) {
  36715. this.stop();
  36716. }
  36717. this._isReadyToPlay = false;
  36718. if (this.soundTrackId === -1) {
  36719. this._scene.mainSoundTrack.RemoveSound(this);
  36720. }
  36721. else {
  36722. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36723. }
  36724. if (this._soundGain) {
  36725. this._soundGain.disconnect();
  36726. this._soundGain = null;
  36727. }
  36728. if (this._soundPanner) {
  36729. this._soundPanner.disconnect();
  36730. this._soundPanner = null;
  36731. }
  36732. if (this._soundSource) {
  36733. this._soundSource.disconnect();
  36734. this._soundSource = null;
  36735. }
  36736. this._audioBuffer = null;
  36737. if (this._htmlAudioElement) {
  36738. this._htmlAudioElement.pause();
  36739. this._htmlAudioElement.src = "";
  36740. document.body.removeChild(this._htmlAudioElement);
  36741. }
  36742. if (this._connectedMesh) {
  36743. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36744. this._connectedMesh = null;
  36745. }
  36746. }
  36747. };
  36748. Sound.prototype._soundLoaded = function (audioData) {
  36749. var _this = this;
  36750. this._isLoaded = true;
  36751. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36752. _this._audioBuffer = buffer;
  36753. _this._isReadyToPlay = true;
  36754. if (_this.autoplay) {
  36755. _this.play();
  36756. }
  36757. if (_this._readyToPlayCallback) {
  36758. _this._readyToPlayCallback();
  36759. }
  36760. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36761. };
  36762. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36763. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36764. this._audioBuffer = audioBuffer;
  36765. this._isReadyToPlay = true;
  36766. }
  36767. };
  36768. Sound.prototype.updateOptions = function (options) {
  36769. if (options) {
  36770. this.loop = options.loop || this.loop;
  36771. this.maxDistance = options.maxDistance || this.maxDistance;
  36772. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36773. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36774. this.refDistance = options.refDistance || this.refDistance;
  36775. this.distanceModel = options.distanceModel || this.distanceModel;
  36776. this._playbackRate = options.playbackRate || this._playbackRate;
  36777. this._updateSpatialParameters();
  36778. if (this.isPlaying) {
  36779. if (this._streaming) {
  36780. this._htmlAudioElement.playbackRate = this._playbackRate;
  36781. }
  36782. else {
  36783. this._soundSource.playbackRate.value = this._playbackRate;
  36784. }
  36785. }
  36786. }
  36787. };
  36788. Sound.prototype._createSpatialParameters = function () {
  36789. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36790. if (this._scene.headphone) {
  36791. this._panningModel = "HRTF";
  36792. }
  36793. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36794. this._updateSpatialParameters();
  36795. this._soundPanner.connect(this._ouputAudioNode);
  36796. this._inputAudioNode = this._soundPanner;
  36797. }
  36798. };
  36799. Sound.prototype._updateSpatialParameters = function () {
  36800. if (this.spatialSound) {
  36801. if (this.useCustomAttenuation) {
  36802. // Tricks to disable in a way embedded Web Audio attenuation
  36803. this._soundPanner.distanceModel = "linear";
  36804. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36805. this._soundPanner.refDistance = 1;
  36806. this._soundPanner.rolloffFactor = 1;
  36807. this._soundPanner.panningModel = this._panningModel;
  36808. }
  36809. else {
  36810. this._soundPanner.distanceModel = this.distanceModel;
  36811. this._soundPanner.maxDistance = this.maxDistance;
  36812. this._soundPanner.refDistance = this.refDistance;
  36813. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36814. this._soundPanner.panningModel = this._panningModel;
  36815. }
  36816. }
  36817. };
  36818. Sound.prototype.switchPanningModelToHRTF = function () {
  36819. this._panningModel = "HRTF";
  36820. this._switchPanningModel();
  36821. };
  36822. Sound.prototype.switchPanningModelToEqualPower = function () {
  36823. this._panningModel = "equalpower";
  36824. this._switchPanningModel();
  36825. };
  36826. Sound.prototype._switchPanningModel = function () {
  36827. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36828. this._soundPanner.panningModel = this._panningModel;
  36829. }
  36830. };
  36831. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36832. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36833. if (this._isOutputConnected) {
  36834. this._ouputAudioNode.disconnect();
  36835. }
  36836. this._ouputAudioNode.connect(soundTrackAudioNode);
  36837. this._isOutputConnected = true;
  36838. }
  36839. };
  36840. /**
  36841. * Transform this sound into a directional source
  36842. * @param coneInnerAngle Size of the inner cone in degree
  36843. * @param coneOuterAngle Size of the outer cone in degree
  36844. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36845. */
  36846. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36847. if (coneOuterAngle < coneInnerAngle) {
  36848. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36849. return;
  36850. }
  36851. this._coneInnerAngle = coneInnerAngle;
  36852. this._coneOuterAngle = coneOuterAngle;
  36853. this._coneOuterGain = coneOuterGain;
  36854. this._isDirectional = true;
  36855. if (this.isPlaying && this.loop) {
  36856. this.stop();
  36857. this.play();
  36858. }
  36859. };
  36860. Sound.prototype.setPosition = function (newPosition) {
  36861. this._position = newPosition;
  36862. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36863. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36864. }
  36865. };
  36866. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36867. this._localDirection = newLocalDirection;
  36868. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36869. this._updateDirection();
  36870. }
  36871. };
  36872. Sound.prototype._updateDirection = function () {
  36873. var mat = this._connectedMesh.getWorldMatrix();
  36874. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36875. direction.normalize();
  36876. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36877. };
  36878. Sound.prototype.updateDistanceFromListener = function () {
  36879. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36880. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36881. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36882. }
  36883. };
  36884. Sound.prototype.setAttenuationFunction = function (callback) {
  36885. this._customAttenuationFunction = callback;
  36886. };
  36887. /**
  36888. * Play the sound
  36889. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36890. * @param offset (optional) Start the sound setting it at a specific time
  36891. */
  36892. Sound.prototype.play = function (time, offset) {
  36893. var _this = this;
  36894. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36895. try {
  36896. if (this._startOffset < 0) {
  36897. time = -this._startOffset;
  36898. this._startOffset = 0;
  36899. }
  36900. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36901. if (!this._soundSource || !this._streamingSource) {
  36902. if (this.spatialSound) {
  36903. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36904. if (this._isDirectional) {
  36905. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36906. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36907. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36908. if (this._connectedMesh) {
  36909. this._updateDirection();
  36910. }
  36911. else {
  36912. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36913. }
  36914. }
  36915. }
  36916. }
  36917. if (this._streaming) {
  36918. if (!this._streamingSource) {
  36919. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36920. this._htmlAudioElement.onended = function () { _this._onended(); };
  36921. this._htmlAudioElement.playbackRate = this._playbackRate;
  36922. }
  36923. this._streamingSource.disconnect();
  36924. this._streamingSource.connect(this._inputAudioNode);
  36925. this._htmlAudioElement.play();
  36926. }
  36927. else {
  36928. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36929. this._soundSource.buffer = this._audioBuffer;
  36930. this._soundSource.connect(this._inputAudioNode);
  36931. this._soundSource.loop = this.loop;
  36932. this._soundSource.playbackRate.value = this._playbackRate;
  36933. this._soundSource.onended = function () { _this._onended(); };
  36934. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36935. }
  36936. this._startTime = startTime;
  36937. this.isPlaying = true;
  36938. this.isPaused = false;
  36939. }
  36940. catch (ex) {
  36941. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36942. }
  36943. }
  36944. };
  36945. Sound.prototype._onended = function () {
  36946. this.isPlaying = false;
  36947. if (this.onended) {
  36948. this.onended();
  36949. }
  36950. };
  36951. /**
  36952. * Stop the sound
  36953. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36954. */
  36955. Sound.prototype.stop = function (time) {
  36956. if (this.isPlaying) {
  36957. if (this._streaming) {
  36958. this._htmlAudioElement.pause();
  36959. // Test needed for Firefox or it will generate an Invalid State Error
  36960. if (this._htmlAudioElement.currentTime > 0) {
  36961. this._htmlAudioElement.currentTime = 0;
  36962. }
  36963. }
  36964. else {
  36965. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36966. this._soundSource.stop(stopTime);
  36967. this._soundSource.onended = null;
  36968. if (!this.isPaused) {
  36969. this._startOffset = 0;
  36970. }
  36971. }
  36972. this.isPlaying = false;
  36973. }
  36974. };
  36975. Sound.prototype.pause = function () {
  36976. if (this.isPlaying) {
  36977. this.isPaused = true;
  36978. if (this._streaming) {
  36979. this._htmlAudioElement.pause();
  36980. }
  36981. else {
  36982. this.stop(0);
  36983. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36984. }
  36985. }
  36986. };
  36987. Sound.prototype.setVolume = function (newVolume, time) {
  36988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36989. if (time) {
  36990. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36991. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36992. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36993. }
  36994. else {
  36995. this._soundGain.gain.value = newVolume;
  36996. }
  36997. }
  36998. this._volume = newVolume;
  36999. };
  37000. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  37001. this._playbackRate = newPlaybackRate;
  37002. if (this.isPlaying) {
  37003. if (this._streaming) {
  37004. this._htmlAudioElement.playbackRate = this._playbackRate;
  37005. }
  37006. else {
  37007. this._soundSource.playbackRate.value = this._playbackRate;
  37008. }
  37009. }
  37010. };
  37011. Sound.prototype.getVolume = function () {
  37012. return this._volume;
  37013. };
  37014. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  37015. var _this = this;
  37016. if (this._connectedMesh) {
  37017. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37018. this._registerFunc = null;
  37019. }
  37020. this._connectedMesh = meshToConnectTo;
  37021. if (!this.spatialSound) {
  37022. this.spatialSound = true;
  37023. this._createSpatialParameters();
  37024. if (this.isPlaying && this.loop) {
  37025. this.stop();
  37026. this.play();
  37027. }
  37028. }
  37029. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  37030. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  37031. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  37032. };
  37033. Sound.prototype.detachFromMesh = function () {
  37034. if (this._connectedMesh) {
  37035. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37036. this._registerFunc = null;
  37037. this._connectedMesh = null;
  37038. }
  37039. };
  37040. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  37041. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  37042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  37043. this._updateDirection();
  37044. }
  37045. };
  37046. Sound.prototype.clone = function () {
  37047. var _this = this;
  37048. if (!this._streaming) {
  37049. var setBufferAndRun = function () {
  37050. if (_this._isReadyToPlay) {
  37051. clonedSound._audioBuffer = _this.getAudioBuffer();
  37052. clonedSound._isReadyToPlay = true;
  37053. if (clonedSound.autoplay) {
  37054. clonedSound.play();
  37055. }
  37056. }
  37057. else {
  37058. window.setTimeout(setBufferAndRun, 300);
  37059. }
  37060. };
  37061. var currentOptions = {
  37062. autoplay: this.autoplay, loop: this.loop,
  37063. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  37064. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  37065. refDistance: this.refDistance, distanceModel: this.distanceModel
  37066. };
  37067. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  37068. if (this.useCustomAttenuation) {
  37069. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  37070. }
  37071. clonedSound.setPosition(this._position);
  37072. clonedSound.setPlaybackRate(this._playbackRate);
  37073. setBufferAndRun();
  37074. return clonedSound;
  37075. }
  37076. else {
  37077. return null;
  37078. }
  37079. };
  37080. Sound.prototype.getAudioBuffer = function () {
  37081. return this._audioBuffer;
  37082. };
  37083. Sound.prototype.serialize = function () {
  37084. var serializationObject = {
  37085. name: this.name,
  37086. url: this.name,
  37087. autoplay: this.autoplay,
  37088. loop: this.loop,
  37089. volume: this._volume,
  37090. spatialSound: this.spatialSound,
  37091. maxDistance: this.maxDistance,
  37092. rolloffFactor: this.rolloffFactor,
  37093. refDistance: this.refDistance,
  37094. distanceModel: this.distanceModel,
  37095. playbackRate: this._playbackRate,
  37096. panningModel: this._panningModel,
  37097. soundTrackId: this.soundTrackId
  37098. };
  37099. if (this.spatialSound) {
  37100. if (this._connectedMesh)
  37101. serializationObject.connectedMeshId = this._connectedMesh.id;
  37102. serializationObject.position = this._position.asArray();
  37103. serializationObject.refDistance = this.refDistance;
  37104. serializationObject.distanceModel = this.distanceModel;
  37105. serializationObject.isDirectional = this._isDirectional;
  37106. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  37107. serializationObject.coneInnerAngle = this._coneInnerAngle;
  37108. serializationObject.coneOuterAngle = this._coneOuterAngle;
  37109. serializationObject.coneOuterGain = this._coneOuterGain;
  37110. }
  37111. return serializationObject;
  37112. };
  37113. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  37114. var soundName = parsedSound.name;
  37115. var soundUrl;
  37116. if (parsedSound.url) {
  37117. soundUrl = rootUrl + parsedSound.url;
  37118. }
  37119. else {
  37120. soundUrl = rootUrl + soundName;
  37121. }
  37122. var options = {
  37123. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  37124. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  37125. rolloffFactor: parsedSound.rolloffFactor,
  37126. refDistance: parsedSound.refDistance,
  37127. distanceModel: parsedSound.distanceModel,
  37128. playbackRate: parsedSound.playbackRate
  37129. };
  37130. var newSound;
  37131. if (!sourceSound) {
  37132. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  37133. scene._addPendingData(newSound);
  37134. }
  37135. else {
  37136. var setBufferAndRun = function () {
  37137. if (sourceSound._isReadyToPlay) {
  37138. newSound._audioBuffer = sourceSound.getAudioBuffer();
  37139. newSound._isReadyToPlay = true;
  37140. if (newSound.autoplay) {
  37141. newSound.play();
  37142. }
  37143. }
  37144. else {
  37145. window.setTimeout(setBufferAndRun, 300);
  37146. }
  37147. };
  37148. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  37149. setBufferAndRun();
  37150. }
  37151. if (parsedSound.position) {
  37152. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  37153. newSound.setPosition(soundPosition);
  37154. }
  37155. if (parsedSound.isDirectional) {
  37156. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  37157. if (parsedSound.localDirectionToMesh) {
  37158. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  37159. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  37160. }
  37161. }
  37162. if (parsedSound.connectedMeshId) {
  37163. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  37164. if (connectedMesh) {
  37165. newSound.attachToMesh(connectedMesh);
  37166. }
  37167. }
  37168. return newSound;
  37169. };
  37170. return Sound;
  37171. }());
  37172. BABYLON.Sound = Sound;
  37173. })(BABYLON || (BABYLON = {}));
  37174. var BABYLON;
  37175. (function (BABYLON) {
  37176. var SoundTrack = (function () {
  37177. function SoundTrack(scene, options) {
  37178. this.id = -1;
  37179. this._isMainTrack = false;
  37180. this._isInitialized = false;
  37181. this._scene = scene;
  37182. this.soundCollection = new Array();
  37183. this._options = options;
  37184. if (!this._isMainTrack) {
  37185. this._scene.soundTracks.push(this);
  37186. this.id = this._scene.soundTracks.length - 1;
  37187. }
  37188. }
  37189. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  37190. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37191. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  37192. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  37193. if (this._options) {
  37194. if (this._options.volume) {
  37195. this._outputAudioNode.gain.value = this._options.volume;
  37196. }
  37197. if (this._options.mainTrack) {
  37198. this._isMainTrack = this._options.mainTrack;
  37199. }
  37200. }
  37201. this._isInitialized = true;
  37202. }
  37203. };
  37204. SoundTrack.prototype.dispose = function () {
  37205. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37206. if (this._connectedAnalyser) {
  37207. this._connectedAnalyser.stopDebugCanvas();
  37208. }
  37209. while (this.soundCollection.length) {
  37210. this.soundCollection[0].dispose();
  37211. }
  37212. if (this._outputAudioNode) {
  37213. this._outputAudioNode.disconnect();
  37214. }
  37215. this._outputAudioNode = null;
  37216. }
  37217. };
  37218. SoundTrack.prototype.AddSound = function (sound) {
  37219. if (!this._isInitialized) {
  37220. this._initializeSoundTrackAudioGraph();
  37221. }
  37222. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37223. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  37224. }
  37225. if (sound.soundTrackId) {
  37226. if (sound.soundTrackId === -1) {
  37227. this._scene.mainSoundTrack.RemoveSound(sound);
  37228. }
  37229. else {
  37230. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  37231. }
  37232. }
  37233. this.soundCollection.push(sound);
  37234. sound.soundTrackId = this.id;
  37235. };
  37236. SoundTrack.prototype.RemoveSound = function (sound) {
  37237. var index = this.soundCollection.indexOf(sound);
  37238. if (index !== -1) {
  37239. this.soundCollection.splice(index, 1);
  37240. }
  37241. };
  37242. SoundTrack.prototype.setVolume = function (newVolume) {
  37243. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37244. this._outputAudioNode.gain.value = newVolume;
  37245. }
  37246. };
  37247. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  37248. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37249. for (var i = 0; i < this.soundCollection.length; i++) {
  37250. this.soundCollection[i].switchPanningModelToHRTF();
  37251. }
  37252. }
  37253. };
  37254. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  37255. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37256. for (var i = 0; i < this.soundCollection.length; i++) {
  37257. this.soundCollection[i].switchPanningModelToEqualPower();
  37258. }
  37259. }
  37260. };
  37261. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  37262. if (this._connectedAnalyser) {
  37263. this._connectedAnalyser.stopDebugCanvas();
  37264. }
  37265. this._connectedAnalyser = analyser;
  37266. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37267. this._outputAudioNode.disconnect();
  37268. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  37269. }
  37270. };
  37271. return SoundTrack;
  37272. }());
  37273. BABYLON.SoundTrack = SoundTrack;
  37274. })(BABYLON || (BABYLON = {}));
  37275. var BABYLON;
  37276. (function (BABYLON) {
  37277. /**
  37278. * Special Glow Blur post process only blurring the alpha channel
  37279. * It enforces keeping the most luminous color in the color channel.
  37280. */
  37281. var GlowBlurPostProcess = (function (_super) {
  37282. __extends(GlowBlurPostProcess, _super);
  37283. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  37284. var _this = this;
  37285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37286. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  37287. this.direction = direction;
  37288. this.blurWidth = blurWidth;
  37289. this.onApplyObservable.add(function (effect) {
  37290. effect.setFloat2("screenSize", _this.width, _this.height);
  37291. effect.setVector2("direction", _this.direction);
  37292. effect.setFloat("blurWidth", _this.blurWidth);
  37293. });
  37294. }
  37295. return GlowBlurPostProcess;
  37296. }(BABYLON.PostProcess));
  37297. /**
  37298. * The highlight layer Helps adding a glow effect around a mesh.
  37299. *
  37300. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  37301. * glowy meshes to your scene.
  37302. *
  37303. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  37304. */
  37305. var HighlightLayer = (function () {
  37306. /**
  37307. * Instantiates a new highlight Layer and references it to the scene..
  37308. * @param name The name of the layer
  37309. * @param scene The scene to use the layer in
  37310. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  37311. */
  37312. function HighlightLayer(name, scene, options) {
  37313. this._vertexBuffers = {};
  37314. this._mainTextureDesiredSize = { width: 0, height: 0 };
  37315. this._meshes = {};
  37316. this._maxSize = 0;
  37317. this._shouldRender = false;
  37318. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  37319. this._excludedMeshes = {};
  37320. /**
  37321. * Specifies whether or not the inner glow is ACTIVE in the layer.
  37322. */
  37323. this.innerGlow = true;
  37324. /**
  37325. * Specifies whether or not the outer glow is ACTIVE in the layer.
  37326. */
  37327. this.outerGlow = true;
  37328. /**
  37329. * An event triggered when the highlight layer has been disposed.
  37330. * @type {BABYLON.Observable}
  37331. */
  37332. this.onDisposeObservable = new BABYLON.Observable();
  37333. /**
  37334. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  37335. * @type {BABYLON.Observable}
  37336. */
  37337. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  37338. /**
  37339. * An event triggered when the highlight layer is being blurred.
  37340. * @type {BABYLON.Observable}
  37341. */
  37342. this.onBeforeBlurObservable = new BABYLON.Observable();
  37343. /**
  37344. * An event triggered when the highlight layer has been blurred.
  37345. * @type {BABYLON.Observable}
  37346. */
  37347. this.onAfterBlurObservable = new BABYLON.Observable();
  37348. /**
  37349. * An event triggered when the glowing blurred texture is being merged in the scene.
  37350. * @type {BABYLON.Observable}
  37351. */
  37352. this.onBeforeComposeObservable = new BABYLON.Observable();
  37353. /**
  37354. * An event triggered when the glowing blurred texture has been merged in the scene.
  37355. * @type {BABYLON.Observable}
  37356. */
  37357. this.onAfterComposeObservable = new BABYLON.Observable();
  37358. /**
  37359. * An event triggered when the highlight layer changes its size.
  37360. * @type {BABYLON.Observable}
  37361. */
  37362. this.onSizeChangedObservable = new BABYLON.Observable();
  37363. this._scene = scene;
  37364. var engine = scene.getEngine();
  37365. this._engine = engine;
  37366. this._maxSize = this._engine.getCaps().maxTextureSize;
  37367. this._scene.highlightLayers.push(this);
  37368. // Warn on stencil.
  37369. if (!this._engine.isStencilEnable) {
  37370. 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 }");
  37371. }
  37372. // Adapt options
  37373. this._options = options || {
  37374. mainTextureRatio: 0.25,
  37375. blurTextureSizeRatio: 0.5,
  37376. blurHorizontalSize: 1,
  37377. blurVerticalSize: 1,
  37378. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  37379. };
  37380. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  37381. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  37382. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  37383. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  37384. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  37385. // VBO
  37386. var vertices = [];
  37387. vertices.push(1, 1);
  37388. vertices.push(-1, 1);
  37389. vertices.push(-1, -1);
  37390. vertices.push(1, -1);
  37391. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37392. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  37393. // Indices
  37394. var indices = [];
  37395. indices.push(0);
  37396. indices.push(1);
  37397. indices.push(2);
  37398. indices.push(0);
  37399. indices.push(2);
  37400. indices.push(3);
  37401. this._indexBuffer = engine.createIndexBuffer(indices);
  37402. // Effect
  37403. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  37404. // Render target
  37405. this.setMainTextureSize();
  37406. // Create Textures and post processes
  37407. this.createTextureAndPostProcesses();
  37408. }
  37409. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  37410. /**
  37411. * Gets the horizontal size of the blur.
  37412. */
  37413. get: function () {
  37414. return this._horizontalBlurPostprocess.blurWidth;
  37415. },
  37416. /**
  37417. * Specifies the horizontal size of the blur.
  37418. */
  37419. set: function (value) {
  37420. this._horizontalBlurPostprocess.blurWidth = value;
  37421. },
  37422. enumerable: true,
  37423. configurable: true
  37424. });
  37425. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  37426. /**
  37427. * Gets the vertical size of the blur.
  37428. */
  37429. get: function () {
  37430. return this._verticalBlurPostprocess.blurWidth;
  37431. },
  37432. /**
  37433. * Specifies the vertical size of the blur.
  37434. */
  37435. set: function (value) {
  37436. this._verticalBlurPostprocess.blurWidth = value;
  37437. },
  37438. enumerable: true,
  37439. configurable: true
  37440. });
  37441. Object.defineProperty(HighlightLayer.prototype, "camera", {
  37442. /**
  37443. * Gets the camera attached to the layer.
  37444. */
  37445. get: function () {
  37446. return this._options.camera;
  37447. },
  37448. enumerable: true,
  37449. configurable: true
  37450. });
  37451. /**
  37452. * Creates the render target textures and post processes used in the highlight layer.
  37453. */
  37454. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  37455. var _this = this;
  37456. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  37457. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  37458. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  37459. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  37460. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  37461. width: this._mainTextureDesiredSize.width,
  37462. height: this._mainTextureDesiredSize.height
  37463. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37464. this._mainTexture.activeCamera = this._options.camera;
  37465. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37466. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37467. this._mainTexture.anisotropicFilteringLevel = 1;
  37468. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37469. this._mainTexture.renderParticles = false;
  37470. this._mainTexture.renderList = null;
  37471. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  37472. width: blurTextureWidth,
  37473. height: blurTextureHeight
  37474. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37475. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37476. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37477. this._blurTexture.anisotropicFilteringLevel = 16;
  37478. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  37479. this._blurTexture.renderParticles = false;
  37480. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37481. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  37482. effect.setTexture("textureSampler", _this._mainTexture);
  37483. });
  37484. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37485. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  37486. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37487. });
  37488. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37489. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  37490. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37491. });
  37492. this._mainTexture.onAfterUnbindObservable.add(function () {
  37493. _this.onBeforeBlurObservable.notifyObservers(_this);
  37494. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  37495. _this.onAfterBlurObservable.notifyObservers(_this);
  37496. });
  37497. // Custom render function
  37498. var renderSubMesh = function (subMesh) {
  37499. var mesh = subMesh.getRenderingMesh();
  37500. var scene = _this._scene;
  37501. var engine = scene.getEngine();
  37502. // Culling
  37503. engine.setState(subMesh.getMaterial().backFaceCulling);
  37504. // Managing instances
  37505. var batch = mesh._getInstancesRenderList(subMesh._id);
  37506. if (batch.mustReturn) {
  37507. return;
  37508. }
  37509. // Excluded Mesh
  37510. if (_this._excludedMeshes[mesh.id]) {
  37511. return;
  37512. }
  37513. ;
  37514. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37515. var highlightLayerMesh = _this._meshes[mesh.id];
  37516. var material = subMesh.getMaterial();
  37517. var emissiveTexture = null;
  37518. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  37519. emissiveTexture = material.emissiveTexture;
  37520. }
  37521. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  37522. engine.enableEffect(_this._glowMapGenerationEffect);
  37523. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  37524. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  37525. if (highlightLayerMesh) {
  37526. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  37527. }
  37528. else {
  37529. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  37530. }
  37531. // Alpha test
  37532. if (material && material.needAlphaTesting()) {
  37533. var alphaTexture = material.getAlphaTestTexture();
  37534. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  37535. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37536. }
  37537. // Glow emissive only
  37538. if (emissiveTexture) {
  37539. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  37540. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  37541. }
  37542. // Bones
  37543. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37544. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37545. }
  37546. // Draw
  37547. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  37548. }
  37549. else {
  37550. // Need to reset refresh rate of the shadowMap
  37551. _this._mainTexture.resetRefreshCounter();
  37552. }
  37553. };
  37554. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  37555. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  37556. var index;
  37557. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37558. renderSubMesh(opaqueSubMeshes.data[index]);
  37559. }
  37560. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37561. renderSubMesh(alphaTestSubMeshes.data[index]);
  37562. }
  37563. for (index = 0; index < transparentSubMeshes.length; index++) {
  37564. renderSubMesh(transparentSubMeshes.data[index]);
  37565. }
  37566. };
  37567. this._mainTexture.onClearObservable.add(function (engine) {
  37568. engine.clear(HighlightLayer.neutralColor, true, true, true);
  37569. });
  37570. };
  37571. /**
  37572. * Checks for the readiness of the element composing the layer.
  37573. * @param subMesh the mesh to check for
  37574. * @param useInstances specify wether or not to use instances to render the mesh
  37575. * @param emissiveTexture the associated emissive texture used to generate the glow
  37576. * @return true if ready otherwise, false
  37577. */
  37578. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  37579. if (!subMesh.getMaterial().isReady()) {
  37580. return false;
  37581. }
  37582. var defines = [];
  37583. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37584. var mesh = subMesh.getMesh();
  37585. var material = subMesh.getMaterial();
  37586. var uv1 = false;
  37587. var uv2 = false;
  37588. // Alpha test
  37589. if (material && material.needAlphaTesting()) {
  37590. var alphaTexture = material.getAlphaTestTexture();
  37591. if (alphaTexture) {
  37592. defines.push("#define ALPHATEST");
  37593. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37594. alphaTexture.coordinatesIndex === 1) {
  37595. defines.push("#define DIFFUSEUV2");
  37596. uv2 = true;
  37597. }
  37598. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37599. defines.push("#define DIFFUSEUV1");
  37600. uv1 = true;
  37601. }
  37602. }
  37603. }
  37604. // Emissive
  37605. if (emissiveTexture) {
  37606. defines.push("#define EMISSIVE");
  37607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37608. emissiveTexture.coordinatesIndex === 1) {
  37609. defines.push("#define EMISSIVEUV2");
  37610. uv2 = true;
  37611. }
  37612. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37613. defines.push("#define EMISSIVEUV1");
  37614. uv1 = true;
  37615. }
  37616. }
  37617. if (uv1) {
  37618. attribs.push(BABYLON.VertexBuffer.UVKind);
  37619. defines.push("#define UV1");
  37620. }
  37621. if (uv2) {
  37622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37623. defines.push("#define UV2");
  37624. }
  37625. // Bones
  37626. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37627. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37628. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37629. if (mesh.numBoneInfluencers > 4) {
  37630. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37631. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37632. }
  37633. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37634. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37635. }
  37636. else {
  37637. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37638. }
  37639. // Instances
  37640. if (useInstances) {
  37641. defines.push("#define INSTANCES");
  37642. attribs.push("world0");
  37643. attribs.push("world1");
  37644. attribs.push("world2");
  37645. attribs.push("world3");
  37646. }
  37647. // Get correct effect
  37648. var join = defines.join("\n");
  37649. if (this._cachedDefines !== join) {
  37650. this._cachedDefines = join;
  37651. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37652. }
  37653. return this._glowMapGenerationEffect.isReady();
  37654. };
  37655. /**
  37656. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37657. */
  37658. HighlightLayer.prototype.render = function () {
  37659. var currentEffect = this._glowMapMergeEffect;
  37660. // Check
  37661. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37662. return;
  37663. var engine = this._scene.getEngine();
  37664. this.onBeforeComposeObservable.notifyObservers(this);
  37665. // Render
  37666. engine.enableEffect(currentEffect);
  37667. engine.setState(false);
  37668. // Cache
  37669. var previousStencilBuffer = engine.getStencilBuffer();
  37670. var previousStencilFunction = engine.getStencilFunction();
  37671. var previousStencilMask = engine.getStencilMask();
  37672. var previousAlphaMode = engine.getAlphaMode();
  37673. // Texture
  37674. currentEffect.setTexture("textureSampler", this._blurTexture);
  37675. // VBOs
  37676. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37677. // Draw order
  37678. engine.setAlphaMode(this._options.alphaBlendingMode);
  37679. engine.setStencilMask(0x00);
  37680. engine.setStencilBuffer(true);
  37681. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37682. if (this.outerGlow) {
  37683. currentEffect.setFloat("offset", 0);
  37684. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37685. engine.draw(true, 0, 6);
  37686. }
  37687. if (this.innerGlow) {
  37688. currentEffect.setFloat("offset", 1);
  37689. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37690. engine.draw(true, 0, 6);
  37691. }
  37692. // Restore Cache
  37693. engine.setStencilFunction(previousStencilFunction);
  37694. engine.setStencilMask(previousStencilMask);
  37695. engine.setAlphaMode(previousAlphaMode);
  37696. engine.setStencilBuffer(previousStencilBuffer);
  37697. this.onAfterComposeObservable.notifyObservers(this);
  37698. // Handle size changes.
  37699. var size = this._mainTexture.getSize();
  37700. this.setMainTextureSize();
  37701. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37702. // Recreate RTT and post processes on size change.
  37703. this.onSizeChangedObservable.notifyObservers(this);
  37704. this.disposeTextureAndPostProcesses();
  37705. this.createTextureAndPostProcesses();
  37706. }
  37707. };
  37708. /**
  37709. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  37710. * @param mesh The mesh to exclude from the highlight layer
  37711. */
  37712. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  37713. var meshExcluded = this._excludedMeshes[mesh.id];
  37714. if (!meshExcluded) {
  37715. this._excludedMeshes[mesh.id] = {
  37716. mesh: mesh,
  37717. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  37718. mesh.getEngine().setStencilBuffer(false);
  37719. }),
  37720. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  37721. mesh.getEngine().setStencilBuffer(true);
  37722. }),
  37723. };
  37724. }
  37725. };
  37726. /**
  37727. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  37728. * @param mesh The mesh to highlight
  37729. */
  37730. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  37731. var meshExcluded = this._excludedMeshes[mesh.id];
  37732. if (meshExcluded) {
  37733. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  37734. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  37735. }
  37736. this._excludedMeshes[mesh.id] = undefined;
  37737. };
  37738. /**
  37739. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37740. * @param mesh The mesh to highlight
  37741. * @param color The color of the highlight
  37742. * @param glowEmissiveOnly Extract the glow from the emissive texture
  37743. */
  37744. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  37745. var _this = this;
  37746. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  37747. var meshHighlight = this._meshes[mesh.id];
  37748. if (meshHighlight) {
  37749. meshHighlight.color = color;
  37750. }
  37751. else {
  37752. this._meshes[mesh.id] = {
  37753. mesh: mesh,
  37754. color: color,
  37755. // Lambda required for capture due to Observable this context
  37756. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37757. if (_this._excludedMeshes[mesh.id]) {
  37758. _this.defaultStencilReference(mesh);
  37759. }
  37760. else {
  37761. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37762. }
  37763. }),
  37764. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  37765. glowEmissiveOnly: glowEmissiveOnly
  37766. };
  37767. }
  37768. this._shouldRender = true;
  37769. };
  37770. /**
  37771. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37772. * @param mesh The mesh to highlight
  37773. */
  37774. HighlightLayer.prototype.removeMesh = function (mesh) {
  37775. var meshHighlight = this._meshes[mesh.id];
  37776. if (meshHighlight) {
  37777. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37778. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37779. }
  37780. this._meshes[mesh.id] = undefined;
  37781. this._shouldRender = false;
  37782. for (var meshHighlightToCheck in this._meshes) {
  37783. if (meshHighlightToCheck) {
  37784. this._shouldRender = true;
  37785. break;
  37786. }
  37787. }
  37788. };
  37789. /**
  37790. * Returns true if the layer contains information to display, otherwise false.
  37791. */
  37792. HighlightLayer.prototype.shouldRender = function () {
  37793. return this._shouldRender;
  37794. };
  37795. /**
  37796. * Sets the main texture desired size which is the closest power of two
  37797. * of the engine canvas size.
  37798. */
  37799. HighlightLayer.prototype.setMainTextureSize = function () {
  37800. if (this._options.mainTextureFixedSize) {
  37801. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  37802. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  37803. }
  37804. else {
  37805. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37806. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37807. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37808. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37809. }
  37810. };
  37811. /**
  37812. * Force the stencil to the normal expected value for none glowing parts
  37813. */
  37814. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37815. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37816. };
  37817. /**
  37818. * Dispose only the render target textures and post process.
  37819. */
  37820. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37821. this._blurTexture.dispose();
  37822. this._mainTexture.dispose();
  37823. this._downSamplePostprocess.dispose();
  37824. this._horizontalBlurPostprocess.dispose();
  37825. this._verticalBlurPostprocess.dispose();
  37826. };
  37827. /**
  37828. * Dispose the highlight layer and free resources.
  37829. */
  37830. HighlightLayer.prototype.dispose = function () {
  37831. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37832. if (vertexBuffer) {
  37833. vertexBuffer.dispose();
  37834. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37835. }
  37836. if (this._indexBuffer) {
  37837. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37838. this._indexBuffer = null;
  37839. }
  37840. // Clean textures and post processes
  37841. this.disposeTextureAndPostProcesses();
  37842. // Clean mesh references
  37843. for (var id in this._meshes) {
  37844. var meshHighlight = this._meshes[id];
  37845. if (meshHighlight && meshHighlight.mesh) {
  37846. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37847. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37848. }
  37849. }
  37850. this._meshes = null;
  37851. for (var id in this._excludedMeshes) {
  37852. var meshHighlight = this._excludedMeshes[id];
  37853. if (meshHighlight) {
  37854. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  37855. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  37856. }
  37857. }
  37858. this._excludedMeshes = null;
  37859. // Remove from scene
  37860. var index = this._scene.highlightLayers.indexOf(this, 0);
  37861. if (index > -1) {
  37862. this._scene.highlightLayers.splice(index, 1);
  37863. }
  37864. // Callback
  37865. this.onDisposeObservable.notifyObservers(this);
  37866. this.onDisposeObservable.clear();
  37867. this.onBeforeRenderMainTextureObservable.clear();
  37868. this.onBeforeBlurObservable.clear();
  37869. this.onBeforeComposeObservable.clear();
  37870. this.onAfterComposeObservable.clear();
  37871. this.onSizeChangedObservable.clear();
  37872. };
  37873. /**
  37874. * The neutral color used during the preparation of the glow effect.
  37875. * This is black by default as the blend operation is a blend operation.
  37876. */
  37877. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37878. /**
  37879. * Stencil value used for glowing meshes.
  37880. */
  37881. HighlightLayer.glowingMeshStencilReference = 0x02;
  37882. /**
  37883. * Stencil value used for the other meshes in the scene.
  37884. */
  37885. HighlightLayer.normalMeshStencilReference = 0x01;
  37886. return HighlightLayer;
  37887. }());
  37888. BABYLON.HighlightLayer = HighlightLayer;
  37889. })(BABYLON || (BABYLON = {}));
  37890. var BABYLON;
  37891. (function (BABYLON) {
  37892. var SIMDVector3 = (function () {
  37893. function SIMDVector3() {
  37894. }
  37895. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37896. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37897. };
  37898. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37899. var m = transformation.m;
  37900. var m0 = SIMD.Float32x4.load(m, 0);
  37901. var m1 = SIMD.Float32x4.load(m, 4);
  37902. var m2 = SIMD.Float32x4.load(m, 8);
  37903. var m3 = SIMD.Float32x4.load(m, 12);
  37904. 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));
  37905. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37906. result.x = SIMD.Float32x4.extractLane(r, 0);
  37907. result.y = SIMD.Float32x4.extractLane(r, 1);
  37908. result.z = SIMD.Float32x4.extractLane(r, 2);
  37909. };
  37910. return SIMDVector3;
  37911. }());
  37912. var SIMDMatrix = (function () {
  37913. function SIMDMatrix() {
  37914. }
  37915. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37916. var tm = this.m;
  37917. var om = other.m;
  37918. var m0 = SIMD.Float32x4.load(om, 0);
  37919. var m1 = SIMD.Float32x4.load(om, 4);
  37920. var m2 = SIMD.Float32x4.load(om, 8);
  37921. var m3 = SIMD.Float32x4.load(om, 12);
  37922. for (var i = 0; i < 16; i += 4) {
  37923. 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)))));
  37924. }
  37925. return this;
  37926. };
  37927. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37928. var src = this.m;
  37929. var dest = other.m;
  37930. // Load the 4 rows
  37931. var src0 = SIMD.Float32x4.load(src, 0);
  37932. var src1 = SIMD.Float32x4.load(src, 4);
  37933. var src2 = SIMD.Float32x4.load(src, 8);
  37934. var src3 = SIMD.Float32x4.load(src, 12);
  37935. // Transpose the source matrix. Sort of. Not a true transpose operation
  37936. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37937. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37938. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37939. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37940. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37941. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37942. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37943. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37944. // This is a true transposition, but it will lead to an incorrect result
  37945. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37946. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37947. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37948. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37949. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37950. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37951. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37952. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37953. // ----
  37954. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37955. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37956. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37957. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37958. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37959. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37960. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37961. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37962. // ----
  37963. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37964. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37965. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37966. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37967. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37968. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37969. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37970. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37971. // ----
  37972. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37973. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37974. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37975. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37976. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37977. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37978. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37979. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37980. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37981. // ----
  37982. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37983. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37984. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37985. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37986. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37987. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37988. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37989. // ----
  37990. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37991. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37992. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37993. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37994. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37995. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37996. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37997. // ----
  37998. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37999. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38000. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  38001. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  38002. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38003. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  38004. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  38005. // Compute determinant
  38006. var det = SIMD.Float32x4.mul(row0, minor0);
  38007. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  38008. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  38009. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  38010. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  38011. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  38012. // These shuffles aren't necessary if the faulty transposition is done
  38013. // up at the top of this function.
  38014. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  38015. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  38016. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  38017. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  38018. // Compute final values by multiplying with 1/det
  38019. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  38020. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  38021. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  38022. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  38023. return this;
  38024. };
  38025. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  38026. var out = result.m;
  38027. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  38028. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  38029. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  38030. // cc.kmVec3Subtract(f, pCenter, pEye);
  38031. var f = SIMD.Float32x4.sub(center, eye);
  38032. // cc.kmVec3Normalize(f, f);
  38033. var tmp = SIMD.Float32x4.mul(f, f);
  38034. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38035. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38036. // cc.kmVec3Assign(up, pUp);
  38037. // cc.kmVec3Normalize(up, up);
  38038. tmp = SIMD.Float32x4.mul(up, up);
  38039. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38040. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38041. // cc.kmVec3Cross(s, f, up);
  38042. 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)));
  38043. // cc.kmVec3Normalize(s, s);
  38044. tmp = SIMD.Float32x4.mul(s, s);
  38045. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38046. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38047. // cc.kmVec3Cross(u, s, f);
  38048. 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)));
  38049. // cc.kmVec3Normalize(s, s);
  38050. tmp = SIMD.Float32x4.mul(s, s);
  38051. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38052. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38053. var zero = SIMD.Float32x4.splat(0.0);
  38054. s = SIMD.Float32x4.neg(s);
  38055. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  38056. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  38057. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  38058. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  38059. 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);
  38060. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  38061. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  38062. 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)))));
  38063. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  38064. 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)))));
  38065. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  38066. 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)))));
  38067. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  38068. 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)))));
  38069. };
  38070. return SIMDMatrix;
  38071. }());
  38072. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  38073. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  38074. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  38075. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  38076. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  38077. var SIMDHelper = (function () {
  38078. function SIMDHelper() {
  38079. }
  38080. Object.defineProperty(SIMDHelper, "IsEnabled", {
  38081. get: function () {
  38082. return SIMDHelper._isEnabled;
  38083. },
  38084. enumerable: true,
  38085. configurable: true
  38086. });
  38087. SIMDHelper.DisableSIMD = function () {
  38088. // Replace functions
  38089. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  38090. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  38091. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  38092. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  38093. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  38094. SIMDHelper._isEnabled = false;
  38095. };
  38096. SIMDHelper.EnableSIMD = function () {
  38097. if (self.SIMD === undefined) {
  38098. return;
  38099. }
  38100. // check if polyfills needed
  38101. if (!self.Math.fround) {
  38102. self.Math.fround = (function (array) { return function (x) {
  38103. return array[0] = x, array[0];
  38104. }; })(new Float32Array(1));
  38105. }
  38106. if (!self.Math.imul) {
  38107. self.Math.imul = function (a, b) {
  38108. var ah = (a >>> 16) & 0xffff;
  38109. var al = a & 0xffff;
  38110. var bh = (b >>> 16) & 0xffff;
  38111. var bl = b & 0xffff;
  38112. // the shift by 0 fixes the sign on the high part
  38113. // the final |0 converts the unsigned value into a signed value
  38114. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  38115. };
  38116. }
  38117. // Replace functions
  38118. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  38119. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  38120. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  38121. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  38122. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  38123. SIMDHelper._isEnabled = true;
  38124. };
  38125. SIMDHelper._isEnabled = false;
  38126. return SIMDHelper;
  38127. }());
  38128. BABYLON.SIMDHelper = SIMDHelper;
  38129. })(BABYLON || (BABYLON = {}));
  38130. var BABYLON;
  38131. (function (BABYLON) {
  38132. /**
  38133. * This class describe a rectangle that were added to the map.
  38134. * You have access to its coordinates either in pixel or normalized (UV)
  38135. */
  38136. var PackedRect = (function () {
  38137. function PackedRect(root, parent, pos, size) {
  38138. this._pos = pos;
  38139. this._size = size;
  38140. this._root = root;
  38141. this._parent = parent;
  38142. this._contentSize = null;
  38143. this._bottomNode = null;
  38144. this._leftNode = null;
  38145. this._initialSize = null;
  38146. this._rightNode = null;
  38147. }
  38148. Object.defineProperty(PackedRect.prototype, "pos", {
  38149. /**
  38150. * @returns the position of this node into the map
  38151. */
  38152. get: function () {
  38153. return this._pos;
  38154. },
  38155. enumerable: true,
  38156. configurable: true
  38157. });
  38158. Object.defineProperty(PackedRect.prototype, "contentSize", {
  38159. /**
  38160. * @returns the size of the rectangle this node handles
  38161. */
  38162. get: function () {
  38163. return this._contentSize;
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. Object.defineProperty(PackedRect.prototype, "UVs", {
  38169. /**
  38170. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  38171. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  38172. */
  38173. get: function () {
  38174. return this.getUVsForCustomSize(this._root._size);
  38175. },
  38176. enumerable: true,
  38177. configurable: true
  38178. });
  38179. /**
  38180. * 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.
  38181. * This method will return the UVs for this part by given the custom size of what you really use
  38182. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  38183. */
  38184. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  38185. var mainWidth = this._root._size.width;
  38186. var mainHeight = this._root._size.height;
  38187. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  38188. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  38189. var uvs = new Array();
  38190. uvs.push(topLeft);
  38191. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  38192. uvs.push(rightBottom);
  38193. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  38194. return uvs;
  38195. };
  38196. /**
  38197. * Free this rectangle from the map.
  38198. * Call this method when you no longer need the rectangle to be in the map.
  38199. */
  38200. PackedRect.prototype.freeContent = function () {
  38201. if (!this.contentSize) {
  38202. return;
  38203. }
  38204. this._contentSize = null;
  38205. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  38206. this.attemptDefrag();
  38207. };
  38208. Object.defineProperty(PackedRect.prototype, "isUsed", {
  38209. get: function () {
  38210. return this._contentSize != null || this._leftNode != null;
  38211. },
  38212. enumerable: true,
  38213. configurable: true
  38214. });
  38215. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  38216. var node = this.findNode(contentSize);
  38217. // Not enough space...
  38218. if (!node) {
  38219. return null;
  38220. }
  38221. node.splitNode(contentSize);
  38222. return node;
  38223. };
  38224. PackedRect.prototype.findNode = function (size) {
  38225. var resNode = null;
  38226. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  38227. if (this.isUsed) {
  38228. if (this._leftNode) {
  38229. resNode = this._leftNode.findNode(size);
  38230. }
  38231. if (!resNode && this._rightNode) {
  38232. resNode = this._rightNode.findNode(size);
  38233. }
  38234. if (!resNode && this._bottomNode) {
  38235. resNode = this._bottomNode.findNode(size);
  38236. }
  38237. }
  38238. else if (this._initialSize) {
  38239. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  38240. resNode = this;
  38241. }
  38242. else {
  38243. return null;
  38244. }
  38245. }
  38246. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  38247. resNode = this;
  38248. }
  38249. return resNode;
  38250. };
  38251. PackedRect.prototype.splitNode = function (contentSize) {
  38252. // 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)
  38253. if (!this._contentSize && this._initialSize) {
  38254. this._contentSize = contentSize.clone();
  38255. 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));
  38256. return this._leftNode.splitNode(contentSize);
  38257. }
  38258. else {
  38259. this._contentSize = contentSize.clone();
  38260. this._initialSize = contentSize.clone();
  38261. if (contentSize.width !== this._size.width) {
  38262. 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));
  38263. }
  38264. if (contentSize.height !== this._size.height) {
  38265. 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));
  38266. }
  38267. return this;
  38268. }
  38269. };
  38270. PackedRect.prototype.attemptDefrag = function () {
  38271. if (!this.isUsed && this.isRecursiveFree) {
  38272. this.clearNode();
  38273. if (this._parent) {
  38274. this._parent.attemptDefrag();
  38275. }
  38276. }
  38277. };
  38278. PackedRect.prototype.clearNode = function () {
  38279. this._initialSize = null;
  38280. this._rightNode = null;
  38281. this._bottomNode = null;
  38282. };
  38283. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  38284. get: function () {
  38285. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  38286. },
  38287. enumerable: true,
  38288. configurable: true
  38289. });
  38290. PackedRect.prototype.evalFreeSize = function (size) {
  38291. var levelSize = 0;
  38292. if (!this.isUsed) {
  38293. if (this._initialSize) {
  38294. levelSize = this._initialSize.surface;
  38295. }
  38296. else {
  38297. levelSize = this._size.surface;
  38298. }
  38299. }
  38300. if (this._rightNode) {
  38301. levelSize += this._rightNode.evalFreeSize(0);
  38302. }
  38303. if (this._bottomNode) {
  38304. levelSize += this._bottomNode.evalFreeSize(0);
  38305. }
  38306. return levelSize + size;
  38307. };
  38308. return PackedRect;
  38309. }());
  38310. BABYLON.PackedRect = PackedRect;
  38311. /**
  38312. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  38313. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  38314. * 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.
  38315. */
  38316. var RectPackingMap = (function (_super) {
  38317. __extends(RectPackingMap, _super);
  38318. /**
  38319. * Create an instance of the object with a dimension using the given size
  38320. * @param size The dimension of the rectangle that will contain all the sub ones.
  38321. */
  38322. function RectPackingMap(size) {
  38323. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  38324. this._root = this;
  38325. }
  38326. /**
  38327. * Add a rectangle, finding the best location to store it into the map
  38328. * @param size the dimension of the rectangle to store
  38329. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  38330. */
  38331. RectPackingMap.prototype.addRect = function (size) {
  38332. var node = this.findAndSplitNode(size);
  38333. return node;
  38334. };
  38335. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  38336. /**
  38337. * Return the current space free normalized between [0;1]
  38338. * @returns {}
  38339. */
  38340. get: function () {
  38341. var freeSize = 0;
  38342. freeSize = this.evalFreeSize(freeSize);
  38343. return freeSize / (this._size.width * this._size.height);
  38344. },
  38345. enumerable: true,
  38346. configurable: true
  38347. });
  38348. return RectPackingMap;
  38349. }(PackedRect));
  38350. BABYLON.RectPackingMap = RectPackingMap;
  38351. })(BABYLON || (BABYLON = {}));
  38352. var BABYLON;
  38353. (function (BABYLON) {
  38354. var DynamicFloatArrayElementInfo = (function () {
  38355. function DynamicFloatArrayElementInfo() {
  38356. }
  38357. return DynamicFloatArrayElementInfo;
  38358. }());
  38359. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  38360. /**
  38361. * 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.
  38362. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  38363. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  38364. * 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.
  38365. * 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.
  38366. * 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".
  38367. */
  38368. var DynamicFloatArray = (function () {
  38369. /**
  38370. * Construct an instance of the dynamic float array
  38371. * @param stride size of one element in float (i.e. not bytes!)
  38372. * @param initialElementCount the number of available entries at construction
  38373. */
  38374. function DynamicFloatArray(stride, initialElementCount) {
  38375. this.compareValueOffset = null;
  38376. this.sortingAscending = true;
  38377. this._stride = stride;
  38378. this.buffer = new Float32Array(stride * initialElementCount);
  38379. this._lastUsed = 0;
  38380. this._firstFree = 0;
  38381. this._allEntries = new Array(initialElementCount);
  38382. this._freeEntries = new Array(initialElementCount);
  38383. for (var i = 0; i < initialElementCount; i++) {
  38384. var element = new DynamicFloatArrayElementInfo();
  38385. element.offset = i * stride;
  38386. this._allEntries[i] = element;
  38387. this._freeEntries[initialElementCount - i - 1] = element;
  38388. }
  38389. }
  38390. /**
  38391. * Allocate an element in the array.
  38392. * @return the element info instance that contains the offset into the main buffer of the element's location.
  38393. * Beware, this offset may change when you call pack()
  38394. */
  38395. DynamicFloatArray.prototype.allocElement = function () {
  38396. if (this._freeEntries.length === 0) {
  38397. this._growBuffer();
  38398. }
  38399. var el = this._freeEntries.pop();
  38400. this._lastUsed = Math.max(el.offset, this._lastUsed);
  38401. if (el.offset === this._firstFree) {
  38402. if (this._freeEntries.length > 0) {
  38403. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  38404. }
  38405. else {
  38406. this._firstFree += this._stride;
  38407. }
  38408. }
  38409. return el;
  38410. };
  38411. /**
  38412. * Free the element corresponding to the given element info
  38413. * @param elInfo the element that describe the allocated element
  38414. */
  38415. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  38416. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  38417. this._freeEntries.push(elInfo);
  38418. };
  38419. /**
  38420. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  38421. * 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().
  38422. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  38423. */
  38424. DynamicFloatArray.prototype.pack = function () {
  38425. // no free slot? no need to pack
  38426. if (this._freeEntries.length === 0) {
  38427. return this.buffer;
  38428. }
  38429. // If the buffer is already packed the last used will always be lower than the first free
  38430. // 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.
  38431. if (this._lastUsed < this._firstFree) {
  38432. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  38433. return elementsBuffer_1;
  38434. }
  38435. var s = this._stride;
  38436. // 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
  38437. var lastFree = new DynamicFloatArrayElementInfo();
  38438. lastFree.offset = this.totalElementCount * s;
  38439. this._freeEntries.push(lastFree);
  38440. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  38441. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38442. var firstFreeSlotOffset = sortedFree[0].offset;
  38443. var freeZoneSize = 1;
  38444. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  38445. var prevOffset = sortedFree[0].offset;
  38446. for (var i = 1; i < sortedFree.length; i++) {
  38447. // 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
  38448. if (firstFreeSlotOffset >= occupiedZoneSize) {
  38449. break;
  38450. }
  38451. var curFree = sortedFree[i];
  38452. var curOffset = curFree.offset;
  38453. // Compute the distance between this offset and the previous
  38454. var distance = curOffset - prevOffset;
  38455. // If the distance is the stride size, they are adjacent, it good, move to the next
  38456. if (distance === s) {
  38457. // Free zone is one element bigger
  38458. ++freeZoneSize;
  38459. // as we're about to iterate to the next, the cur becomes the previous...
  38460. prevOffset = curOffset;
  38461. continue;
  38462. }
  38463. // Distance is bigger, which means there's x element between the previous free and this one
  38464. var usedRange = (distance / s) - 1;
  38465. // Two cases the free zone is smaller than the data to move or bigger
  38466. // Copy what can fit in the free zone
  38467. var curMoveOffset = curOffset - s;
  38468. var copyCount = Math.min(freeZoneSize, usedRange);
  38469. for (var j = 0; j < copyCount; j++) {
  38470. var freeI = firstFreeSlotOffset / s;
  38471. var curI = curMoveOffset / s;
  38472. var moveEl = sortedAll[curI];
  38473. this._moveElement(moveEl, firstFreeSlotOffset);
  38474. var replacedEl = sortedAll[freeI];
  38475. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  38476. replacedEl.offset = curMoveOffset;
  38477. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  38478. sortedAll[freeI] = moveEl;
  38479. sortedAll[curI] = replacedEl;
  38480. curMoveOffset -= s;
  38481. firstFreeSlotOffset += s;
  38482. }
  38483. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  38484. if (freeZoneSize <= usedRange) {
  38485. firstFreeSlotOffset = curMoveOffset + s;
  38486. freeZoneSize = 1 + copyCount;
  38487. }
  38488. else {
  38489. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  38490. }
  38491. // as we're about to iterate to the next, the cur becomes the previous...
  38492. prevOffset = curOffset;
  38493. }
  38494. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  38495. this._lastUsed = firstFreeSlotOffset - s;
  38496. this._firstFree = firstFreeSlotOffset;
  38497. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  38498. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  38499. this._allEntries = sortedAll;
  38500. return elementsBuffer;
  38501. };
  38502. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  38503. for (var i = 0; i < this._stride; i++) {
  38504. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  38505. }
  38506. element.offset = destOffset;
  38507. };
  38508. DynamicFloatArray.prototype._growBuffer = function () {
  38509. // Allocate the new buffer with 50% more entries, copy the content of the current one
  38510. var newElCount = Math.floor(this.totalElementCount * 1.5);
  38511. var newBuffer = new Float32Array(newElCount * this._stride);
  38512. newBuffer.set(this.buffer);
  38513. var curCount = this.totalElementCount;
  38514. var addedCount = newElCount - this.totalElementCount;
  38515. for (var i = 0; i < addedCount; i++) {
  38516. var element = new DynamicFloatArrayElementInfo();
  38517. element.offset = (curCount + i) * this.stride;
  38518. this._allEntries.push(element);
  38519. this._freeEntries[addedCount - i - 1] = element;
  38520. }
  38521. this._firstFree = curCount * this.stride;
  38522. this.buffer = newBuffer;
  38523. };
  38524. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  38525. /**
  38526. * Get the total count of entries that can fit in the current buffer
  38527. * @returns the elements count
  38528. */
  38529. get: function () {
  38530. return this._allEntries.length;
  38531. },
  38532. enumerable: true,
  38533. configurable: true
  38534. });
  38535. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  38536. /**
  38537. * Get the count of free entries that can still be allocated without resizing the buffer
  38538. * @returns the free elements count
  38539. */
  38540. get: function () {
  38541. return this._freeEntries.length;
  38542. },
  38543. enumerable: true,
  38544. configurable: true
  38545. });
  38546. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  38547. /**
  38548. * Get the count of allocated elements
  38549. * @returns the allocated elements count
  38550. */
  38551. get: function () {
  38552. return this._allEntries.length - this._freeEntries.length;
  38553. },
  38554. enumerable: true,
  38555. configurable: true
  38556. });
  38557. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  38558. /**
  38559. * Return the size of one element in float
  38560. * @returns the size in float
  38561. */
  38562. get: function () {
  38563. return this._stride;
  38564. },
  38565. enumerable: true,
  38566. configurable: true
  38567. });
  38568. DynamicFloatArray.prototype.sort = function () {
  38569. var _this = this;
  38570. if (!this.compareValueOffset) {
  38571. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  38572. }
  38573. var count = this.usedElementCount;
  38574. // Do we have to (re)create the sort table?
  38575. if (!this._sortTable || this._sortTable.length < count) {
  38576. // 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...
  38577. var newCount = Math.min(this.totalElementCount, count * 2);
  38578. this._sortTable = new Array(newCount);
  38579. }
  38580. if (!this._sortedTable || this._sortedTable.length !== count) {
  38581. this._sortedTable = new Array(count);
  38582. }
  38583. // Because, you know...
  38584. this.pack();
  38585. //let stride = this.stride;
  38586. //for (let i = 0; i < count; i++) {
  38587. // let si = this._sortTable[i];
  38588. // if (!si) {
  38589. // si = new SortInfo();
  38590. // this._sortTable[i] = si;
  38591. // }
  38592. // si.entry = this._allEntries[i];
  38593. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  38594. // si.swapedOffset = null;
  38595. // this._sortedTable[i] = si;
  38596. //}
  38597. var curOffset = 0;
  38598. var stride = this.stride;
  38599. for (var i = 0; i < count; i++, curOffset += stride) {
  38600. var si = this._sortTable[i];
  38601. if (!si) {
  38602. si = new SortInfo();
  38603. this._sortTable[i] = si;
  38604. }
  38605. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  38606. si.offset = curOffset;
  38607. si.swapedOffset = null;
  38608. this._sortedTable[i] = si;
  38609. }
  38610. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  38611. if (this.sortingAscending) {
  38612. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  38613. }
  38614. else {
  38615. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  38616. }
  38617. var swapElements = function (src, dst) {
  38618. for (var i = 0; i < stride; i++) {
  38619. var tps = _this.buffer[dst + i];
  38620. _this.buffer[dst + i] = _this.buffer[src + i];
  38621. _this.buffer[src + i] = tps;
  38622. }
  38623. };
  38624. // 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:
  38625. // 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),
  38626. // and I still want something with a good algorithm complexity.
  38627. // 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,
  38628. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  38629. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  38630. // 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
  38631. // until we find a SortInfo object without a swapedOffset which means we got the right location
  38632. // 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
  38633. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  38634. for (var i = 0; i < count; i++) {
  38635. // Get the element to move
  38636. var sourceSI = this._sortedTable[i];
  38637. var destSI = this._sortTable[i];
  38638. var sourceOff = sourceSI.offset;
  38639. // If the source changed location, find the new one
  38640. if (sourceSI.swapedOffset) {
  38641. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  38642. var curSI = sourceSI;
  38643. while (curSI.swapedOffset) {
  38644. curSI = this._sortTable[curSI.swapedOffset / stride];
  38645. }
  38646. // Finally get the right location
  38647. sourceOff = curSI.offset;
  38648. }
  38649. // Tag the element being replaced with its new location
  38650. destSI.swapedOffset = sourceOff;
  38651. // Swap elements (only if needed)
  38652. if (sourceOff !== destSI.offset) {
  38653. swapElements(sourceOff, destSI.offset);
  38654. }
  38655. // Update the offset in the corresponding DFAE
  38656. //sourceSI.entry.offset = destSI.entry.offset;
  38657. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38658. }
  38659. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38660. return true;
  38661. };
  38662. return DynamicFloatArray;
  38663. }());
  38664. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38665. var SortInfo = (function () {
  38666. function SortInfo() {
  38667. this.compareData = this.offset = this.swapedOffset = null;
  38668. }
  38669. return SortInfo;
  38670. }());
  38671. })(BABYLON || (BABYLON = {}));
  38672. var BABYLON;
  38673. (function (BABYLON) {
  38674. /**
  38675. * This class given information about a given character.
  38676. */
  38677. var CharInfo = (function () {
  38678. function CharInfo() {
  38679. }
  38680. return CharInfo;
  38681. }());
  38682. BABYLON.CharInfo = CharInfo;
  38683. var FontTexture = (function (_super) {
  38684. __extends(FontTexture, _super);
  38685. /**
  38686. * Create a new instance of the FontTexture class
  38687. * @param name the name of the texture
  38688. * @param font the font to use, use the W3C CSS notation
  38689. * @param scene the scene that owns the texture
  38690. * @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
  38691. * @param samplingMode the texture sampling mode
  38692. * @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.
  38693. */
  38694. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  38695. if (maxCharCount === void 0) { maxCharCount = 200; }
  38696. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38697. if (superSample === void 0) { superSample = false; }
  38698. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38699. _super.call(this, null, scene, true, false, samplingMode);
  38700. this._charInfos = {};
  38701. this._curCharCount = 0;
  38702. this._lastUpdateCharCount = -1;
  38703. this._usedCounter = 1;
  38704. this.name = name;
  38705. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38706. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38707. this._sdfScale = 8;
  38708. this._signedDistanceField = signedDistanceField;
  38709. this._superSample = false;
  38710. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  38711. if (superSample || signedDistanceField) {
  38712. var sfont = this.getSuperSampleFont(font);
  38713. if (sfont) {
  38714. this._superSample = true;
  38715. font = sfont;
  38716. }
  38717. }
  38718. // First canvas creation to determine the size of the texture to create
  38719. this._canvas = document.createElement("canvas");
  38720. this._context = this._canvas.getContext("2d");
  38721. this._context.font = font;
  38722. this._context.fillStyle = "white";
  38723. this._context.textBaseline = "top";
  38724. this._cachedFontId = null;
  38725. var res = this.getFontHeight(font);
  38726. this._lineHeightSuper = res.height + 4;
  38727. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  38728. this._offset = res.offset - 1;
  38729. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38730. this._yMargin = this._xMargin;
  38731. var maxCharWidth = this._context.measureText("W").width;
  38732. this._spaceWidthSuper = this._context.measureText(" ").width;
  38733. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38734. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38735. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  38736. var edge = Math.sqrt(totalEstSurface);
  38737. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38738. // Create the texture that will store the font characters
  38739. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38740. var textureSize = this.getSize();
  38741. this.hasAlpha = this._signedDistanceField === false;
  38742. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38743. this._canvas = document.createElement("canvas");
  38744. this._canvas.width = textureSize.width;
  38745. this._canvas.height = textureSize.height;
  38746. this._context = this._canvas.getContext("2d");
  38747. this._context.textBaseline = "top";
  38748. this._context.font = font;
  38749. this._context.fillStyle = "white";
  38750. this._context.imageSmoothingEnabled = false;
  38751. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  38752. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  38753. // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
  38754. // So you can see this context as an intermediate one, because it is.
  38755. if (this._signedDistanceField) {
  38756. var sdfC = document.createElement("canvas");
  38757. var s = this._sdfScale;
  38758. sdfC.width = maxCharWidth * s;
  38759. sdfC.height = this._lineHeightSuper * s;
  38760. var sdfCtx = sdfC.getContext("2d");
  38761. sdfCtx.scale(s, s);
  38762. sdfCtx.textBaseline = "top";
  38763. sdfCtx.font = font;
  38764. sdfCtx.fillStyle = "white";
  38765. sdfCtx.imageSmoothingEnabled = false;
  38766. this._sdfCanvas = sdfC;
  38767. this._sdfContext = sdfCtx;
  38768. }
  38769. this._currentFreePosition = BABYLON.Vector2.Zero();
  38770. // Add the basic ASCII based characters
  38771. for (var i = 0x20; i < 0x7F; i++) {
  38772. var c = String.fromCharCode(i);
  38773. this.getChar(c);
  38774. }
  38775. this.update();
  38776. }
  38777. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38778. get: function () {
  38779. return this._superSample;
  38780. },
  38781. enumerable: true,
  38782. configurable: true
  38783. });
  38784. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  38785. get: function () {
  38786. return this._signedDistanceField;
  38787. },
  38788. enumerable: true,
  38789. configurable: true
  38790. });
  38791. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38792. get: function () {
  38793. return this._spaceWidth;
  38794. },
  38795. enumerable: true,
  38796. configurable: true
  38797. });
  38798. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38799. get: function () {
  38800. return this._lineHeight;
  38801. },
  38802. enumerable: true,
  38803. configurable: true
  38804. });
  38805. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  38806. if (supersample === void 0) { supersample = false; }
  38807. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38808. var s = scene;
  38809. if (!s.__fontTextureCache__) {
  38810. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38811. }
  38812. var dic = s.__fontTextureCache__;
  38813. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  38814. var ft = dic.get(lfn);
  38815. if (ft) {
  38816. ++ft._usedCounter;
  38817. return ft;
  38818. }
  38819. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  38820. ft._cachedFontId = lfn;
  38821. dic.add(lfn, ft);
  38822. return ft;
  38823. };
  38824. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  38825. if (supersample === void 0) { supersample = false; }
  38826. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38827. var s = scene;
  38828. var dic = s.__fontTextureCache__;
  38829. if (!dic) {
  38830. return;
  38831. }
  38832. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  38833. var font = dic.get(lfn);
  38834. if (--font._usedCounter === 0) {
  38835. dic.remove(lfn);
  38836. font.dispose();
  38837. }
  38838. };
  38839. /**
  38840. * Make sure the given char is present in the font map.
  38841. * @param char the character to get or add
  38842. * @return the CharInfo instance corresponding to the given character
  38843. */
  38844. FontTexture.prototype.getChar = function (char) {
  38845. if (char.length !== 1) {
  38846. return null;
  38847. }
  38848. var info = this._charInfos[char];
  38849. if (info) {
  38850. return info;
  38851. }
  38852. info = new CharInfo();
  38853. var measure = this._context.measureText(char);
  38854. var textureSize = this.getSize();
  38855. // we reached the end of the current line?
  38856. var width = Math.round(measure.width);
  38857. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  38858. this._currentFreePosition.x = 0;
  38859. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  38860. // No more room?
  38861. if (this._currentFreePosition.y > textureSize.height) {
  38862. return this.getChar("!");
  38863. }
  38864. }
  38865. // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
  38866. if (this._signedDistanceField) {
  38867. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  38868. this._sdfContext.fillText(char, 0, -this._offset);
  38869. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  38870. var res = this._computeSDFChar(data);
  38871. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  38872. }
  38873. else {
  38874. // Draw the character in the HTML canvas
  38875. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38876. }
  38877. // Fill the CharInfo object
  38878. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38879. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38880. if (this._signedDistanceField) {
  38881. var off = 1 / textureSize.width;
  38882. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  38883. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  38884. }
  38885. info.charWidth = this._superSample ? (width / 2) : width;
  38886. // Add the info structure
  38887. this._charInfos[char] = info;
  38888. this._curCharCount++;
  38889. // Set the next position
  38890. this._currentFreePosition.x += width + this._xMargin;
  38891. return info;
  38892. };
  38893. FontTexture.prototype._computeSDFChar = function (source) {
  38894. var scl = this._sdfScale;
  38895. var sw = source.width;
  38896. var sh = source.height;
  38897. var dw = sw / scl;
  38898. var dh = sh / scl;
  38899. var roffx = 0;
  38900. var roffy = 0;
  38901. // We shouldn't look beyond half of the biggest between width and height
  38902. var radius = scl;
  38903. var br = radius - 1;
  38904. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  38905. var sx = dx * scl;
  38906. var sy = dy * scl;
  38907. // Looking out of the area? return true to make the test going on
  38908. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  38909. return true;
  38910. }
  38911. // Get the pixel we want
  38912. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  38913. var res = (val > 0) === lookVis;
  38914. if (!res) {
  38915. roffx = offX;
  38916. roffy = offY;
  38917. }
  38918. return res;
  38919. };
  38920. var lookupArea = function (dx, dy, lookVis) {
  38921. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  38922. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  38923. lookupSrc(dx, dy, 0, -br, lookVis) &&
  38924. lookupSrc(dx, dy, -br, 0, lookVis) &&
  38925. lookupSrc(dx, dy, br, 0, lookVis)) {
  38926. return 0;
  38927. }
  38928. for (var i = 1; i <= radius; i++) {
  38929. // Quick test N, S, W, E
  38930. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  38931. return i * i; // Squared Distance is simple to compute in this case
  38932. }
  38933. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  38934. for (var j = 1; j <= i; j++) {
  38935. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  38936. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  38937. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  38938. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  38939. // We found the nearest texel having and opposite state, store the squared length
  38940. var res_1 = (i * i) + (j * j);
  38941. var count = 1;
  38942. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  38943. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  38944. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  38945. ++count;
  38946. }
  38947. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  38948. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  38949. ++count;
  38950. }
  38951. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  38952. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  38953. ++count;
  38954. }
  38955. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  38956. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  38957. ++count;
  38958. }
  38959. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  38960. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  38961. ++count;
  38962. }
  38963. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  38964. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  38965. ++count;
  38966. }
  38967. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  38968. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  38969. ++count;
  38970. }
  38971. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  38972. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  38973. ++count;
  38974. }
  38975. // Compute the average based on the accumulated distance
  38976. return res_1 / count;
  38977. }
  38978. }
  38979. }
  38980. return 0;
  38981. };
  38982. var tmp = new Array(dw * dh);
  38983. for (var y = 0; y < dh; y++) {
  38984. for (var x = 0; x < dw; x++) {
  38985. var curState = lookupSrc(x, y, 0, 0, true);
  38986. var d = lookupArea(x, y, curState);
  38987. if (d === 0) {
  38988. d = radius * radius * 2;
  38989. }
  38990. tmp[(y * dw) + x] = curState ? d : -d;
  38991. }
  38992. }
  38993. var res = this._context.createImageData(dw, dh);
  38994. var size = dw * dh;
  38995. for (var j = 0; j < size; j++) {
  38996. var d = tmp[j];
  38997. var sign = (d < 0) ? -1 : 1;
  38998. d = Math.sqrt(Math.abs(d)) * sign;
  38999. d *= 127.5 / radius;
  39000. d += 127.5;
  39001. if (d < 0) {
  39002. d = 0;
  39003. }
  39004. else if (d > 255) {
  39005. d = 255;
  39006. }
  39007. d += 0.5;
  39008. res.data[j * 4 + 0] = d;
  39009. res.data[j * 4 + 1] = d;
  39010. res.data[j * 4 + 2] = d;
  39011. res.data[j * 4 + 3] = 255;
  39012. }
  39013. return res;
  39014. };
  39015. FontTexture.prototype.measureText = function (text, tabulationSize) {
  39016. if (tabulationSize === void 0) { tabulationSize = 4; }
  39017. var maxWidth = 0;
  39018. var curWidth = 0;
  39019. var lineCount = 1;
  39020. var charxpos = 0;
  39021. // Parse each char of the string
  39022. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  39023. var char = text_1[_i];
  39024. // Next line feed?
  39025. if (char === "\n") {
  39026. maxWidth = Math.max(maxWidth, curWidth);
  39027. charxpos = 0;
  39028. curWidth = 0;
  39029. ++lineCount;
  39030. continue;
  39031. }
  39032. // Tabulation ?
  39033. if (char === "\t") {
  39034. var nextPos = charxpos + tabulationSize;
  39035. nextPos = nextPos - (nextPos % tabulationSize);
  39036. curWidth += (nextPos - charxpos) * this.spaceWidth;
  39037. charxpos = nextPos;
  39038. continue;
  39039. }
  39040. if (char < " ") {
  39041. continue;
  39042. }
  39043. curWidth += this.getChar(char).charWidth;
  39044. ++charxpos;
  39045. }
  39046. maxWidth = Math.max(maxWidth, curWidth);
  39047. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  39048. };
  39049. FontTexture.prototype.getSuperSampleFont = function (font) {
  39050. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  39051. 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*$/;
  39052. var res = font.toLocaleLowerCase().match(regex);
  39053. if (res == null) {
  39054. return null;
  39055. }
  39056. var size = parseInt(res[4]);
  39057. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  39058. var newFont = "";
  39059. for (var j = 1; j < res.length; j++) {
  39060. if (res[j] != null) {
  39061. newFont += res[j] + " ";
  39062. }
  39063. }
  39064. return newFont;
  39065. };
  39066. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  39067. FontTexture.prototype.getFontHeight = function (font) {
  39068. var fontDraw = document.createElement("canvas");
  39069. var ctx = fontDraw.getContext('2d');
  39070. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  39071. ctx.textBaseline = 'top';
  39072. ctx.fillStyle = 'white';
  39073. ctx.font = font;
  39074. ctx.fillText('jH|', 0, 0);
  39075. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  39076. var start = -1;
  39077. var end = -1;
  39078. for (var row = 0; row < fontDraw.height; row++) {
  39079. for (var column = 0; column < fontDraw.width; column++) {
  39080. var index = (row * fontDraw.width + column) * 4;
  39081. if (pixels[index] === 0) {
  39082. if (column === fontDraw.width - 1 && start !== -1) {
  39083. end = row;
  39084. row = fontDraw.height;
  39085. break;
  39086. }
  39087. continue;
  39088. }
  39089. else {
  39090. if (start === -1) {
  39091. start = row;
  39092. }
  39093. break;
  39094. }
  39095. }
  39096. }
  39097. return { height: (end - start) + 1, offset: start - 1 };
  39098. };
  39099. Object.defineProperty(FontTexture.prototype, "canRescale", {
  39100. get: function () {
  39101. return false;
  39102. },
  39103. enumerable: true,
  39104. configurable: true
  39105. });
  39106. FontTexture.prototype.getContext = function () {
  39107. return this._context;
  39108. };
  39109. /**
  39110. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  39111. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  39112. */
  39113. FontTexture.prototype.update = function () {
  39114. // Update only if there's new char added since the previous update
  39115. if (this._lastUpdateCharCount < this._curCharCount) {
  39116. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  39117. this._lastUpdateCharCount = this._curCharCount;
  39118. }
  39119. };
  39120. // cloning should be prohibited, there's no point to duplicate this texture at all
  39121. FontTexture.prototype.clone = function () {
  39122. return null;
  39123. };
  39124. /**
  39125. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  39126. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  39127. */
  39128. FontTexture.prototype.incCachedFontTextureCounter = function () {
  39129. ++this._usedCounter;
  39130. };
  39131. /**
  39132. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  39133. */
  39134. FontTexture.prototype.decCachedFontTextureCounter = function () {
  39135. var s = this.getScene();
  39136. var dic = s.__fontTextureCache__;
  39137. if (!dic) {
  39138. return;
  39139. }
  39140. if (--this._usedCounter === 0) {
  39141. dic.remove(this._cachedFontId);
  39142. this.dispose();
  39143. }
  39144. };
  39145. return FontTexture;
  39146. }(BABYLON.Texture));
  39147. BABYLON.FontTexture = FontTexture;
  39148. })(BABYLON || (BABYLON = {}));
  39149. var BABYLON;
  39150. (function (BABYLON) {
  39151. var MapTexture = (function (_super) {
  39152. __extends(MapTexture, _super);
  39153. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  39154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39155. if (useMipMap === void 0) { useMipMap = false; }
  39156. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  39157. this.name = name;
  39158. this._size = size;
  39159. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39160. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39161. // Create the rectPackMap that will allocate portion of the texture
  39162. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  39163. // Create the texture that will store the content
  39164. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  39165. }
  39166. /**
  39167. * Allocate a rectangle of a given size in the texture map
  39168. * @param size the size of the rectangle to allocation
  39169. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  39170. */
  39171. MapTexture.prototype.allocateRect = function (size) {
  39172. return this._rectPackingMap.addRect(size);
  39173. };
  39174. /**
  39175. * Free a given rectangle from the texture map
  39176. * @param rectInfo the instance corresponding to the rect to free.
  39177. */
  39178. MapTexture.prototype.freeRect = function (rectInfo) {
  39179. if (rectInfo) {
  39180. rectInfo.freeContent();
  39181. }
  39182. };
  39183. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  39184. /**
  39185. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  39186. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  39187. * @returns {}
  39188. */
  39189. get: function () {
  39190. return this._rectPackingMap.freeSpace;
  39191. },
  39192. enumerable: true,
  39193. configurable: true
  39194. });
  39195. /**
  39196. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  39197. * 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.
  39198. * Don't forget to call unbindTexture when you're done rendering
  39199. * @param rect the zone to render to
  39200. * @param clear true to clear the portion's color/depth data
  39201. */
  39202. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  39203. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  39204. };
  39205. /**
  39206. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  39207. * 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.
  39208. * Don't forget to call unbindTexture when you're done rendering
  39209. * @param pos the position into the texture
  39210. * @param size the portion to fit the clip space to
  39211. * @param clear true to clear the portion's color/depth data
  39212. */
  39213. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  39214. var engine = this.getScene().getEngine();
  39215. engine.bindFramebuffer(this._texture);
  39216. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  39217. if (clear) {
  39218. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  39219. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  39220. }
  39221. };
  39222. /**
  39223. * Unbind the texture map from the rendering engine.
  39224. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  39225. * @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.
  39226. */
  39227. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  39228. // Dump ?
  39229. if (dumpForDebug) {
  39230. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  39231. }
  39232. var engine = this.getScene().getEngine();
  39233. if (this._replacedViewport) {
  39234. engine.setViewport(this._replacedViewport);
  39235. this._replacedViewport = null;
  39236. }
  39237. engine.unBindFramebuffer(this._texture);
  39238. };
  39239. Object.defineProperty(MapTexture.prototype, "canRescale", {
  39240. get: function () {
  39241. return false;
  39242. },
  39243. enumerable: true,
  39244. configurable: true
  39245. });
  39246. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  39247. // Anyway, there's not much point to use this method for this kind of texture I guess
  39248. MapTexture.prototype.clone = function () {
  39249. return null;
  39250. };
  39251. return MapTexture;
  39252. }(BABYLON.Texture));
  39253. BABYLON.MapTexture = MapTexture;
  39254. })(BABYLON || (BABYLON = {}));
  39255. var BABYLON;
  39256. (function (BABYLON) {
  39257. var ShaderMaterial = (function (_super) {
  39258. __extends(ShaderMaterial, _super);
  39259. function ShaderMaterial(name, scene, shaderPath, options) {
  39260. _super.call(this, name, scene);
  39261. this._textures = {};
  39262. this._textureArrays = {};
  39263. this._floats = {};
  39264. this._floatsArrays = {};
  39265. this._colors3 = {};
  39266. this._colors4 = {};
  39267. this._vectors2 = {};
  39268. this._vectors3 = {};
  39269. this._vectors4 = {};
  39270. this._matrices = {};
  39271. this._matrices3x3 = {};
  39272. this._matrices2x2 = {};
  39273. this._vectors3Arrays = {};
  39274. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39275. this._shaderPath = shaderPath;
  39276. options.needAlphaBlending = options.needAlphaBlending || false;
  39277. options.needAlphaTesting = options.needAlphaTesting || false;
  39278. options.attributes = options.attributes || ["position", "normal", "uv"];
  39279. options.uniforms = options.uniforms || ["worldViewProjection"];
  39280. options.samplers = options.samplers || [];
  39281. options.defines = options.defines || [];
  39282. this._options = options;
  39283. }
  39284. ShaderMaterial.prototype.needAlphaBlending = function () {
  39285. return this._options.needAlphaBlending;
  39286. };
  39287. ShaderMaterial.prototype.needAlphaTesting = function () {
  39288. return this._options.needAlphaTesting;
  39289. };
  39290. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39291. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39292. this._options.uniforms.push(uniformName);
  39293. }
  39294. };
  39295. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39296. if (this._options.samplers.indexOf(name) === -1) {
  39297. this._options.samplers.push(name);
  39298. }
  39299. this._textures[name] = texture;
  39300. return this;
  39301. };
  39302. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39303. if (this._options.samplers.indexOf(name) === -1) {
  39304. this._options.samplers.push(name);
  39305. }
  39306. this._checkUniform(name);
  39307. this._textureArrays[name] = textures;
  39308. return this;
  39309. };
  39310. ShaderMaterial.prototype.setFloat = function (name, value) {
  39311. this._checkUniform(name);
  39312. this._floats[name] = value;
  39313. return this;
  39314. };
  39315. ShaderMaterial.prototype.setFloats = function (name, value) {
  39316. this._checkUniform(name);
  39317. this._floatsArrays[name] = value;
  39318. return this;
  39319. };
  39320. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39321. this._checkUniform(name);
  39322. this._colors3[name] = value;
  39323. return this;
  39324. };
  39325. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39326. this._checkUniform(name);
  39327. this._colors4[name] = value;
  39328. return this;
  39329. };
  39330. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39331. this._checkUniform(name);
  39332. this._vectors2[name] = value;
  39333. return this;
  39334. };
  39335. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39336. this._checkUniform(name);
  39337. this._vectors3[name] = value;
  39338. return this;
  39339. };
  39340. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39341. this._checkUniform(name);
  39342. this._vectors4[name] = value;
  39343. return this;
  39344. };
  39345. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39346. this._checkUniform(name);
  39347. this._matrices[name] = value;
  39348. return this;
  39349. };
  39350. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39351. this._checkUniform(name);
  39352. this._matrices3x3[name] = value;
  39353. return this;
  39354. };
  39355. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39356. this._checkUniform(name);
  39357. this._matrices2x2[name] = value;
  39358. return this;
  39359. };
  39360. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39361. this._checkUniform(name);
  39362. this._vectors3Arrays[name] = value;
  39363. return this;
  39364. };
  39365. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39366. var scene = this.getScene();
  39367. var engine = scene.getEngine();
  39368. if (!this.checkReadyOnEveryCall) {
  39369. if (this._renderId === scene.getRenderId()) {
  39370. return true;
  39371. }
  39372. }
  39373. // Instances
  39374. var defines = [];
  39375. var fallbacks = new BABYLON.EffectFallbacks();
  39376. if (useInstances) {
  39377. defines.push("#define INSTANCES");
  39378. }
  39379. for (var index = 0; index < this._options.defines.length; index++) {
  39380. defines.push(this._options.defines[index]);
  39381. }
  39382. // Bones
  39383. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39384. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39385. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39386. fallbacks.addCPUSkinningFallback(0, mesh);
  39387. }
  39388. // Alpha test
  39389. if (engine.getAlphaTesting()) {
  39390. defines.push("#define ALPHATEST");
  39391. }
  39392. var previousEffect = this._effect;
  39393. var join = defines.join("\n");
  39394. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  39395. if (!this._effect.isReady()) {
  39396. return false;
  39397. }
  39398. if (previousEffect !== this._effect) {
  39399. scene.resetCachedMaterial();
  39400. }
  39401. this._renderId = scene.getRenderId();
  39402. return true;
  39403. };
  39404. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39405. var scene = this.getScene();
  39406. if (this._options.uniforms.indexOf("world") !== -1) {
  39407. this._effect.setMatrix("world", world);
  39408. }
  39409. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39410. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39411. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39412. }
  39413. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39414. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39415. }
  39416. };
  39417. ShaderMaterial.prototype.bind = function (world, mesh) {
  39418. // Std values
  39419. this.bindOnlyWorldMatrix(world);
  39420. if (this.getScene().getCachedMaterial() !== this) {
  39421. if (this._options.uniforms.indexOf("view") !== -1) {
  39422. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39423. }
  39424. if (this._options.uniforms.indexOf("projection") !== -1) {
  39425. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39426. }
  39427. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39428. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39429. }
  39430. // Bones
  39431. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39432. var name;
  39433. // Texture
  39434. for (name in this._textures) {
  39435. this._effect.setTexture(name, this._textures[name]);
  39436. }
  39437. // Texture arrays
  39438. for (name in this._textureArrays) {
  39439. this._effect.setTextureArray(name, this._textureArrays[name]);
  39440. }
  39441. // Float
  39442. for (name in this._floats) {
  39443. this._effect.setFloat(name, this._floats[name]);
  39444. }
  39445. // Float s
  39446. for (name in this._floatsArrays) {
  39447. this._effect.setArray(name, this._floatsArrays[name]);
  39448. }
  39449. // Color3
  39450. for (name in this._colors3) {
  39451. this._effect.setColor3(name, this._colors3[name]);
  39452. }
  39453. // Color4
  39454. for (name in this._colors4) {
  39455. var color = this._colors4[name];
  39456. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39457. }
  39458. // Vector2
  39459. for (name in this._vectors2) {
  39460. this._effect.setVector2(name, this._vectors2[name]);
  39461. }
  39462. // Vector3
  39463. for (name in this._vectors3) {
  39464. this._effect.setVector3(name, this._vectors3[name]);
  39465. }
  39466. // Vector4
  39467. for (name in this._vectors4) {
  39468. this._effect.setVector4(name, this._vectors4[name]);
  39469. }
  39470. // Matrix
  39471. for (name in this._matrices) {
  39472. this._effect.setMatrix(name, this._matrices[name]);
  39473. }
  39474. // Matrix 3x3
  39475. for (name in this._matrices3x3) {
  39476. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39477. }
  39478. // Matrix 2x2
  39479. for (name in this._matrices2x2) {
  39480. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39481. }
  39482. // Vector3Array
  39483. for (name in this._vectors3Arrays) {
  39484. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39485. }
  39486. }
  39487. _super.prototype.bind.call(this, world, mesh);
  39488. };
  39489. ShaderMaterial.prototype.clone = function (name) {
  39490. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39491. return newShaderMaterial;
  39492. };
  39493. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39494. if (forceDisposeTextures) {
  39495. var name;
  39496. for (name in this._textures) {
  39497. this._textures[name].dispose();
  39498. }
  39499. for (name in this._textureArrays) {
  39500. var array = this._textureArrays[name];
  39501. for (var index = 0; index < array.length; index++) {
  39502. array[index].dispose();
  39503. }
  39504. }
  39505. }
  39506. this._textures = {};
  39507. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39508. };
  39509. ShaderMaterial.prototype.serialize = function () {
  39510. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39511. serializationObject.customType = "BABYLON.ShaderMaterial";
  39512. serializationObject.options = this._options;
  39513. serializationObject.shaderPath = this._shaderPath;
  39514. var name;
  39515. // Texture
  39516. serializationObject.textures = {};
  39517. for (name in this._textures) {
  39518. serializationObject.textures[name] = this._textures[name].serialize();
  39519. }
  39520. // Texture arrays
  39521. serializationObject.textureArrays = {};
  39522. for (name in this._textureArrays) {
  39523. serializationObject.textureArrays[name] = [];
  39524. var array = this._textureArrays[name];
  39525. for (var index = 0; index < array.length; index++) {
  39526. serializationObject.textureArrays[name].push(array[index].serialize());
  39527. }
  39528. }
  39529. // Float
  39530. serializationObject.floats = {};
  39531. for (name in this._floats) {
  39532. serializationObject.floats[name] = this._floats[name];
  39533. }
  39534. // Float s
  39535. serializationObject.floatArrays = {};
  39536. for (name in this._floatsArrays) {
  39537. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39538. }
  39539. // Color3
  39540. serializationObject.colors3 = {};
  39541. for (name in this._colors3) {
  39542. serializationObject.colors3[name] = this._colors3[name].asArray();
  39543. }
  39544. // Color4
  39545. serializationObject.colors4 = {};
  39546. for (name in this._colors4) {
  39547. serializationObject.colors4[name] = this._colors4[name].asArray();
  39548. }
  39549. // Vector2
  39550. serializationObject.vectors2 = {};
  39551. for (name in this._vectors2) {
  39552. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39553. }
  39554. // Vector3
  39555. serializationObject.vectors3 = {};
  39556. for (name in this._vectors3) {
  39557. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39558. }
  39559. // Vector4
  39560. serializationObject.vectors4 = {};
  39561. for (name in this._vectors4) {
  39562. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39563. }
  39564. // Matrix
  39565. serializationObject.matrices = {};
  39566. for (name in this._matrices) {
  39567. serializationObject.matrices[name] = this._matrices[name].asArray();
  39568. }
  39569. // Matrix 3x3
  39570. serializationObject.matrices3x3 = {};
  39571. for (name in this._matrices3x3) {
  39572. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39573. }
  39574. // Matrix 2x2
  39575. serializationObject.matrices2x2 = {};
  39576. for (name in this._matrices2x2) {
  39577. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39578. }
  39579. // Vector3Array
  39580. serializationObject.vectors3Arrays = {};
  39581. for (name in this._vectors3Arrays) {
  39582. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39583. }
  39584. return serializationObject;
  39585. };
  39586. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39587. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39588. var name;
  39589. // Texture
  39590. for (name in source.textures) {
  39591. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39592. }
  39593. // Texture arrays
  39594. for (name in source.textureArrays) {
  39595. var array = source.textureArrays[name];
  39596. var textureArray = new Array();
  39597. for (var index = 0; index < array.length; index++) {
  39598. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39599. }
  39600. material.setTextureArray(name, textureArray);
  39601. }
  39602. // Float
  39603. for (name in source.floats) {
  39604. material.setFloat(name, source.floats[name]);
  39605. }
  39606. // Float s
  39607. for (name in source.floatsArrays) {
  39608. material.setFloats(name, source.floatsArrays[name]);
  39609. }
  39610. // Color3
  39611. for (name in source.colors3) {
  39612. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39613. }
  39614. // Color4
  39615. for (name in source.colors4) {
  39616. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39617. }
  39618. // Vector2
  39619. for (name in source.vectors2) {
  39620. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39621. }
  39622. // Vector3
  39623. for (name in source.vectors3) {
  39624. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39625. }
  39626. // Vector4
  39627. for (name in source.vectors4) {
  39628. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39629. }
  39630. // Matrix
  39631. for (name in source.matrices) {
  39632. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39633. }
  39634. // Matrix 3x3
  39635. for (name in source.matrices3x3) {
  39636. material.setMatrix3x3(name, source.matrices3x3[name]);
  39637. }
  39638. // Matrix 2x2
  39639. for (name in source.matrices2x2) {
  39640. material.setMatrix2x2(name, source.matrices2x2[name]);
  39641. }
  39642. // Vector3Array
  39643. for (name in source.vectors3Arrays) {
  39644. material.setArray3(name, source.vectors3Arrays[name]);
  39645. }
  39646. return material;
  39647. };
  39648. return ShaderMaterial;
  39649. }(BABYLON.Material));
  39650. BABYLON.ShaderMaterial = ShaderMaterial;
  39651. })(BABYLON || (BABYLON = {}));
  39652. var BABYLON;
  39653. (function (BABYLON) {
  39654. var Internals;
  39655. (function (Internals) {
  39656. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  39657. // All values and structures referenced from:
  39658. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  39659. var DDS_MAGIC = 0x20534444;
  39660. 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;
  39661. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  39662. 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;
  39663. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  39664. function FourCCToInt32(value) {
  39665. return value.charCodeAt(0) +
  39666. (value.charCodeAt(1) << 8) +
  39667. (value.charCodeAt(2) << 16) +
  39668. (value.charCodeAt(3) << 24);
  39669. }
  39670. function Int32ToFourCC(value) {
  39671. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  39672. }
  39673. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  39674. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  39675. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  39676. var headerLengthInt = 31; // The header length in 32 bit ints
  39677. // Offsets into the header array
  39678. var off_magic = 0;
  39679. var off_size = 1;
  39680. var off_flags = 2;
  39681. var off_height = 3;
  39682. var off_width = 4;
  39683. var off_mipmapCount = 7;
  39684. var off_pfFlags = 20;
  39685. var off_pfFourCC = 21;
  39686. var off_RGBbpp = 22;
  39687. var off_RMask = 23;
  39688. var off_GMask = 24;
  39689. var off_BMask = 25;
  39690. var off_AMask = 26;
  39691. var off_caps1 = 27;
  39692. var off_caps2 = 28;
  39693. ;
  39694. var DDSTools = (function () {
  39695. function DDSTools() {
  39696. }
  39697. DDSTools.GetDDSInfo = function (arrayBuffer) {
  39698. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  39699. var mipmapCount = 1;
  39700. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  39701. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39702. }
  39703. return {
  39704. width: header[off_width],
  39705. height: header[off_height],
  39706. mipmapCount: mipmapCount,
  39707. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  39708. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  39709. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  39710. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  39711. };
  39712. };
  39713. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39714. var byteArray = new Uint8Array(dataLength);
  39715. var srcData = new Uint8Array(arrayBuffer);
  39716. var index = 0;
  39717. for (var y = height - 1; y >= 0; y--) {
  39718. for (var x = 0; x < width; x++) {
  39719. var srcPos = dataOffset + (x + y * width) * 4;
  39720. byteArray[index + 2] = srcData[srcPos];
  39721. byteArray[index + 1] = srcData[srcPos + 1];
  39722. byteArray[index] = srcData[srcPos + 2];
  39723. byteArray[index + 3] = srcData[srcPos + 3];
  39724. index += 4;
  39725. }
  39726. }
  39727. return byteArray;
  39728. };
  39729. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39730. var byteArray = new Uint8Array(dataLength);
  39731. var srcData = new Uint8Array(arrayBuffer);
  39732. var index = 0;
  39733. for (var y = height - 1; y >= 0; y--) {
  39734. for (var x = 0; x < width; x++) {
  39735. var srcPos = dataOffset + (x + y * width) * 3;
  39736. byteArray[index + 2] = srcData[srcPos];
  39737. byteArray[index + 1] = srcData[srcPos + 1];
  39738. byteArray[index] = srcData[srcPos + 2];
  39739. index += 3;
  39740. }
  39741. }
  39742. return byteArray;
  39743. };
  39744. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39745. var byteArray = new Uint8Array(dataLength);
  39746. var srcData = new Uint8Array(arrayBuffer);
  39747. var index = 0;
  39748. for (var y = height - 1; y >= 0; y--) {
  39749. for (var x = 0; x < width; x++) {
  39750. var srcPos = dataOffset + (x + y * width);
  39751. byteArray[index] = srcData[srcPos];
  39752. index++;
  39753. }
  39754. }
  39755. return byteArray;
  39756. };
  39757. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  39758. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  39759. if (header[off_magic] != DDS_MAGIC) {
  39760. BABYLON.Tools.Error("Invalid magic number in DDS header");
  39761. return;
  39762. }
  39763. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  39764. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  39765. return;
  39766. }
  39767. if (info.isFourCC) {
  39768. fourCC = header[off_pfFourCC];
  39769. switch (fourCC) {
  39770. case FOURCC_DXT1:
  39771. blockBytes = 8;
  39772. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39773. break;
  39774. case FOURCC_DXT3:
  39775. blockBytes = 16;
  39776. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39777. break;
  39778. case FOURCC_DXT5:
  39779. blockBytes = 16;
  39780. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39781. break;
  39782. default:
  39783. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  39784. return;
  39785. }
  39786. }
  39787. mipmapCount = 1;
  39788. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  39789. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39790. }
  39791. var bpp = header[off_RGBbpp];
  39792. for (var face = 0; face < faces; face++) {
  39793. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  39794. width = header[off_width];
  39795. height = header[off_height];
  39796. dataOffset = header[off_size] + 4;
  39797. for (i = 0; i < mipmapCount; ++i) {
  39798. if (info.isRGB) {
  39799. if (bpp === 24) {
  39800. dataLength = width * height * 3;
  39801. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39802. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  39803. }
  39804. else {
  39805. dataLength = width * height * 4;
  39806. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39807. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  39808. }
  39809. }
  39810. else if (info.isLuminance) {
  39811. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  39812. var unpaddedRowSize = width;
  39813. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  39814. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  39815. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39816. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  39817. }
  39818. else {
  39819. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  39820. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  39821. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  39822. }
  39823. dataOffset += dataLength;
  39824. width *= 0.5;
  39825. height *= 0.5;
  39826. width = Math.max(1.0, width);
  39827. height = Math.max(1.0, height);
  39828. }
  39829. }
  39830. };
  39831. return DDSTools;
  39832. }());
  39833. Internals.DDSTools = DDSTools;
  39834. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39835. })(BABYLON || (BABYLON = {}));
  39836. var BABYLON;
  39837. (function (BABYLON) {
  39838. var CannonJSPlugin = (function () {
  39839. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  39840. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  39841. if (iterations === void 0) { iterations = 10; }
  39842. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  39843. this.name = "CannonJSPlugin";
  39844. this._physicsMaterials = [];
  39845. this._fixedTimeStep = 1 / 60;
  39846. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39847. this._currentCollisionGroup = 2;
  39848. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  39849. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  39850. this._tmpPosition = BABYLON.Vector3.Zero();
  39851. this._tmpQuaternion = new BABYLON.Quaternion();
  39852. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  39853. this._tmpDeltaRotation = new BABYLON.Quaternion();
  39854. this._tmpUnityRotation = new BABYLON.Quaternion();
  39855. if (!this.isSupported()) {
  39856. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  39857. return;
  39858. }
  39859. this.world = new CANNON.World();
  39860. this.world.broadphase = new CANNON.NaiveBroadphase();
  39861. this.world.solver.iterations = iterations;
  39862. }
  39863. CannonJSPlugin.prototype.setGravity = function (gravity) {
  39864. this.world.gravity.copy(gravity);
  39865. };
  39866. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  39867. this._fixedTimeStep = timeStep;
  39868. };
  39869. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  39870. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  39871. };
  39872. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39873. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39874. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39875. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39876. };
  39877. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39878. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39879. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39880. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39881. };
  39882. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39883. //parent-child relationship. Does this impostor has a parent impostor?
  39884. if (impostor.parent) {
  39885. if (impostor.physicsBody) {
  39886. this.removePhysicsBody(impostor);
  39887. //TODO is that needed?
  39888. impostor.forceUpdate();
  39889. }
  39890. return;
  39891. }
  39892. //should a new body be created for this impostor?
  39893. if (impostor.isBodyInitRequired()) {
  39894. var shape = this._createShape(impostor);
  39895. //unregister events, if body is being changed
  39896. var oldBody = impostor.physicsBody;
  39897. if (oldBody) {
  39898. this.removePhysicsBody(impostor);
  39899. }
  39900. //create the body and material
  39901. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  39902. var bodyCreationObject = {
  39903. mass: impostor.getParam("mass"),
  39904. material: material
  39905. };
  39906. // A simple extend, in case native options were used.
  39907. var nativeOptions = impostor.getParam("nativeOptions");
  39908. for (var key in nativeOptions) {
  39909. if (nativeOptions.hasOwnProperty(key)) {
  39910. bodyCreationObject[key] = nativeOptions[key];
  39911. }
  39912. }
  39913. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  39914. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  39915. this.world.addEventListener("preStep", impostor.beforeStep);
  39916. this.world.addEventListener("postStep", impostor.afterStep);
  39917. impostor.physicsBody.addShape(shape);
  39918. this.world.add(impostor.physicsBody);
  39919. //try to keep the body moving in the right direction by taking old properties.
  39920. //Should be tested!
  39921. if (oldBody) {
  39922. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  39923. impostor.physicsBody[param].copy(oldBody[param]);
  39924. });
  39925. }
  39926. this._processChildMeshes(impostor);
  39927. }
  39928. //now update the body's transformation
  39929. this._updatePhysicsBodyTransformation(impostor);
  39930. };
  39931. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  39932. var _this = this;
  39933. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  39934. if (meshChildren.length) {
  39935. var processMesh = function (localPosition, mesh) {
  39936. var childImpostor = mesh.getPhysicsImpostor();
  39937. if (childImpostor) {
  39938. var parent = childImpostor.parent;
  39939. if (parent !== mainImpostor) {
  39940. var localPosition = mesh.position;
  39941. if (childImpostor.physicsBody) {
  39942. _this.removePhysicsBody(childImpostor);
  39943. childImpostor.physicsBody = null;
  39944. }
  39945. childImpostor.parent = mainImpostor;
  39946. childImpostor.resetUpdateFlags();
  39947. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  39948. //Add the mass of the children.
  39949. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  39950. }
  39951. }
  39952. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  39953. };
  39954. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  39955. }
  39956. };
  39957. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  39958. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  39959. this.world.removeEventListener("preStep", impostor.beforeStep);
  39960. this.world.removeEventListener("postStep", impostor.afterStep);
  39961. this.world.remove(impostor.physicsBody);
  39962. };
  39963. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  39964. var mainBody = impostorJoint.mainImpostor.physicsBody;
  39965. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  39966. if (!mainBody || !connectedBody) {
  39967. return;
  39968. }
  39969. var constraint;
  39970. var jointData = impostorJoint.joint.jointData;
  39971. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39972. var constraintData = {
  39973. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  39974. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  39975. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  39976. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  39977. maxForce: jointData.nativeParams.maxForce,
  39978. collideConnected: !!jointData.collision
  39979. };
  39980. //Not needed, Cannon has a collideConnected flag
  39981. /*if (!jointData.collision) {
  39982. //add 1st body to a collision group of its own, if it is not in 1
  39983. if (mainBody.collisionFilterGroup === 1) {
  39984. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  39985. this._currentCollisionGroup <<= 1;
  39986. }
  39987. if (connectedBody.collisionFilterGroup === 1) {
  39988. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  39989. this._currentCollisionGroup <<= 1;
  39990. }
  39991. //add their mask to the collisionFilterMask of each other:
  39992. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  39993. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  39994. }*/
  39995. switch (impostorJoint.joint.type) {
  39996. case BABYLON.PhysicsJoint.HingeJoint:
  39997. case BABYLON.PhysicsJoint.Hinge2Joint:
  39998. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  39999. break;
  40000. case BABYLON.PhysicsJoint.DistanceJoint:
  40001. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  40002. break;
  40003. case BABYLON.PhysicsJoint.SpringJoint:
  40004. var springData = jointData;
  40005. constraint = new CANNON.Spring(mainBody, connectedBody, {
  40006. restLength: springData.length,
  40007. stiffness: springData.stiffness,
  40008. damping: springData.damping,
  40009. localAnchorA: constraintData.pivotA,
  40010. localAnchorB: constraintData.pivotB
  40011. });
  40012. break;
  40013. case BABYLON.PhysicsJoint.LockJoint:
  40014. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  40015. break;
  40016. case BABYLON.PhysicsJoint.PointToPointJoint:
  40017. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40018. default:
  40019. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  40020. break;
  40021. }
  40022. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  40023. constraint.collideConnected = !!jointData.collision;
  40024. impostorJoint.joint.physicsJoint = constraint;
  40025. //don't add spring as constraint, as it is not one.
  40026. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  40027. this.world.addConstraint(constraint);
  40028. }
  40029. else {
  40030. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  40031. constraint.applyForce();
  40032. });
  40033. }
  40034. };
  40035. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40036. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  40037. };
  40038. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  40039. var index;
  40040. var mat;
  40041. for (index = 0; index < this._physicsMaterials.length; index++) {
  40042. mat = this._physicsMaterials[index];
  40043. if (mat.friction === friction && mat.restitution === restitution) {
  40044. return mat;
  40045. }
  40046. }
  40047. var currentMat = new CANNON.Material(name);
  40048. currentMat.friction = friction;
  40049. currentMat.restitution = restitution;
  40050. this._physicsMaterials.push(currentMat);
  40051. return currentMat;
  40052. };
  40053. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  40054. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  40055. };
  40056. CannonJSPlugin.prototype._createShape = function (impostor) {
  40057. var object = impostor.object;
  40058. var returnValue;
  40059. var extendSize = impostor.getObjectExtendSize();
  40060. switch (impostor.type) {
  40061. case BABYLON.PhysicsEngine.SphereImpostor:
  40062. var radiusX = extendSize.x;
  40063. var radiusY = extendSize.y;
  40064. var radiusZ = extendSize.z;
  40065. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40066. break;
  40067. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40068. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40069. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40070. break;
  40071. case BABYLON.PhysicsImpostor.BoxImpostor:
  40072. var box = extendSize.scale(0.5);
  40073. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40074. break;
  40075. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40076. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40077. returnValue = new CANNON.Plane();
  40078. break;
  40079. case BABYLON.PhysicsImpostor.MeshImpostor:
  40080. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40081. var rawFaces = object.getIndices ? object.getIndices() : [];
  40082. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40083. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40084. break;
  40085. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40086. returnValue = this._createHeightmap(object);
  40087. break;
  40088. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40089. returnValue = new CANNON.Particle();
  40090. break;
  40091. }
  40092. return returnValue;
  40093. };
  40094. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40095. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40096. var matrix = [];
  40097. //For now pointDepth will not be used and will be automatically calculated.
  40098. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40099. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40100. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40101. var elementSize = dim * 2 / arraySize;
  40102. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40103. for (var i = 0; i < pos.length; i = i + 3) {
  40104. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40105. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40106. var y = pos[i + 1] + minY;
  40107. if (!matrix[x]) {
  40108. matrix[x] = [];
  40109. }
  40110. if (!matrix[x][z]) {
  40111. matrix[x][z] = y;
  40112. }
  40113. matrix[x][z] = Math.max(y, matrix[x][z]);
  40114. }
  40115. for (var x = 0; x <= arraySize; ++x) {
  40116. if (!matrix[x]) {
  40117. var loc = 1;
  40118. while (!matrix[(x + loc) % arraySize]) {
  40119. loc++;
  40120. }
  40121. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40122. }
  40123. for (var z = 0; z <= arraySize; ++z) {
  40124. if (!matrix[x][z]) {
  40125. var loc = 1;
  40126. var newValue;
  40127. while (newValue === undefined) {
  40128. newValue = matrix[x][(z + loc++) % arraySize];
  40129. }
  40130. matrix[x][z] = newValue;
  40131. }
  40132. }
  40133. }
  40134. var shape = new CANNON.Heightfield(matrix, {
  40135. elementSize: elementSize
  40136. });
  40137. //For future reference, needed for body transformation
  40138. shape.minY = minY;
  40139. return shape;
  40140. };
  40141. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40142. var object = impostor.object;
  40143. //make sure it is updated...
  40144. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40145. // The delta between the mesh position and the mesh bounding box center
  40146. var center = impostor.getObjectCenter();
  40147. var extendSize = impostor.getObjectExtendSize();
  40148. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40149. this._tmpPosition.copyFrom(center);
  40150. var quaternion = object.rotationQuaternion;
  40151. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40152. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40153. //-90 DEG in X, precalculated
  40154. quaternion = quaternion.multiply(this._minus90X);
  40155. //Invert! (Precalculated, 90 deg in X)
  40156. //No need to clone. this will never change.
  40157. impostor.setDeltaRotation(this._plus90X);
  40158. }
  40159. //If it is a heightfield, if should be centered.
  40160. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40161. var mesh = object;
  40162. //calculate the correct body position:
  40163. var rotationQuaternion = mesh.rotationQuaternion;
  40164. mesh.rotationQuaternion = this._tmpUnityRotation;
  40165. mesh.computeWorldMatrix(true);
  40166. //get original center with no rotation
  40167. var c = center.clone();
  40168. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40169. //rotation is back
  40170. mesh.rotationQuaternion = rotationQuaternion;
  40171. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40172. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40173. mesh.setPivotMatrix(p);
  40174. mesh.computeWorldMatrix(true);
  40175. //calculate the translation
  40176. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40177. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40178. //add it inverted to the delta
  40179. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40180. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40181. mesh.setPivotMatrix(oldPivot);
  40182. mesh.computeWorldMatrix(true);
  40183. }
  40184. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40185. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40186. this._tmpPosition.copyFrom(object.position);
  40187. }
  40188. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40189. //Now update the impostor object
  40190. impostor.physicsBody.position.copy(this._tmpPosition);
  40191. impostor.physicsBody.quaternion.copy(quaternion);
  40192. };
  40193. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40194. impostor.object.position.copyFrom(impostor.physicsBody.position);
  40195. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  40196. };
  40197. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40198. impostor.physicsBody.position.copy(newPosition);
  40199. impostor.physicsBody.quaternion.copy(newRotation);
  40200. };
  40201. CannonJSPlugin.prototype.isSupported = function () {
  40202. return window.CANNON !== undefined;
  40203. };
  40204. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40205. impostor.physicsBody.velocity.copy(velocity);
  40206. };
  40207. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40208. impostor.physicsBody.angularVelocity.copy(velocity);
  40209. };
  40210. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40211. var v = impostor.physicsBody.velocity;
  40212. if (!v)
  40213. return null;
  40214. return new BABYLON.Vector3(v.x, v.y, v.z);
  40215. };
  40216. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40217. var v = impostor.physicsBody.angularVelocity;
  40218. if (!v)
  40219. return null;
  40220. return new BABYLON.Vector3(v.x, v.y, v.z);
  40221. };
  40222. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40223. impostor.physicsBody.mass = mass;
  40224. impostor.physicsBody.updateMassProperties();
  40225. };
  40226. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  40227. impostor.physicsBody.sleep();
  40228. };
  40229. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  40230. impostor.physicsBody.wakeUp();
  40231. };
  40232. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40233. joint.physicsJoint.distance = maxDistance;
  40234. };
  40235. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  40236. if (!motorIndex) {
  40237. joint.physicsJoint.enableMotor();
  40238. }
  40239. };
  40240. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  40241. if (!motorIndex) {
  40242. joint.physicsJoint.disableMotor();
  40243. }
  40244. };
  40245. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40246. if (!motorIndex) {
  40247. joint.physicsJoint.enableMotor();
  40248. joint.physicsJoint.setMotorSpeed(speed);
  40249. if (maxForce) {
  40250. this.setLimit(joint, maxForce);
  40251. }
  40252. }
  40253. };
  40254. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  40255. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  40256. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  40257. };
  40258. CannonJSPlugin.prototype.dispose = function () {
  40259. //nothing to do, actually.
  40260. };
  40261. return CannonJSPlugin;
  40262. }());
  40263. BABYLON.CannonJSPlugin = CannonJSPlugin;
  40264. })(BABYLON || (BABYLON = {}));
  40265. var BABYLON;
  40266. (function (BABYLON) {
  40267. var OimoJSPlugin = (function () {
  40268. function OimoJSPlugin(iterations) {
  40269. this.name = "OimoJSPlugin";
  40270. this._tmpImpostorsArray = [];
  40271. this._tmpPositionVector = BABYLON.Vector3.Zero();
  40272. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  40273. this.world.worldscale(1);
  40274. this.world.clear();
  40275. //making sure no stats are calculated
  40276. this.world.isNoStat = true;
  40277. }
  40278. OimoJSPlugin.prototype.setGravity = function (gravity) {
  40279. this.world.gravity.copy(gravity);
  40280. };
  40281. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  40282. this.world.timeStep = timeStep;
  40283. };
  40284. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  40285. var _this = this;
  40286. impostors.forEach(function (impostor) {
  40287. impostor.beforeStep();
  40288. });
  40289. this.world.step();
  40290. impostors.forEach(function (impostor) {
  40291. impostor.afterStep();
  40292. //update the ordered impostors array
  40293. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  40294. });
  40295. //check for collisions
  40296. var contact = this.world.contacts;
  40297. while (contact !== null) {
  40298. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  40299. contact = contact.next;
  40300. continue;
  40301. }
  40302. //is this body colliding with any other? get the impostor
  40303. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  40304. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  40305. if (!mainImpostor || !collidingImpostor) {
  40306. contact = contact.next;
  40307. continue;
  40308. }
  40309. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  40310. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  40311. contact = contact.next;
  40312. }
  40313. };
  40314. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40315. var mass = impostor.physicsBody.massInfo.mass;
  40316. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  40317. };
  40318. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40319. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  40320. this.applyImpulse(impostor, force, contactPoint);
  40321. };
  40322. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40323. var _this = this;
  40324. //parent-child relationship. Does this impostor has a parent impostor?
  40325. if (impostor.parent) {
  40326. if (impostor.physicsBody) {
  40327. this.removePhysicsBody(impostor);
  40328. //TODO is that needed?
  40329. impostor.forceUpdate();
  40330. }
  40331. return;
  40332. }
  40333. if (impostor.isBodyInitRequired()) {
  40334. var bodyConfig = {
  40335. name: impostor.uniqueId,
  40336. //Oimo must have mass, also for static objects.
  40337. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  40338. size: [],
  40339. type: [],
  40340. pos: [],
  40341. rot: [],
  40342. move: impostor.getParam("mass") !== 0,
  40343. //Supporting older versions of Oimo
  40344. world: this.world
  40345. };
  40346. var impostors = [impostor];
  40347. var addToArray = function (parent) {
  40348. if (!parent.getChildMeshes)
  40349. return;
  40350. parent.getChildMeshes().forEach(function (m) {
  40351. if (m.physicsImpostor) {
  40352. impostors.push(m.physicsImpostor);
  40353. m.physicsImpostor._init();
  40354. }
  40355. });
  40356. };
  40357. addToArray(impostor.object);
  40358. var checkWithEpsilon_1 = function (value) {
  40359. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  40360. };
  40361. impostors.forEach(function (i) {
  40362. //get the correct bounding box
  40363. var oldQuaternion = i.object.rotationQuaternion;
  40364. var rot = new OIMO.Euler().setFromQuaternion({
  40365. x: impostor.object.rotationQuaternion.x,
  40366. y: impostor.object.rotationQuaternion.y,
  40367. z: impostor.object.rotationQuaternion.z,
  40368. s: impostor.object.rotationQuaternion.w
  40369. });
  40370. var extendSize = i.getObjectExtendSize();
  40371. if (i === impostor) {
  40372. var center = impostor.getObjectCenter();
  40373. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  40374. //Can also use Array.prototype.push.apply
  40375. bodyConfig.pos.push(center.x);
  40376. bodyConfig.pos.push(center.y);
  40377. bodyConfig.pos.push(center.z);
  40378. //tmp solution
  40379. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  40380. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  40381. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  40382. }
  40383. else {
  40384. bodyConfig.pos.push(i.object.position.x);
  40385. bodyConfig.pos.push(i.object.position.y);
  40386. bodyConfig.pos.push(i.object.position.z);
  40387. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  40388. bodyConfig.rot.push(0);
  40389. bodyConfig.rot.push(0);
  40390. bodyConfig.rot.push(0);
  40391. }
  40392. // register mesh
  40393. switch (i.type) {
  40394. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40395. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  40396. case BABYLON.PhysicsImpostor.SphereImpostor:
  40397. var radiusX = extendSize.x;
  40398. var radiusY = extendSize.y;
  40399. var radiusZ = extendSize.z;
  40400. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  40401. bodyConfig.type.push('sphere');
  40402. //due to the way oimo works with compounds, add 3 times
  40403. bodyConfig.size.push(size);
  40404. bodyConfig.size.push(size);
  40405. bodyConfig.size.push(size);
  40406. break;
  40407. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40408. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  40409. var sizeY = checkWithEpsilon_1(extendSize.y);
  40410. bodyConfig.type.push('cylinder');
  40411. bodyConfig.size.push(sizeX);
  40412. bodyConfig.size.push(sizeY);
  40413. //due to the way oimo works with compounds, add one more value.
  40414. bodyConfig.size.push(sizeY);
  40415. break;
  40416. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40417. case BABYLON.PhysicsImpostor.BoxImpostor:
  40418. default:
  40419. var sizeX = checkWithEpsilon_1(extendSize.x);
  40420. var sizeY = checkWithEpsilon_1(extendSize.y);
  40421. var sizeZ = checkWithEpsilon_1(extendSize.z);
  40422. bodyConfig.type.push('box');
  40423. bodyConfig.size.push(sizeX);
  40424. bodyConfig.size.push(sizeY);
  40425. bodyConfig.size.push(sizeZ);
  40426. break;
  40427. }
  40428. //actually not needed, but hey...
  40429. i.object.rotationQuaternion = oldQuaternion;
  40430. });
  40431. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  40432. }
  40433. else {
  40434. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  40435. }
  40436. impostor.setDeltaPosition(this._tmpPositionVector);
  40437. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  40438. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  40439. };
  40440. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40441. //impostor.physicsBody.dispose();
  40442. //Same as : (older oimo versions)
  40443. this.world.removeRigidBody(impostor.physicsBody);
  40444. };
  40445. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40446. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40447. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40448. if (!mainBody || !connectedBody) {
  40449. return;
  40450. }
  40451. var jointData = impostorJoint.joint.jointData;
  40452. var options = jointData.nativeParams || {};
  40453. var type;
  40454. var nativeJointData = {
  40455. body1: mainBody,
  40456. body2: connectedBody,
  40457. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  40458. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  40459. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  40460. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  40461. min: options.min,
  40462. max: options.max,
  40463. collision: options.collision || jointData.collision,
  40464. spring: options.spring,
  40465. //supporting older version of Oimo
  40466. world: this.world
  40467. };
  40468. switch (impostorJoint.joint.type) {
  40469. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40470. type = "jointBall";
  40471. break;
  40472. case BABYLON.PhysicsJoint.SpringJoint:
  40473. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  40474. var springData = jointData;
  40475. nativeJointData.min = springData.length || nativeJointData.min;
  40476. //Max should also be set, just make sure it is at least min
  40477. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  40478. case BABYLON.PhysicsJoint.DistanceJoint:
  40479. type = "jointDistance";
  40480. nativeJointData.max = jointData.maxDistance;
  40481. break;
  40482. case BABYLON.PhysicsJoint.PrismaticJoint:
  40483. type = "jointPrisme";
  40484. break;
  40485. case BABYLON.PhysicsJoint.SliderJoint:
  40486. type = "jointSlide";
  40487. break;
  40488. case BABYLON.PhysicsJoint.WheelJoint:
  40489. type = "jointWheel";
  40490. break;
  40491. case BABYLON.PhysicsJoint.HingeJoint:
  40492. default:
  40493. type = "jointHinge";
  40494. break;
  40495. }
  40496. nativeJointData.type = type;
  40497. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  40498. };
  40499. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40500. //Bug in Oimo prevents us from disposing a joint in the playground
  40501. //joint.joint.physicsJoint.dispose();
  40502. //So we will bruteforce it!
  40503. try {
  40504. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  40505. }
  40506. catch (e) {
  40507. BABYLON.Tools.Warn(e);
  40508. }
  40509. };
  40510. OimoJSPlugin.prototype.isSupported = function () {
  40511. return OIMO !== undefined;
  40512. };
  40513. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40514. if (!impostor.physicsBody.sleeping) {
  40515. //TODO check that
  40516. if (impostor.physicsBody.shapes.next) {
  40517. var parentShape = this._getLastShape(impostor.physicsBody);
  40518. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  40519. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  40520. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  40521. }
  40522. else {
  40523. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  40524. }
  40525. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  40526. impostor.object.rotationQuaternion.normalize();
  40527. }
  40528. };
  40529. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40530. var body = impostor.physicsBody;
  40531. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  40532. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  40533. body.syncShapes();
  40534. body.awake();
  40535. };
  40536. OimoJSPlugin.prototype._getLastShape = function (body) {
  40537. var lastShape = body.shapes;
  40538. while (lastShape.next) {
  40539. lastShape = lastShape.next;
  40540. }
  40541. return lastShape;
  40542. };
  40543. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40544. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  40545. };
  40546. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40547. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  40548. };
  40549. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40550. var v = impostor.physicsBody.linearVelocity;
  40551. if (!v)
  40552. return null;
  40553. return new BABYLON.Vector3(v.x, v.y, v.z);
  40554. };
  40555. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40556. var v = impostor.physicsBody.angularVelocity;
  40557. if (!v)
  40558. return null;
  40559. return new BABYLON.Vector3(v.x, v.y, v.z);
  40560. };
  40561. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40562. var staticBody = mass === 0;
  40563. //this will actually set the body's density and not its mass.
  40564. //But this is how oimo treats the mass variable.
  40565. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  40566. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  40567. };
  40568. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  40569. impostor.physicsBody.sleep();
  40570. };
  40571. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  40572. impostor.physicsBody.awake();
  40573. };
  40574. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40575. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  40576. if (minDistance !== void 0) {
  40577. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  40578. }
  40579. };
  40580. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40581. //TODO separate rotational and transational motors.
  40582. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40583. if (motor) {
  40584. motor.setMotor(speed, maxForce);
  40585. }
  40586. };
  40587. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  40588. //TODO separate rotational and transational motors.
  40589. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40590. if (motor) {
  40591. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  40592. }
  40593. };
  40594. OimoJSPlugin.prototype.dispose = function () {
  40595. this.world.clear();
  40596. };
  40597. return OimoJSPlugin;
  40598. }());
  40599. BABYLON.OimoJSPlugin = OimoJSPlugin;
  40600. })(BABYLON || (BABYLON = {}));
  40601. var BABYLON;
  40602. (function (BABYLON) {
  40603. var DisplayPassPostProcess = (function (_super) {
  40604. __extends(DisplayPassPostProcess, _super);
  40605. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  40606. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  40607. }
  40608. return DisplayPassPostProcess;
  40609. }(BABYLON.PostProcess));
  40610. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  40611. })(BABYLON || (BABYLON = {}));
  40612. var BABYLON;
  40613. (function (BABYLON) {
  40614. var SimplificationSettings = (function () {
  40615. function SimplificationSettings(quality, distance, optimizeMesh) {
  40616. this.quality = quality;
  40617. this.distance = distance;
  40618. this.optimizeMesh = optimizeMesh;
  40619. }
  40620. return SimplificationSettings;
  40621. }());
  40622. BABYLON.SimplificationSettings = SimplificationSettings;
  40623. var SimplificationQueue = (function () {
  40624. function SimplificationQueue() {
  40625. this.running = false;
  40626. this._simplificationArray = [];
  40627. }
  40628. SimplificationQueue.prototype.addTask = function (task) {
  40629. this._simplificationArray.push(task);
  40630. };
  40631. SimplificationQueue.prototype.executeNext = function () {
  40632. var task = this._simplificationArray.pop();
  40633. if (task) {
  40634. this.running = true;
  40635. this.runSimplification(task);
  40636. }
  40637. else {
  40638. this.running = false;
  40639. }
  40640. };
  40641. SimplificationQueue.prototype.runSimplification = function (task) {
  40642. var _this = this;
  40643. if (task.parallelProcessing) {
  40644. //parallel simplifier
  40645. task.settings.forEach(function (setting) {
  40646. var simplifier = _this.getSimplifier(task);
  40647. simplifier.simplify(setting, function (newMesh) {
  40648. task.mesh.addLODLevel(setting.distance, newMesh);
  40649. newMesh.isVisible = true;
  40650. //check if it is the last
  40651. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  40652. //all done, run the success callback.
  40653. task.successCallback();
  40654. }
  40655. _this.executeNext();
  40656. });
  40657. });
  40658. }
  40659. else {
  40660. //single simplifier.
  40661. var simplifier = this.getSimplifier(task);
  40662. var runDecimation = function (setting, callback) {
  40663. simplifier.simplify(setting, function (newMesh) {
  40664. task.mesh.addLODLevel(setting.distance, newMesh);
  40665. newMesh.isVisible = true;
  40666. //run the next quality level
  40667. callback();
  40668. });
  40669. };
  40670. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  40671. runDecimation(task.settings[loop.index], function () {
  40672. loop.executeNext();
  40673. });
  40674. }, function () {
  40675. //execution ended, run the success callback.
  40676. if (task.successCallback) {
  40677. task.successCallback();
  40678. }
  40679. _this.executeNext();
  40680. });
  40681. }
  40682. };
  40683. SimplificationQueue.prototype.getSimplifier = function (task) {
  40684. switch (task.simplificationType) {
  40685. case SimplificationType.QUADRATIC:
  40686. default:
  40687. return new QuadraticErrorSimplification(task.mesh);
  40688. }
  40689. };
  40690. return SimplificationQueue;
  40691. }());
  40692. BABYLON.SimplificationQueue = SimplificationQueue;
  40693. /**
  40694. * The implemented types of simplification.
  40695. * At the moment only Quadratic Error Decimation is implemented.
  40696. */
  40697. (function (SimplificationType) {
  40698. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  40699. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  40700. var SimplificationType = BABYLON.SimplificationType;
  40701. var DecimationTriangle = (function () {
  40702. function DecimationTriangle(vertices) {
  40703. this.vertices = vertices;
  40704. this.error = new Array(4);
  40705. this.deleted = false;
  40706. this.isDirty = false;
  40707. this.deletePending = false;
  40708. this.borderFactor = 0;
  40709. }
  40710. return DecimationTriangle;
  40711. }());
  40712. BABYLON.DecimationTriangle = DecimationTriangle;
  40713. var DecimationVertex = (function () {
  40714. function DecimationVertex(position, id) {
  40715. this.position = position;
  40716. this.id = id;
  40717. this.isBorder = true;
  40718. this.q = new QuadraticMatrix();
  40719. this.triangleCount = 0;
  40720. this.triangleStart = 0;
  40721. this.originalOffsets = [];
  40722. }
  40723. DecimationVertex.prototype.updatePosition = function (newPosition) {
  40724. this.position.copyFrom(newPosition);
  40725. };
  40726. return DecimationVertex;
  40727. }());
  40728. BABYLON.DecimationVertex = DecimationVertex;
  40729. var QuadraticMatrix = (function () {
  40730. function QuadraticMatrix(data) {
  40731. this.data = new Array(10);
  40732. for (var i = 0; i < 10; ++i) {
  40733. if (data && data[i]) {
  40734. this.data[i] = data[i];
  40735. }
  40736. else {
  40737. this.data[i] = 0;
  40738. }
  40739. }
  40740. }
  40741. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  40742. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  40743. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  40744. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  40745. return det;
  40746. };
  40747. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  40748. for (var i = 0; i < 10; ++i) {
  40749. this.data[i] += matrix.data[i];
  40750. }
  40751. };
  40752. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  40753. for (var i = 0; i < 10; ++i) {
  40754. this.data[i] += data[i];
  40755. }
  40756. };
  40757. QuadraticMatrix.prototype.add = function (matrix) {
  40758. var m = new QuadraticMatrix();
  40759. for (var i = 0; i < 10; ++i) {
  40760. m.data[i] = this.data[i] + matrix.data[i];
  40761. }
  40762. return m;
  40763. };
  40764. QuadraticMatrix.FromData = function (a, b, c, d) {
  40765. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  40766. };
  40767. //returning an array to avoid garbage collection
  40768. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  40769. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  40770. };
  40771. return QuadraticMatrix;
  40772. }());
  40773. BABYLON.QuadraticMatrix = QuadraticMatrix;
  40774. var Reference = (function () {
  40775. function Reference(vertexId, triangleId) {
  40776. this.vertexId = vertexId;
  40777. this.triangleId = triangleId;
  40778. }
  40779. return Reference;
  40780. }());
  40781. BABYLON.Reference = Reference;
  40782. /**
  40783. * An implementation of the Quadratic Error simplification algorithm.
  40784. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  40785. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  40786. * @author RaananW
  40787. */
  40788. var QuadraticErrorSimplification = (function () {
  40789. function QuadraticErrorSimplification(_mesh) {
  40790. this._mesh = _mesh;
  40791. this.initialized = false;
  40792. this.syncIterations = 5000;
  40793. this.aggressiveness = 7;
  40794. this.decimationIterations = 100;
  40795. this.boundingBoxEpsilon = BABYLON.Epsilon;
  40796. }
  40797. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  40798. var _this = this;
  40799. this.initDecimatedMesh();
  40800. //iterating through the submeshes array, one after the other.
  40801. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  40802. _this.initWithMesh(loop.index, function () {
  40803. _this.runDecimation(settings, loop.index, function () {
  40804. loop.executeNext();
  40805. });
  40806. }, settings.optimizeMesh);
  40807. }, function () {
  40808. setTimeout(function () {
  40809. successCallback(_this._reconstructedMesh);
  40810. }, 0);
  40811. });
  40812. };
  40813. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  40814. var _this = this;
  40815. var gCount = 0;
  40816. triangle.vertices.forEach(function (vertex) {
  40817. var count = 0;
  40818. var vPos = vertex.position;
  40819. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  40820. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  40821. ++count;
  40822. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  40823. ++count;
  40824. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  40825. ++count;
  40826. if (count > 1) {
  40827. ++gCount;
  40828. }
  40829. ;
  40830. });
  40831. if (gCount > 1) {
  40832. console.log(triangle, gCount);
  40833. }
  40834. return gCount > 1;
  40835. };
  40836. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  40837. var _this = this;
  40838. var targetCount = ~~(this.triangles.length * settings.quality);
  40839. var deletedTriangles = 0;
  40840. var triangleCount = this.triangles.length;
  40841. var iterationFunction = function (iteration, callback) {
  40842. setTimeout(function () {
  40843. if (iteration % 5 === 0) {
  40844. _this.updateMesh(iteration === 0);
  40845. }
  40846. for (var i = 0; i < _this.triangles.length; ++i) {
  40847. _this.triangles[i].isDirty = false;
  40848. }
  40849. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  40850. var trianglesIterator = function (i) {
  40851. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  40852. var t = _this.triangles[tIdx];
  40853. if (!t)
  40854. return;
  40855. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  40856. return;
  40857. }
  40858. for (var j = 0; j < 3; ++j) {
  40859. if (t.error[j] < threshold) {
  40860. var deleted0 = [];
  40861. var deleted1 = [];
  40862. var v0 = t.vertices[j];
  40863. var v1 = t.vertices[(j + 1) % 3];
  40864. if (v0.isBorder || v1.isBorder)
  40865. continue;
  40866. var p = BABYLON.Vector3.Zero();
  40867. var n = BABYLON.Vector3.Zero();
  40868. var uv = BABYLON.Vector2.Zero();
  40869. var color = new BABYLON.Color4(0, 0, 0, 1);
  40870. _this.calculateError(v0, v1, p, n, uv, color);
  40871. var delTr = [];
  40872. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  40873. continue;
  40874. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  40875. continue;
  40876. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  40877. continue;
  40878. var uniqueArray = [];
  40879. delTr.forEach(function (deletedT) {
  40880. if (uniqueArray.indexOf(deletedT) === -1) {
  40881. deletedT.deletePending = true;
  40882. uniqueArray.push(deletedT);
  40883. }
  40884. });
  40885. if (uniqueArray.length % 2 !== 0) {
  40886. continue;
  40887. }
  40888. v0.q = v1.q.add(v0.q);
  40889. v0.updatePosition(p);
  40890. var tStart = _this.references.length;
  40891. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  40892. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  40893. var tCount = _this.references.length - tStart;
  40894. if (tCount <= v0.triangleCount) {
  40895. if (tCount) {
  40896. for (var c = 0; c < tCount; c++) {
  40897. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  40898. }
  40899. }
  40900. }
  40901. else {
  40902. v0.triangleStart = tStart;
  40903. }
  40904. v0.triangleCount = tCount;
  40905. break;
  40906. }
  40907. }
  40908. };
  40909. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  40910. }, 0);
  40911. };
  40912. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  40913. if (triangleCount - deletedTriangles <= targetCount)
  40914. loop.breakLoop();
  40915. else {
  40916. iterationFunction(loop.index, function () {
  40917. loop.executeNext();
  40918. });
  40919. }
  40920. }, function () {
  40921. setTimeout(function () {
  40922. //reconstruct this part of the mesh
  40923. _this.reconstructMesh(submeshIndex);
  40924. successCallback();
  40925. }, 0);
  40926. });
  40927. };
  40928. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  40929. var _this = this;
  40930. this.vertices = [];
  40931. this.triangles = [];
  40932. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40933. var indices = this._mesh.getIndices();
  40934. var submesh = this._mesh.subMeshes[submeshIndex];
  40935. var findInVertices = function (positionToSearch) {
  40936. if (optimizeMesh) {
  40937. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  40938. if (_this.vertices[ii].position.equals(positionToSearch)) {
  40939. return _this.vertices[ii];
  40940. }
  40941. }
  40942. }
  40943. return null;
  40944. };
  40945. var vertexReferences = [];
  40946. var vertexInit = function (i) {
  40947. var offset = i + submesh.verticesStart;
  40948. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  40949. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  40950. vertex.originalOffsets.push(offset);
  40951. if (vertex.id === _this.vertices.length) {
  40952. _this.vertices.push(vertex);
  40953. }
  40954. vertexReferences.push(vertex.id);
  40955. };
  40956. //var totalVertices = mesh.getTotalVertices();
  40957. var totalVertices = submesh.verticesCount;
  40958. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  40959. var indicesInit = function (i) {
  40960. var offset = (submesh.indexStart / 3) + i;
  40961. var pos = (offset * 3);
  40962. var i0 = indices[pos + 0];
  40963. var i1 = indices[pos + 1];
  40964. var i2 = indices[pos + 2];
  40965. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  40966. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  40967. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  40968. var triangle = new DecimationTriangle([v0, v1, v2]);
  40969. triangle.originalOffset = pos;
  40970. _this.triangles.push(triangle);
  40971. };
  40972. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  40973. _this.init(callback);
  40974. });
  40975. });
  40976. };
  40977. QuadraticErrorSimplification.prototype.init = function (callback) {
  40978. var _this = this;
  40979. var triangleInit1 = function (i) {
  40980. var t = _this.triangles[i];
  40981. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  40982. for (var j = 0; j < 3; j++) {
  40983. 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))));
  40984. }
  40985. };
  40986. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  40987. var triangleInit2 = function (i) {
  40988. var t = _this.triangles[i];
  40989. for (var j = 0; j < 3; ++j) {
  40990. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  40991. }
  40992. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  40993. };
  40994. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  40995. _this.initialized = true;
  40996. callback();
  40997. });
  40998. });
  40999. };
  41000. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  41001. var newTriangles = [];
  41002. var i;
  41003. for (i = 0; i < this.vertices.length; ++i) {
  41004. this.vertices[i].triangleCount = 0;
  41005. }
  41006. var t;
  41007. var j;
  41008. for (i = 0; i < this.triangles.length; ++i) {
  41009. if (!this.triangles[i].deleted) {
  41010. t = this.triangles[i];
  41011. for (j = 0; j < 3; ++j) {
  41012. t.vertices[j].triangleCount = 1;
  41013. }
  41014. newTriangles.push(t);
  41015. }
  41016. }
  41017. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  41018. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  41019. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  41020. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  41021. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41022. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41023. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41024. var vertexCount = 0;
  41025. for (i = 0; i < this.vertices.length; ++i) {
  41026. var vertex = this.vertices[i];
  41027. vertex.id = vertexCount;
  41028. if (vertex.triangleCount) {
  41029. vertex.originalOffsets.forEach(function (originalOffset) {
  41030. newPositionData.push(vertex.position.x);
  41031. newPositionData.push(vertex.position.y);
  41032. newPositionData.push(vertex.position.z);
  41033. newNormalData.push(normalData[originalOffset * 3]);
  41034. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  41035. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  41036. if (uvs && uvs.length) {
  41037. newUVsData.push(uvs[(originalOffset * 2)]);
  41038. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  41039. }
  41040. else if (colorsData && colorsData.length) {
  41041. newColorsData.push(colorsData[(originalOffset * 4)]);
  41042. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  41043. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  41044. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  41045. }
  41046. ++vertexCount;
  41047. });
  41048. }
  41049. }
  41050. var startingIndex = this._reconstructedMesh.getTotalIndices();
  41051. var startingVertex = this._reconstructedMesh.getTotalVertices();
  41052. var submeshesArray = this._reconstructedMesh.subMeshes;
  41053. this._reconstructedMesh.subMeshes = [];
  41054. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  41055. var originalIndices = this._mesh.getIndices();
  41056. for (i = 0; i < newTriangles.length; ++i) {
  41057. t = newTriangles[i]; //now get the new referencing point for each vertex
  41058. [0, 1, 2].forEach(function (idx) {
  41059. var id = originalIndices[t.originalOffset + idx];
  41060. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  41061. if (offset < 0)
  41062. offset = 0;
  41063. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41064. });
  41065. }
  41066. //overwriting the old vertex buffers and indices.
  41067. this._reconstructedMesh.setIndices(newIndicesArray);
  41068. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41069. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41070. if (newUVsData.length > 0)
  41071. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41072. if (newColorsData.length > 0)
  41073. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41074. //create submesh
  41075. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41076. if (submeshIndex > 0) {
  41077. this._reconstructedMesh.subMeshes = [];
  41078. submeshesArray.forEach(function (submesh) {
  41079. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41080. });
  41081. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41082. }
  41083. };
  41084. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41085. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41086. this._reconstructedMesh.material = this._mesh.material;
  41087. this._reconstructedMesh.parent = this._mesh.parent;
  41088. this._reconstructedMesh.isVisible = false;
  41089. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41090. };
  41091. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41092. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41093. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41094. if (t.deleted)
  41095. continue;
  41096. var s = this.references[vertex1.triangleStart + i].vertexId;
  41097. var v1 = t.vertices[(s + 1) % 3];
  41098. var v2 = t.vertices[(s + 2) % 3];
  41099. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41100. deletedArray[i] = true;
  41101. delTr.push(t);
  41102. continue;
  41103. }
  41104. var d1 = v1.position.subtract(point);
  41105. d1 = d1.normalize();
  41106. var d2 = v2.position.subtract(point);
  41107. d2 = d2.normalize();
  41108. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41109. return true;
  41110. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41111. deletedArray[i] = false;
  41112. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41113. return true;
  41114. }
  41115. return false;
  41116. };
  41117. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41118. var newDeleted = deletedTriangles;
  41119. for (var i = 0; i < vertex.triangleCount; ++i) {
  41120. var ref = this.references[vertex.triangleStart + i];
  41121. var t = this.triangles[ref.triangleId];
  41122. if (t.deleted)
  41123. continue;
  41124. if (deletedArray[i] && t.deletePending) {
  41125. t.deleted = true;
  41126. newDeleted++;
  41127. continue;
  41128. }
  41129. t.vertices[ref.vertexId] = origVertex;
  41130. t.isDirty = true;
  41131. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41132. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41133. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41134. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41135. this.references.push(ref);
  41136. }
  41137. return newDeleted;
  41138. };
  41139. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41140. for (var i = 0; i < this.vertices.length; ++i) {
  41141. var vCount = [];
  41142. var vId = [];
  41143. var v = this.vertices[i];
  41144. var j;
  41145. for (j = 0; j < v.triangleCount; ++j) {
  41146. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41147. for (var ii = 0; ii < 3; ii++) {
  41148. var ofs = 0;
  41149. var vv = triangle.vertices[ii];
  41150. while (ofs < vCount.length) {
  41151. if (vId[ofs] === vv.id)
  41152. break;
  41153. ++ofs;
  41154. }
  41155. if (ofs === vCount.length) {
  41156. vCount.push(1);
  41157. vId.push(vv.id);
  41158. }
  41159. else {
  41160. vCount[ofs]++;
  41161. }
  41162. }
  41163. }
  41164. for (j = 0; j < vCount.length; ++j) {
  41165. if (vCount[j] === 1) {
  41166. this.vertices[vId[j]].isBorder = true;
  41167. }
  41168. else {
  41169. this.vertices[vId[j]].isBorder = false;
  41170. }
  41171. }
  41172. }
  41173. };
  41174. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41175. if (identifyBorders === void 0) { identifyBorders = false; }
  41176. var i;
  41177. if (!identifyBorders) {
  41178. var newTrianglesVector = [];
  41179. for (i = 0; i < this.triangles.length; ++i) {
  41180. if (!this.triangles[i].deleted) {
  41181. newTrianglesVector.push(this.triangles[i]);
  41182. }
  41183. }
  41184. this.triangles = newTrianglesVector;
  41185. }
  41186. for (i = 0; i < this.vertices.length; ++i) {
  41187. this.vertices[i].triangleCount = 0;
  41188. this.vertices[i].triangleStart = 0;
  41189. }
  41190. var t;
  41191. var j;
  41192. var v;
  41193. for (i = 0; i < this.triangles.length; ++i) {
  41194. t = this.triangles[i];
  41195. for (j = 0; j < 3; ++j) {
  41196. v = t.vertices[j];
  41197. v.triangleCount++;
  41198. }
  41199. }
  41200. var tStart = 0;
  41201. for (i = 0; i < this.vertices.length; ++i) {
  41202. this.vertices[i].triangleStart = tStart;
  41203. tStart += this.vertices[i].triangleCount;
  41204. this.vertices[i].triangleCount = 0;
  41205. }
  41206. var newReferences = new Array(this.triangles.length * 3);
  41207. for (i = 0; i < this.triangles.length; ++i) {
  41208. t = this.triangles[i];
  41209. for (j = 0; j < 3; ++j) {
  41210. v = t.vertices[j];
  41211. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  41212. v.triangleCount++;
  41213. }
  41214. }
  41215. this.references = newReferences;
  41216. if (identifyBorders) {
  41217. this.identifyBorder();
  41218. }
  41219. };
  41220. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  41221. var x = point.x;
  41222. var y = point.y;
  41223. var z = point.z;
  41224. 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
  41225. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  41226. };
  41227. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  41228. var q = vertex1.q.add(vertex2.q);
  41229. var border = vertex1.isBorder && vertex2.isBorder;
  41230. var error = 0;
  41231. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  41232. if (qDet !== 0 && !border) {
  41233. if (!pointResult) {
  41234. pointResult = BABYLON.Vector3.Zero();
  41235. }
  41236. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  41237. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  41238. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  41239. error = this.vertexError(q, pointResult);
  41240. }
  41241. else {
  41242. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  41243. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  41244. var error1 = this.vertexError(q, vertex1.position);
  41245. var error2 = this.vertexError(q, vertex2.position);
  41246. var error3 = this.vertexError(q, p3);
  41247. error = Math.min(error1, error2, error3);
  41248. if (error === error1) {
  41249. if (pointResult) {
  41250. pointResult.copyFrom(vertex1.position);
  41251. }
  41252. }
  41253. else if (error === error2) {
  41254. if (pointResult) {
  41255. pointResult.copyFrom(vertex2.position);
  41256. }
  41257. }
  41258. else {
  41259. if (pointResult) {
  41260. pointResult.copyFrom(p3);
  41261. }
  41262. }
  41263. }
  41264. return error;
  41265. };
  41266. return QuadraticErrorSimplification;
  41267. }());
  41268. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  41269. })(BABYLON || (BABYLON = {}));
  41270. var BABYLON;
  41271. (function (BABYLON) {
  41272. var serializedGeometries = [];
  41273. var serializeGeometry = function (geometry, serializationGeometries) {
  41274. if (serializedGeometries[geometry.id]) {
  41275. return;
  41276. }
  41277. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  41278. serializationGeometries.boxes.push(geometry.serialize());
  41279. }
  41280. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  41281. serializationGeometries.spheres.push(geometry.serialize());
  41282. }
  41283. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  41284. serializationGeometries.cylinders.push(geometry.serialize());
  41285. }
  41286. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  41287. serializationGeometries.toruses.push(geometry.serialize());
  41288. }
  41289. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  41290. serializationGeometries.grounds.push(geometry.serialize());
  41291. }
  41292. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  41293. serializationGeometries.planes.push(geometry.serialize());
  41294. }
  41295. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  41296. serializationGeometries.torusKnots.push(geometry.serialize());
  41297. }
  41298. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  41299. throw new Error("Unknown primitive type");
  41300. }
  41301. else {
  41302. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  41303. }
  41304. serializedGeometries[geometry.id] = true;
  41305. };
  41306. var serializeMesh = function (mesh, serializationScene) {
  41307. var serializationObject = {};
  41308. serializationObject.name = mesh.name;
  41309. serializationObject.id = mesh.id;
  41310. if (BABYLON.Tags.HasTags(mesh)) {
  41311. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  41312. }
  41313. serializationObject.position = mesh.position.asArray();
  41314. if (mesh.rotationQuaternion) {
  41315. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  41316. }
  41317. else if (mesh.rotation) {
  41318. serializationObject.rotation = mesh.rotation.asArray();
  41319. }
  41320. serializationObject.scaling = mesh.scaling.asArray();
  41321. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  41322. serializationObject.isEnabled = mesh.isEnabled();
  41323. serializationObject.isVisible = mesh.isVisible;
  41324. serializationObject.infiniteDistance = mesh.infiniteDistance;
  41325. serializationObject.pickable = mesh.isPickable;
  41326. serializationObject.receiveShadows = mesh.receiveShadows;
  41327. serializationObject.billboardMode = mesh.billboardMode;
  41328. serializationObject.visibility = mesh.visibility;
  41329. serializationObject.checkCollisions = mesh.checkCollisions;
  41330. // Parent
  41331. if (mesh.parent) {
  41332. serializationObject.parentId = mesh.parent.id;
  41333. }
  41334. // Geometry
  41335. var geometry = mesh._geometry;
  41336. if (geometry) {
  41337. var geometryId = geometry.id;
  41338. serializationObject.geometryId = geometryId;
  41339. if (!mesh.getScene().getGeometryByID(geometryId)) {
  41340. // 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
  41341. serializeGeometry(geometry, serializationScene.geometries);
  41342. }
  41343. // SubMeshes
  41344. serializationObject.subMeshes = [];
  41345. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41346. var subMesh = mesh.subMeshes[subIndex];
  41347. serializationObject.subMeshes.push({
  41348. materialIndex: subMesh.materialIndex,
  41349. verticesStart: subMesh.verticesStart,
  41350. verticesCount: subMesh.verticesCount,
  41351. indexStart: subMesh.indexStart,
  41352. indexCount: subMesh.indexCount
  41353. });
  41354. }
  41355. }
  41356. // Material
  41357. if (mesh.material) {
  41358. serializationObject.materialId = mesh.material.id;
  41359. }
  41360. else {
  41361. mesh.material = null;
  41362. }
  41363. // Skeleton
  41364. if (mesh.skeleton) {
  41365. serializationObject.skeletonId = mesh.skeleton.id;
  41366. }
  41367. // Physics
  41368. //TODO implement correct serialization for physics impostors.
  41369. if (mesh.getPhysicsImpostor()) {
  41370. serializationObject.physicsMass = mesh.getPhysicsMass();
  41371. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  41372. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  41373. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  41374. }
  41375. // Instances
  41376. serializationObject.instances = [];
  41377. for (var index = 0; index < mesh.instances.length; index++) {
  41378. var instance = mesh.instances[index];
  41379. var serializationInstance = {
  41380. name: instance.name,
  41381. position: instance.position.asArray(),
  41382. scaling: instance.scaling.asArray()
  41383. };
  41384. if (instance.rotationQuaternion) {
  41385. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  41386. }
  41387. else if (instance.rotation) {
  41388. serializationInstance.rotation = instance.rotation.asArray();
  41389. }
  41390. serializationObject.instances.push(serializationInstance);
  41391. // Animations
  41392. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  41393. serializationInstance.ranges = instance.serializeAnimationRanges();
  41394. }
  41395. // Animations
  41396. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  41397. serializationObject.ranges = mesh.serializeAnimationRanges();
  41398. // Layer mask
  41399. serializationObject.layerMask = mesh.layerMask;
  41400. // Action Manager
  41401. if (mesh.actionManager) {
  41402. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  41403. }
  41404. return serializationObject;
  41405. };
  41406. var finalizeSingleMesh = function (mesh, serializationObject) {
  41407. //only works if the mesh is already loaded
  41408. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41409. //serialize material
  41410. if (mesh.material) {
  41411. if (mesh.material instanceof BABYLON.StandardMaterial) {
  41412. serializationObject.materials = serializationObject.materials || [];
  41413. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41414. serializationObject.materials.push(mesh.material.serialize());
  41415. }
  41416. }
  41417. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  41418. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  41419. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41420. serializationObject.multiMaterials.push(mesh.material.serialize());
  41421. }
  41422. }
  41423. }
  41424. //serialize geometry
  41425. var geometry = mesh._geometry;
  41426. if (geometry) {
  41427. if (!serializationObject.geometries) {
  41428. serializationObject.geometries = {};
  41429. serializationObject.geometries.boxes = [];
  41430. serializationObject.geometries.spheres = [];
  41431. serializationObject.geometries.cylinders = [];
  41432. serializationObject.geometries.toruses = [];
  41433. serializationObject.geometries.grounds = [];
  41434. serializationObject.geometries.planes = [];
  41435. serializationObject.geometries.torusKnots = [];
  41436. serializationObject.geometries.vertexData = [];
  41437. }
  41438. serializeGeometry(geometry, serializationObject.geometries);
  41439. }
  41440. // Skeletons
  41441. if (mesh.skeleton) {
  41442. serializationObject.skeletons = serializationObject.skeletons || [];
  41443. serializationObject.skeletons.push(mesh.skeleton.serialize());
  41444. }
  41445. //serialize the actual mesh
  41446. serializationObject.meshes = serializationObject.meshes || [];
  41447. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41448. }
  41449. };
  41450. var SceneSerializer = (function () {
  41451. function SceneSerializer() {
  41452. }
  41453. SceneSerializer.ClearCache = function () {
  41454. serializedGeometries = [];
  41455. };
  41456. SceneSerializer.Serialize = function (scene) {
  41457. var serializationObject = {};
  41458. // Scene
  41459. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  41460. serializationObject.autoClear = scene.autoClear;
  41461. serializationObject.clearColor = scene.clearColor.asArray();
  41462. serializationObject.ambientColor = scene.ambientColor.asArray();
  41463. serializationObject.gravity = scene.gravity.asArray();
  41464. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  41465. serializationObject.workerCollisions = scene.workerCollisions;
  41466. // Fog
  41467. if (scene.fogMode && scene.fogMode !== 0) {
  41468. serializationObject.fogMode = scene.fogMode;
  41469. serializationObject.fogColor = scene.fogColor.asArray();
  41470. serializationObject.fogStart = scene.fogStart;
  41471. serializationObject.fogEnd = scene.fogEnd;
  41472. serializationObject.fogDensity = scene.fogDensity;
  41473. }
  41474. //Physics
  41475. if (scene.isPhysicsEnabled()) {
  41476. serializationObject.physicsEnabled = true;
  41477. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  41478. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  41479. }
  41480. // Lights
  41481. serializationObject.lights = [];
  41482. var index;
  41483. var light;
  41484. for (index = 0; index < scene.lights.length; index++) {
  41485. light = scene.lights[index];
  41486. serializationObject.lights.push(light.serialize());
  41487. }
  41488. // Cameras
  41489. serializationObject.cameras = [];
  41490. for (index = 0; index < scene.cameras.length; index++) {
  41491. var camera = scene.cameras[index];
  41492. serializationObject.cameras.push(camera.serialize());
  41493. }
  41494. if (scene.activeCamera) {
  41495. serializationObject.activeCameraID = scene.activeCamera.id;
  41496. }
  41497. // Animations
  41498. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  41499. // Materials
  41500. serializationObject.materials = [];
  41501. serializationObject.multiMaterials = [];
  41502. var material;
  41503. for (index = 0; index < scene.materials.length; index++) {
  41504. material = scene.materials[index];
  41505. serializationObject.materials.push(material.serialize());
  41506. }
  41507. // MultiMaterials
  41508. serializationObject.multiMaterials = [];
  41509. for (index = 0; index < scene.multiMaterials.length; index++) {
  41510. var multiMaterial = scene.multiMaterials[index];
  41511. serializationObject.multiMaterials.push(multiMaterial.serialize());
  41512. }
  41513. // Skeletons
  41514. serializationObject.skeletons = [];
  41515. for (index = 0; index < scene.skeletons.length; index++) {
  41516. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  41517. }
  41518. // Geometries
  41519. serializationObject.geometries = {};
  41520. serializationObject.geometries.boxes = [];
  41521. serializationObject.geometries.spheres = [];
  41522. serializationObject.geometries.cylinders = [];
  41523. serializationObject.geometries.toruses = [];
  41524. serializationObject.geometries.grounds = [];
  41525. serializationObject.geometries.planes = [];
  41526. serializationObject.geometries.torusKnots = [];
  41527. serializationObject.geometries.vertexData = [];
  41528. serializedGeometries = [];
  41529. var geometries = scene.getGeometries();
  41530. for (index = 0; index < geometries.length; index++) {
  41531. var geometry = geometries[index];
  41532. if (geometry.isReady()) {
  41533. serializeGeometry(geometry, serializationObject.geometries);
  41534. }
  41535. }
  41536. // Meshes
  41537. serializationObject.meshes = [];
  41538. for (index = 0; index < scene.meshes.length; index++) {
  41539. var abstractMesh = scene.meshes[index];
  41540. if (abstractMesh instanceof BABYLON.Mesh) {
  41541. var mesh = abstractMesh;
  41542. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41543. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41544. }
  41545. }
  41546. }
  41547. // Particles Systems
  41548. serializationObject.particleSystems = [];
  41549. for (index = 0; index < scene.particleSystems.length; index++) {
  41550. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  41551. }
  41552. // Lens flares
  41553. serializationObject.lensFlareSystems = [];
  41554. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  41555. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  41556. }
  41557. // Shadows
  41558. serializationObject.shadowGenerators = [];
  41559. for (index = 0; index < scene.lights.length; index++) {
  41560. light = scene.lights[index];
  41561. var shadowGenerator = light.getShadowGenerator();
  41562. // Only support serialization for official generator so far.
  41563. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  41564. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  41565. }
  41566. }
  41567. // Action Manager
  41568. if (scene.actionManager) {
  41569. serializationObject.actions = scene.actionManager.serialize("scene");
  41570. }
  41571. // Audio
  41572. serializationObject.sounds = [];
  41573. for (index = 0; index < scene.soundTracks.length; index++) {
  41574. var soundtrack = scene.soundTracks[index];
  41575. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  41576. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  41577. }
  41578. }
  41579. return serializationObject;
  41580. };
  41581. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  41582. if (withParents === void 0) { withParents = false; }
  41583. if (withChildren === void 0) { withChildren = false; }
  41584. var serializationObject = {};
  41585. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  41586. if (withParents || withChildren) {
  41587. //deliberate for loop! not for each, appended should be processed as well.
  41588. for (var i = 0; i < toSerialize.length; ++i) {
  41589. if (withChildren) {
  41590. toSerialize[i].getDescendants().forEach(function (node) {
  41591. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  41592. toSerialize.push(node);
  41593. }
  41594. });
  41595. }
  41596. //make sure the array doesn't contain the object already
  41597. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  41598. toSerialize.push(toSerialize[i].parent);
  41599. }
  41600. }
  41601. }
  41602. toSerialize.forEach(function (mesh) {
  41603. finalizeSingleMesh(mesh, serializationObject);
  41604. });
  41605. return serializationObject;
  41606. };
  41607. return SceneSerializer;
  41608. }());
  41609. BABYLON.SceneSerializer = SceneSerializer;
  41610. })(BABYLON || (BABYLON = {}));
  41611. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  41612. // Huge respect for a such great lib.
  41613. // Earcut license:
  41614. // Copyright (c) 2016, Mapbox
  41615. //
  41616. // Permission to use, copy, modify, and/or distribute this software for any purpose
  41617. // with or without fee is hereby granted, provided that the above copyright notice
  41618. // and this permission notice appear in all copies.
  41619. //
  41620. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  41621. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  41622. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  41623. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  41624. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  41625. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  41626. // THIS SOFTWARE.
  41627. var Earcut;
  41628. (function (Earcut) {
  41629. /**
  41630. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  41631. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  41632. * @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).
  41633. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  41634. */
  41635. function earcut(data, holeIndices, dim) {
  41636. dim = dim || 2;
  41637. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  41638. if (!outerNode)
  41639. return triangles;
  41640. var minX, minY, maxX, maxY, x, y, size;
  41641. if (hasHoles)
  41642. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  41643. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  41644. if (data.length > 80 * dim) {
  41645. minX = maxX = data[0];
  41646. minY = maxY = data[1];
  41647. for (var i = dim; i < outerLen; i += dim) {
  41648. x = data[i];
  41649. y = data[i + 1];
  41650. if (x < minX)
  41651. minX = x;
  41652. if (y < minY)
  41653. minY = y;
  41654. if (x > maxX)
  41655. maxX = x;
  41656. if (y > maxY)
  41657. maxY = y;
  41658. }
  41659. // minX, minY and size are later used to transform coords into integers for z-order calculation
  41660. size = Math.max(maxX - minX, maxY - minY);
  41661. }
  41662. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  41663. return triangles;
  41664. }
  41665. Earcut.earcut = earcut;
  41666. // create a circular doubly linked list from polygon points in the specified winding order
  41667. function linkedList(data, start, end, dim, clockwise) {
  41668. var i, last;
  41669. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  41670. for (i = start; i < end; i += dim)
  41671. last = insertNode(i, data[i], data[i + 1], last);
  41672. }
  41673. else {
  41674. for (i = end - dim; i >= start; i -= dim)
  41675. last = insertNode(i, data[i], data[i + 1], last);
  41676. }
  41677. if (last && equals(last, last.next)) {
  41678. removeNode(last);
  41679. last = last.next;
  41680. }
  41681. return last;
  41682. }
  41683. // eliminate colinear or duplicate points
  41684. function filterPoints(start, end) {
  41685. if (!start)
  41686. return start;
  41687. if (!end)
  41688. end = start;
  41689. var p = start, again;
  41690. do {
  41691. again = false;
  41692. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  41693. removeNode(p);
  41694. p = end = p.prev;
  41695. if (p === p.next)
  41696. return null;
  41697. again = true;
  41698. }
  41699. else {
  41700. p = p.next;
  41701. }
  41702. } while (again || p !== end);
  41703. return end;
  41704. }
  41705. // main ear slicing loop which triangulates a polygon (given as a linked list)
  41706. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  41707. if (!ear)
  41708. return;
  41709. // interlink polygon nodes in z-order
  41710. if (!pass && size)
  41711. indexCurve(ear, minX, minY, size);
  41712. var stop = ear, prev, next;
  41713. // iterate through ears, slicing them one by one
  41714. while (ear.prev !== ear.next) {
  41715. prev = ear.prev;
  41716. next = ear.next;
  41717. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  41718. // cut off the triangle
  41719. triangles.push(prev.i / dim);
  41720. triangles.push(ear.i / dim);
  41721. triangles.push(next.i / dim);
  41722. removeNode(ear);
  41723. // skipping the next vertice leads to less sliver triangles
  41724. ear = next.next;
  41725. stop = next.next;
  41726. continue;
  41727. }
  41728. ear = next;
  41729. // if we looped through the whole remaining polygon and can't find any more ears
  41730. if (ear === stop) {
  41731. // try filtering points and slicing again
  41732. if (!pass) {
  41733. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  41734. }
  41735. else if (pass === 1) {
  41736. ear = cureLocalIntersections(ear, triangles, dim);
  41737. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  41738. }
  41739. else if (pass === 2) {
  41740. splitEarcut(ear, triangles, dim, minX, minY, size);
  41741. }
  41742. break;
  41743. }
  41744. }
  41745. }
  41746. // check whether a polygon node forms a valid ear with adjacent nodes
  41747. function isEar(ear) {
  41748. var a = ear.prev, b = ear, c = ear.next;
  41749. if (area(a, b, c) >= 0)
  41750. return false; // reflex, can't be an ear
  41751. // now make sure we don't have other points inside the potential ear
  41752. var p = ear.next.next;
  41753. while (p !== ear.prev) {
  41754. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41755. area(p.prev, p, p.next) >= 0)
  41756. return false;
  41757. p = p.next;
  41758. }
  41759. return true;
  41760. }
  41761. function isEarHashed(ear, minX, minY, size) {
  41762. var a = ear.prev, b = ear, c = ear.next;
  41763. if (area(a, b, c) >= 0)
  41764. return false; // reflex, can't be an ear
  41765. // triangle bbox; min & max are calculated like this for speed
  41766. 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);
  41767. // z-order range for the current triangle bbox;
  41768. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  41769. // first look for points inside the triangle in increasing z-order
  41770. var p = ear.nextZ;
  41771. while (p && p.z <= maxZ) {
  41772. if (p !== ear.prev &&
  41773. p !== ear.next &&
  41774. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41775. area(p.prev, p, p.next) >= 0)
  41776. return false;
  41777. p = p.nextZ;
  41778. }
  41779. // then look for points in decreasing z-order
  41780. p = ear.prevZ;
  41781. while (p && p.z >= minZ) {
  41782. if (p !== ear.prev &&
  41783. p !== ear.next &&
  41784. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41785. area(p.prev, p, p.next) >= 0)
  41786. return false;
  41787. p = p.prevZ;
  41788. }
  41789. return true;
  41790. }
  41791. // go through all polygon nodes and cure small local self-intersections
  41792. function cureLocalIntersections(start, triangles, dim) {
  41793. var p = start;
  41794. do {
  41795. var a = p.prev, b = p.next.next;
  41796. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  41797. triangles.push(a.i / dim);
  41798. triangles.push(p.i / dim);
  41799. triangles.push(b.i / dim);
  41800. // remove two nodes involved
  41801. removeNode(p);
  41802. removeNode(p.next);
  41803. p = start = b;
  41804. }
  41805. p = p.next;
  41806. } while (p !== start);
  41807. return p;
  41808. }
  41809. // try splitting polygon into two and triangulate them independently
  41810. function splitEarcut(start, triangles, dim, minX, minY, size) {
  41811. // look for a valid diagonal that divides the polygon into two
  41812. var a = start;
  41813. do {
  41814. var b = a.next.next;
  41815. while (b !== a.prev) {
  41816. if (a.i !== b.i && isValidDiagonal(a, b)) {
  41817. // split the polygon in two by the diagonal
  41818. var c = splitPolygon(a, b);
  41819. // filter colinear points around the cuts
  41820. a = filterPoints(a, a.next);
  41821. c = filterPoints(c, c.next);
  41822. // run earcut on each half
  41823. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  41824. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  41825. return;
  41826. }
  41827. b = b.next;
  41828. }
  41829. a = a.next;
  41830. } while (a !== start);
  41831. }
  41832. // link every hole into the outer loop, producing a single-ring polygon without holes
  41833. function eliminateHoles(data, holeIndices, outerNode, dim) {
  41834. var queue = [], i, len, start, end, list;
  41835. for (i = 0, len = holeIndices.length; i < len; i++) {
  41836. start = holeIndices[i] * dim;
  41837. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41838. list = linkedList(data, start, end, dim, false);
  41839. if (list === list.next)
  41840. list.steiner = true;
  41841. queue.push(getLeftmost(list));
  41842. }
  41843. queue.sort(compareX);
  41844. // process holes from left to right
  41845. for (i = 0; i < queue.length; i++) {
  41846. eliminateHole(queue[i], outerNode);
  41847. outerNode = filterPoints(outerNode, outerNode.next);
  41848. }
  41849. return outerNode;
  41850. }
  41851. function compareX(a, b) {
  41852. return a.x - b.x;
  41853. }
  41854. // find a bridge between vertices that connects hole with an outer ring and and link it
  41855. function eliminateHole(hole, outerNode) {
  41856. outerNode = findHoleBridge(hole, outerNode);
  41857. if (outerNode) {
  41858. var b = splitPolygon(outerNode, hole);
  41859. filterPoints(b, b.next);
  41860. }
  41861. }
  41862. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  41863. function findHoleBridge(hole, outerNode) {
  41864. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  41865. // find a segment intersected by a ray from the hole's leftmost point to the left;
  41866. // segment's endpoint with lesser x will be potential connection point
  41867. do {
  41868. if (hy <= p.y && hy >= p.next.y) {
  41869. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  41870. if (x <= hx && x > qx) {
  41871. qx = x;
  41872. if (x === hx) {
  41873. if (hy === p.y)
  41874. return p;
  41875. if (hy === p.next.y)
  41876. return p.next;
  41877. }
  41878. m = p.x < p.next.x ? p : p.next;
  41879. }
  41880. }
  41881. p = p.next;
  41882. } while (p !== outerNode);
  41883. if (!m)
  41884. return null;
  41885. if (hx === qx)
  41886. return m.prev; // hole touches outer segment; pick lower endpoint
  41887. // look for points inside the triangle of hole point, segment intersection and endpoint;
  41888. // if there are no points found, we have a valid connection;
  41889. // otherwise choose the point of the minimum angle with the ray as connection point
  41890. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  41891. p = m.next;
  41892. while (p !== stop) {
  41893. if (hx >= p.x &&
  41894. p.x >= mx &&
  41895. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  41896. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  41897. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  41898. m = p;
  41899. tanMin = tan;
  41900. }
  41901. }
  41902. p = p.next;
  41903. }
  41904. return m;
  41905. }
  41906. // interlink polygon nodes in z-order
  41907. function indexCurve(start, minX, minY, size) {
  41908. var p = start;
  41909. do {
  41910. if (p.z === null)
  41911. p.z = zOrder(p.x, p.y, minX, minY, size);
  41912. p.prevZ = p.prev;
  41913. p.nextZ = p.next;
  41914. p = p.next;
  41915. } while (p !== start);
  41916. p.prevZ.nextZ = null;
  41917. p.prevZ = null;
  41918. sortLinked(p);
  41919. }
  41920. // Simon Tatham's linked list merge sort algorithm
  41921. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  41922. function sortLinked(list) {
  41923. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  41924. do {
  41925. p = list;
  41926. list = null;
  41927. tail = null;
  41928. numMerges = 0;
  41929. while (p) {
  41930. numMerges++;
  41931. q = p;
  41932. pSize = 0;
  41933. for (i = 0; i < inSize; i++) {
  41934. pSize++;
  41935. q = q.nextZ;
  41936. if (!q)
  41937. break;
  41938. }
  41939. qSize = inSize;
  41940. while (pSize > 0 || (qSize > 0 && q)) {
  41941. if (pSize === 0) {
  41942. e = q;
  41943. q = q.nextZ;
  41944. qSize--;
  41945. }
  41946. else if (qSize === 0 || !q) {
  41947. e = p;
  41948. p = p.nextZ;
  41949. pSize--;
  41950. }
  41951. else if (p.z <= q.z) {
  41952. e = p;
  41953. p = p.nextZ;
  41954. pSize--;
  41955. }
  41956. else {
  41957. e = q;
  41958. q = q.nextZ;
  41959. qSize--;
  41960. }
  41961. if (tail)
  41962. tail.nextZ = e;
  41963. else
  41964. list = e;
  41965. e.prevZ = tail;
  41966. tail = e;
  41967. }
  41968. p = q;
  41969. }
  41970. tail.nextZ = null;
  41971. inSize *= 2;
  41972. } while (numMerges > 1);
  41973. return list;
  41974. }
  41975. // z-order of a point given coords and size of the data bounding box
  41976. function zOrder(x, y, minX, minY, size) {
  41977. // coords are transformed into non-negative 15-bit integer range
  41978. x = 32767 * (x - minX) / size;
  41979. y = 32767 * (y - minY) / size;
  41980. x = (x | (x << 8)) & 0x00FF00FF;
  41981. x = (x | (x << 4)) & 0x0F0F0F0F;
  41982. x = (x | (x << 2)) & 0x33333333;
  41983. x = (x | (x << 1)) & 0x55555555;
  41984. y = (y | (y << 8)) & 0x00FF00FF;
  41985. y = (y | (y << 4)) & 0x0F0F0F0F;
  41986. y = (y | (y << 2)) & 0x33333333;
  41987. y = (y | (y << 1)) & 0x55555555;
  41988. return x | (y << 1);
  41989. }
  41990. // find the leftmost node of a polygon ring
  41991. function getLeftmost(start) {
  41992. var p = start, leftmost = start;
  41993. do {
  41994. if (p.x < leftmost.x)
  41995. leftmost = p;
  41996. p = p.next;
  41997. } while (p !== start);
  41998. return leftmost;
  41999. }
  42000. // check if a point lies within a convex triangle
  42001. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  42002. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  42003. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  42004. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  42005. }
  42006. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  42007. function isValidDiagonal(a, b) {
  42008. return a.next.i !== b.i &&
  42009. a.prev.i !== b.i &&
  42010. !intersectsPolygon(a, b) &&
  42011. locallyInside(a, b) &&
  42012. locallyInside(b, a) &&
  42013. middleInside(a, b);
  42014. }
  42015. // signed area of a triangle
  42016. function area(p, q, r) {
  42017. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  42018. }
  42019. // check if two points are equal
  42020. function equals(p1, p2) {
  42021. return p1.x === p2.x && p1.y === p2.y;
  42022. }
  42023. // check if two segments intersect
  42024. function intersects(p1, q1, p2, q2) {
  42025. if ((equals(p1, q1) && equals(p2, q2)) ||
  42026. (equals(p1, q2) && equals(p2, q1)))
  42027. return true;
  42028. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  42029. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  42030. }
  42031. // check if a polygon diagonal intersects any polygon segments
  42032. function intersectsPolygon(a, b) {
  42033. var p = a;
  42034. do {
  42035. if (p.i !== a.i &&
  42036. p.next.i !== a.i &&
  42037. p.i !== b.i &&
  42038. p.next.i !== b.i &&
  42039. intersects(p, p.next, a, b))
  42040. return true;
  42041. p = p.next;
  42042. } while (p !== a);
  42043. return false;
  42044. }
  42045. // check if a polygon diagonal is locally inside the polygon
  42046. function locallyInside(a, b) {
  42047. return area(a.prev, a, a.next) < 0
  42048. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  42049. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  42050. }
  42051. // check if the middle point of a polygon diagonal is inside the polygon
  42052. function middleInside(a, b) {
  42053. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  42054. do {
  42055. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  42056. inside = !inside;
  42057. p = p.next;
  42058. } while (p !== a);
  42059. return inside;
  42060. }
  42061. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  42062. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  42063. function splitPolygon(a, b) {
  42064. 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;
  42065. a.next = b;
  42066. b.prev = a;
  42067. a2.next = an;
  42068. an.prev = a2;
  42069. b2.next = a2;
  42070. a2.prev = b2;
  42071. bp.next = b2;
  42072. b2.prev = bp;
  42073. return b2;
  42074. }
  42075. // create a node and optionally link it with previous one (in a circular doubly linked list)
  42076. function insertNode(i, x, y, last) {
  42077. var p = new Node(i, x, y);
  42078. if (!last) {
  42079. p.prev = p;
  42080. p.next = p;
  42081. }
  42082. else {
  42083. p.next = last.next;
  42084. p.prev = last;
  42085. last.next.prev = p;
  42086. last.next = p;
  42087. }
  42088. return p;
  42089. }
  42090. function removeNode(p) {
  42091. p.next.prev = p.prev;
  42092. p.prev.next = p.next;
  42093. if (p.prevZ)
  42094. p.prevZ.nextZ = p.nextZ;
  42095. if (p.nextZ)
  42096. p.nextZ.prevZ = p.prevZ;
  42097. }
  42098. function Node(i, x, y) {
  42099. // vertice index in coordinates array
  42100. this.i = i;
  42101. // vertex coordinates
  42102. this.x = x;
  42103. this.y = y;
  42104. // previous and next vertice nodes in a polygon ring
  42105. this.prev = null;
  42106. this.next = null;
  42107. // z-order curve value
  42108. this.z = null;
  42109. // previous and next nodes in z-order
  42110. this.prevZ = null;
  42111. this.nextZ = null;
  42112. // indicates whether this is a steiner point
  42113. this.steiner = false;
  42114. }
  42115. /**
  42116. * return a percentage difference between the polygon area and its triangulation area;
  42117. * used to verify correctness of triangulation
  42118. */
  42119. function deviation(data, holeIndices, dim, triangles) {
  42120. var hasHoles = holeIndices && holeIndices.length;
  42121. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  42122. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  42123. if (hasHoles) {
  42124. for (var i = 0, len = holeIndices.length; i < len; i++) {
  42125. var start = holeIndices[i] * dim;
  42126. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42127. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  42128. }
  42129. }
  42130. var trianglesArea = 0;
  42131. for (i = 0; i < triangles.length; i += 3) {
  42132. var a = triangles[i] * dim;
  42133. var b = triangles[i + 1] * dim;
  42134. var c = triangles[i + 2] * dim;
  42135. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  42136. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  42137. }
  42138. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  42139. }
  42140. Earcut.deviation = deviation;
  42141. ;
  42142. function signedArea(data, start, end, dim) {
  42143. var sum = 0;
  42144. for (var i = start, j = end - dim; i < end; i += dim) {
  42145. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  42146. j = i;
  42147. }
  42148. return sum;
  42149. }
  42150. /**
  42151. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  42152. */
  42153. function flatten(data) {
  42154. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  42155. for (var i = 0; i < data.length; i++) {
  42156. for (var j = 0; j < data[i].length; j++) {
  42157. for (var d = 0; d < dim; d++)
  42158. result.vertices.push(data[i][j][d]);
  42159. }
  42160. if (i > 0) {
  42161. holeIndex += data[i - 1].length;
  42162. result.holes.push(holeIndex);
  42163. }
  42164. }
  42165. return result;
  42166. }
  42167. Earcut.flatten = flatten;
  42168. ;
  42169. })(Earcut || (Earcut = {}));
  42170. var BABYLON;
  42171. (function (BABYLON) {
  42172. // Unique ID when we import meshes from Babylon to CSG
  42173. var currentCSGMeshId = 0;
  42174. // # class Vertex
  42175. // Represents a vertex of a polygon. Use your own vertex class instead of this
  42176. // one to provide additional features like texture coordinates and vertex
  42177. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  42178. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  42179. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  42180. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  42181. // is not used anywhere else.
  42182. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  42183. var Vertex = (function () {
  42184. function Vertex(pos, normal, uv) {
  42185. this.pos = pos;
  42186. this.normal = normal;
  42187. this.uv = uv;
  42188. }
  42189. Vertex.prototype.clone = function () {
  42190. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  42191. };
  42192. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  42193. // orientation of a polygon is flipped.
  42194. Vertex.prototype.flip = function () {
  42195. this.normal = this.normal.scale(-1);
  42196. };
  42197. // Create a new vertex between this vertex and `other` by linearly
  42198. // interpolating all properties using a parameter of `t`. Subclasses should
  42199. // override this to interpolate additional properties.
  42200. Vertex.prototype.interpolate = function (other, t) {
  42201. 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));
  42202. };
  42203. return Vertex;
  42204. }());
  42205. // # class Plane
  42206. // Represents a plane in 3D space.
  42207. var Plane = (function () {
  42208. function Plane(normal, w) {
  42209. this.normal = normal;
  42210. this.w = w;
  42211. }
  42212. Plane.FromPoints = function (a, b, c) {
  42213. var v0 = c.subtract(a);
  42214. var v1 = b.subtract(a);
  42215. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  42216. return null;
  42217. }
  42218. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  42219. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  42220. };
  42221. Plane.prototype.clone = function () {
  42222. return new Plane(this.normal.clone(), this.w);
  42223. };
  42224. Plane.prototype.flip = function () {
  42225. this.normal.scaleInPlace(-1);
  42226. this.w = -this.w;
  42227. };
  42228. // Split `polygon` by this plane if needed, then put the polygon or polygon
  42229. // fragments in the appropriate lists. Coplanar polygons go into either
  42230. // `coplanarFront` or `coplanarBack` depending on their orientation with
  42231. // respect to this plane. Polygons in front or in back of this plane go into
  42232. // either `front` or `back`.
  42233. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  42234. var COPLANAR = 0;
  42235. var FRONT = 1;
  42236. var BACK = 2;
  42237. var SPANNING = 3;
  42238. // Classify each point as well as the entire polygon into one of the above
  42239. // four classes.
  42240. var polygonType = 0;
  42241. var types = [];
  42242. var i;
  42243. var t;
  42244. for (i = 0; i < polygon.vertices.length; i++) {
  42245. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  42246. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  42247. polygonType |= type;
  42248. types.push(type);
  42249. }
  42250. // Put the polygon in the correct list, splitting it when necessary.
  42251. switch (polygonType) {
  42252. case COPLANAR:
  42253. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  42254. break;
  42255. case FRONT:
  42256. front.push(polygon);
  42257. break;
  42258. case BACK:
  42259. back.push(polygon);
  42260. break;
  42261. case SPANNING:
  42262. var f = [], b = [];
  42263. for (i = 0; i < polygon.vertices.length; i++) {
  42264. var j = (i + 1) % polygon.vertices.length;
  42265. var ti = types[i], tj = types[j];
  42266. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  42267. if (ti !== BACK)
  42268. f.push(vi);
  42269. if (ti !== FRONT)
  42270. b.push(ti !== BACK ? vi.clone() : vi);
  42271. if ((ti | tj) === SPANNING) {
  42272. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  42273. var v = vi.interpolate(vj, t);
  42274. f.push(v);
  42275. b.push(v.clone());
  42276. }
  42277. }
  42278. var poly;
  42279. if (f.length >= 3) {
  42280. poly = new Polygon(f, polygon.shared);
  42281. if (poly.plane)
  42282. front.push(poly);
  42283. }
  42284. if (b.length >= 3) {
  42285. poly = new Polygon(b, polygon.shared);
  42286. if (poly.plane)
  42287. back.push(poly);
  42288. }
  42289. break;
  42290. }
  42291. };
  42292. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  42293. // point is on the plane.
  42294. Plane.EPSILON = 1e-5;
  42295. return Plane;
  42296. }());
  42297. // # class Polygon
  42298. // Represents a convex polygon. The vertices used to initialize a polygon must
  42299. // be coplanar and form a convex loop.
  42300. //
  42301. // Each convex polygon has a `shared` property, which is shared between all
  42302. // polygons that are clones of each other or were split from the same polygon.
  42303. // This can be used to define per-polygon properties (such as surface color).
  42304. var Polygon = (function () {
  42305. function Polygon(vertices, shared) {
  42306. this.vertices = vertices;
  42307. this.shared = shared;
  42308. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  42309. }
  42310. Polygon.prototype.clone = function () {
  42311. var vertices = this.vertices.map(function (v) { return v.clone(); });
  42312. return new Polygon(vertices, this.shared);
  42313. };
  42314. Polygon.prototype.flip = function () {
  42315. this.vertices.reverse().map(function (v) { v.flip(); });
  42316. this.plane.flip();
  42317. };
  42318. return Polygon;
  42319. }());
  42320. // # class Node
  42321. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  42322. // by picking a polygon to split along. That polygon (and all other coplanar
  42323. // polygons) are added directly to that node and the other polygons are added to
  42324. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  42325. // no distinction between internal and leaf nodes.
  42326. var Node = (function () {
  42327. function Node(polygons) {
  42328. this.plane = null;
  42329. this.front = null;
  42330. this.back = null;
  42331. this.polygons = [];
  42332. if (polygons) {
  42333. this.build(polygons);
  42334. }
  42335. }
  42336. Node.prototype.clone = function () {
  42337. var node = new Node();
  42338. node.plane = this.plane && this.plane.clone();
  42339. node.front = this.front && this.front.clone();
  42340. node.back = this.back && this.back.clone();
  42341. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  42342. return node;
  42343. };
  42344. // Convert solid space to empty space and empty space to solid space.
  42345. Node.prototype.invert = function () {
  42346. for (var i = 0; i < this.polygons.length; i++) {
  42347. this.polygons[i].flip();
  42348. }
  42349. if (this.plane) {
  42350. this.plane.flip();
  42351. }
  42352. if (this.front) {
  42353. this.front.invert();
  42354. }
  42355. if (this.back) {
  42356. this.back.invert();
  42357. }
  42358. var temp = this.front;
  42359. this.front = this.back;
  42360. this.back = temp;
  42361. };
  42362. // Recursively remove all polygons in `polygons` that are inside this BSP
  42363. // tree.
  42364. Node.prototype.clipPolygons = function (polygons) {
  42365. if (!this.plane)
  42366. return polygons.slice();
  42367. var front = [], back = [];
  42368. for (var i = 0; i < polygons.length; i++) {
  42369. this.plane.splitPolygon(polygons[i], front, back, front, back);
  42370. }
  42371. if (this.front) {
  42372. front = this.front.clipPolygons(front);
  42373. }
  42374. if (this.back) {
  42375. back = this.back.clipPolygons(back);
  42376. }
  42377. else {
  42378. back = [];
  42379. }
  42380. return front.concat(back);
  42381. };
  42382. // Remove all polygons in this BSP tree that are inside the other BSP tree
  42383. // `bsp`.
  42384. Node.prototype.clipTo = function (bsp) {
  42385. this.polygons = bsp.clipPolygons(this.polygons);
  42386. if (this.front)
  42387. this.front.clipTo(bsp);
  42388. if (this.back)
  42389. this.back.clipTo(bsp);
  42390. };
  42391. // Return a list of all polygons in this BSP tree.
  42392. Node.prototype.allPolygons = function () {
  42393. var polygons = this.polygons.slice();
  42394. if (this.front)
  42395. polygons = polygons.concat(this.front.allPolygons());
  42396. if (this.back)
  42397. polygons = polygons.concat(this.back.allPolygons());
  42398. return polygons;
  42399. };
  42400. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  42401. // new polygons are filtered down to the bottom of the tree and become new
  42402. // nodes there. Each set of polygons is partitioned using the first polygon
  42403. // (no heuristic is used to pick a good split).
  42404. Node.prototype.build = function (polygons) {
  42405. if (!polygons.length)
  42406. return;
  42407. if (!this.plane)
  42408. this.plane = polygons[0].plane.clone();
  42409. var front = [], back = [];
  42410. for (var i = 0; i < polygons.length; i++) {
  42411. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  42412. }
  42413. if (front.length) {
  42414. if (!this.front)
  42415. this.front = new Node();
  42416. this.front.build(front);
  42417. }
  42418. if (back.length) {
  42419. if (!this.back)
  42420. this.back = new Node();
  42421. this.back.build(back);
  42422. }
  42423. };
  42424. return Node;
  42425. }());
  42426. var CSG = (function () {
  42427. function CSG() {
  42428. this.polygons = new Array();
  42429. }
  42430. // Convert BABYLON.Mesh to BABYLON.CSG
  42431. CSG.FromMesh = function (mesh) {
  42432. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  42433. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  42434. if (mesh instanceof BABYLON.Mesh) {
  42435. mesh.computeWorldMatrix(true);
  42436. matrix = mesh.getWorldMatrix();
  42437. meshPosition = mesh.position.clone();
  42438. meshRotation = mesh.rotation.clone();
  42439. if (mesh.rotationQuaternion) {
  42440. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  42441. }
  42442. meshScaling = mesh.scaling.clone();
  42443. }
  42444. else {
  42445. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  42446. }
  42447. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42448. var subMeshes = mesh.subMeshes;
  42449. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  42450. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  42451. vertices = [];
  42452. for (var j = 0; j < 3; j++) {
  42453. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  42454. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  42455. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  42456. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  42457. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  42458. vertex = new Vertex(position, normal, uv);
  42459. vertices.push(vertex);
  42460. }
  42461. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  42462. // To handle the case of degenerated triangle
  42463. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  42464. if (polygon.plane)
  42465. polygons.push(polygon);
  42466. }
  42467. }
  42468. var csg = CSG.FromPolygons(polygons);
  42469. csg.matrix = matrix;
  42470. csg.position = meshPosition;
  42471. csg.rotation = meshRotation;
  42472. csg.scaling = meshScaling;
  42473. csg.rotationQuaternion = meshRotationQuaternion;
  42474. currentCSGMeshId++;
  42475. return csg;
  42476. };
  42477. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  42478. CSG.FromPolygons = function (polygons) {
  42479. var csg = new CSG();
  42480. csg.polygons = polygons;
  42481. return csg;
  42482. };
  42483. CSG.prototype.clone = function () {
  42484. var csg = new CSG();
  42485. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  42486. csg.copyTransformAttributes(this);
  42487. return csg;
  42488. };
  42489. CSG.prototype.toPolygons = function () {
  42490. return this.polygons;
  42491. };
  42492. CSG.prototype.union = function (csg) {
  42493. var a = new Node(this.clone().polygons);
  42494. var b = new Node(csg.clone().polygons);
  42495. a.clipTo(b);
  42496. b.clipTo(a);
  42497. b.invert();
  42498. b.clipTo(a);
  42499. b.invert();
  42500. a.build(b.allPolygons());
  42501. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42502. };
  42503. CSG.prototype.unionInPlace = function (csg) {
  42504. var a = new Node(this.polygons);
  42505. var b = new Node(csg.polygons);
  42506. a.clipTo(b);
  42507. b.clipTo(a);
  42508. b.invert();
  42509. b.clipTo(a);
  42510. b.invert();
  42511. a.build(b.allPolygons());
  42512. this.polygons = a.allPolygons();
  42513. };
  42514. CSG.prototype.subtract = function (csg) {
  42515. var a = new Node(this.clone().polygons);
  42516. var b = new Node(csg.clone().polygons);
  42517. a.invert();
  42518. a.clipTo(b);
  42519. b.clipTo(a);
  42520. b.invert();
  42521. b.clipTo(a);
  42522. b.invert();
  42523. a.build(b.allPolygons());
  42524. a.invert();
  42525. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42526. };
  42527. CSG.prototype.subtractInPlace = function (csg) {
  42528. var a = new Node(this.polygons);
  42529. var b = new Node(csg.polygons);
  42530. a.invert();
  42531. a.clipTo(b);
  42532. b.clipTo(a);
  42533. b.invert();
  42534. b.clipTo(a);
  42535. b.invert();
  42536. a.build(b.allPolygons());
  42537. a.invert();
  42538. this.polygons = a.allPolygons();
  42539. };
  42540. CSG.prototype.intersect = function (csg) {
  42541. var a = new Node(this.clone().polygons);
  42542. var b = new Node(csg.clone().polygons);
  42543. a.invert();
  42544. b.clipTo(a);
  42545. b.invert();
  42546. a.clipTo(b);
  42547. b.clipTo(a);
  42548. a.build(b.allPolygons());
  42549. a.invert();
  42550. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42551. };
  42552. CSG.prototype.intersectInPlace = function (csg) {
  42553. var a = new Node(this.polygons);
  42554. var b = new Node(csg.polygons);
  42555. a.invert();
  42556. b.clipTo(a);
  42557. b.invert();
  42558. a.clipTo(b);
  42559. b.clipTo(a);
  42560. a.build(b.allPolygons());
  42561. a.invert();
  42562. this.polygons = a.allPolygons();
  42563. };
  42564. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  42565. // not modified.
  42566. CSG.prototype.inverse = function () {
  42567. var csg = this.clone();
  42568. csg.inverseInPlace();
  42569. return csg;
  42570. };
  42571. CSG.prototype.inverseInPlace = function () {
  42572. this.polygons.map(function (p) { p.flip(); });
  42573. };
  42574. // This is used to keep meshes transformations so they can be restored
  42575. // when we build back a Babylon Mesh
  42576. // NB : All CSG operations are performed in world coordinates
  42577. CSG.prototype.copyTransformAttributes = function (csg) {
  42578. this.matrix = csg.matrix;
  42579. this.position = csg.position;
  42580. this.rotation = csg.rotation;
  42581. this.scaling = csg.scaling;
  42582. this.rotationQuaternion = csg.rotationQuaternion;
  42583. return this;
  42584. };
  42585. // Build Raw mesh from CSG
  42586. // Coordinates here are in world space
  42587. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  42588. var matrix = this.matrix.clone();
  42589. matrix.invert();
  42590. 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;
  42591. if (keepSubMeshes) {
  42592. // Sort Polygons, since subMeshes are indices range
  42593. polygons.sort(function (a, b) {
  42594. if (a.shared.meshId === b.shared.meshId) {
  42595. return a.shared.subMeshId - b.shared.subMeshId;
  42596. }
  42597. else {
  42598. return a.shared.meshId - b.shared.meshId;
  42599. }
  42600. });
  42601. }
  42602. for (var i = 0, il = polygons.length; i < il; i++) {
  42603. polygon = polygons[i];
  42604. // Building SubMeshes
  42605. if (!subMesh_dict[polygon.shared.meshId]) {
  42606. subMesh_dict[polygon.shared.meshId] = {};
  42607. }
  42608. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  42609. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  42610. indexStart: +Infinity,
  42611. indexEnd: -Infinity,
  42612. materialIndex: polygon.shared.materialIndex
  42613. };
  42614. }
  42615. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  42616. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  42617. polygonIndices[0] = 0;
  42618. polygonIndices[1] = j - 1;
  42619. polygonIndices[2] = j;
  42620. for (var k = 0; k < 3; k++) {
  42621. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  42622. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  42623. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  42624. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  42625. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  42626. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  42627. // Check if 2 points can be merged
  42628. if (!(typeof vertex_idx !== 'undefined' &&
  42629. normals[vertex_idx * 3] === localNormal.x &&
  42630. normals[vertex_idx * 3 + 1] === localNormal.y &&
  42631. normals[vertex_idx * 3 + 2] === localNormal.z &&
  42632. uvs[vertex_idx * 2] === uv.x &&
  42633. uvs[vertex_idx * 2 + 1] === uv.y)) {
  42634. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  42635. uvs.push(uv.x, uv.y);
  42636. normals.push(normal.x, normal.y, normal.z);
  42637. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  42638. }
  42639. indices.push(vertex_idx);
  42640. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  42641. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  42642. currentIndex++;
  42643. }
  42644. }
  42645. }
  42646. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  42647. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  42648. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  42649. mesh.setIndices(indices);
  42650. if (keepSubMeshes) {
  42651. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  42652. var materialIndexOffset = 0, materialMaxIndex;
  42653. mesh.subMeshes = new Array();
  42654. for (var m in subMesh_dict) {
  42655. materialMaxIndex = -1;
  42656. for (var sm in subMesh_dict[m]) {
  42657. subMesh_obj = subMesh_dict[m][sm];
  42658. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  42659. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  42660. }
  42661. materialIndexOffset += ++materialMaxIndex;
  42662. }
  42663. }
  42664. return mesh;
  42665. };
  42666. // Build Mesh from CSG taking material and transforms into account
  42667. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  42668. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  42669. mesh.material = material;
  42670. mesh.position.copyFrom(this.position);
  42671. mesh.rotation.copyFrom(this.rotation);
  42672. if (this.rotationQuaternion) {
  42673. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  42674. }
  42675. mesh.scaling.copyFrom(this.scaling);
  42676. mesh.computeWorldMatrix(true);
  42677. return mesh;
  42678. };
  42679. return CSG;
  42680. }());
  42681. BABYLON.CSG = CSG;
  42682. })(BABYLON || (BABYLON = {}));
  42683. var BABYLON;
  42684. (function (BABYLON) {
  42685. var VRDistortionCorrectionPostProcess = (function (_super) {
  42686. __extends(VRDistortionCorrectionPostProcess, _super);
  42687. //ANY
  42688. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  42689. var _this = this;
  42690. _super.call(this, name, "vrDistortionCorrection", [
  42691. 'LensCenter',
  42692. 'Scale',
  42693. 'ScaleIn',
  42694. 'HmdWarpParam'
  42695. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  42696. this._isRightEye = isRightEye;
  42697. this._distortionFactors = vrMetrics.distortionK;
  42698. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  42699. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42700. this.onSizeChangedObservable.add(function () {
  42701. _this.aspectRatio = _this.width * .5 / _this.height;
  42702. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42703. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42704. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42705. });
  42706. this.onApplyObservable.add(function (effect) {
  42707. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42708. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42709. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42710. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42711. });
  42712. }
  42713. return VRDistortionCorrectionPostProcess;
  42714. }(BABYLON.PostProcess));
  42715. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42716. })(BABYLON || (BABYLON = {}));
  42717. // Mainly based on these 2 articles :
  42718. // 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
  42719. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42720. var BABYLON;
  42721. (function (BABYLON) {
  42722. (function (JoystickAxis) {
  42723. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42724. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42725. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42726. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42727. var JoystickAxis = BABYLON.JoystickAxis;
  42728. var VirtualJoystick = (function () {
  42729. function VirtualJoystick(leftJoystick) {
  42730. var _this = this;
  42731. if (leftJoystick) {
  42732. this._leftJoystick = true;
  42733. }
  42734. else {
  42735. this._leftJoystick = false;
  42736. }
  42737. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42738. VirtualJoystick._globalJoystickIndex++;
  42739. // By default left & right arrow keys are moving the X
  42740. // and up & down keys are moving the Y
  42741. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42742. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42743. this.reverseLeftRight = false;
  42744. this.reverseUpDown = false;
  42745. // collections of pointers
  42746. this._touches = new BABYLON.StringDictionary();
  42747. this.deltaPosition = BABYLON.Vector3.Zero();
  42748. this._joystickSensibility = 25;
  42749. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42750. this._rotationSpeed = 25;
  42751. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42752. this._rotateOnAxisRelativeToMesh = false;
  42753. this._onResize = function (evt) {
  42754. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42755. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42756. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42757. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42758. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42759. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42760. };
  42761. // injecting a canvas element on top of the canvas 3D game
  42762. if (!VirtualJoystick.vjCanvas) {
  42763. window.addEventListener("resize", this._onResize, false);
  42764. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42765. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42766. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42767. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42768. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42769. VirtualJoystick.vjCanvas.style.width = "100%";
  42770. VirtualJoystick.vjCanvas.style.height = "100%";
  42771. VirtualJoystick.vjCanvas.style.position = "absolute";
  42772. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42773. VirtualJoystick.vjCanvas.style.top = "0px";
  42774. VirtualJoystick.vjCanvas.style.left = "0px";
  42775. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42776. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42777. // Support for jQuery PEP polyfill
  42778. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42779. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42780. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42781. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42782. document.body.appendChild(VirtualJoystick.vjCanvas);
  42783. }
  42784. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42785. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42786. this.pressed = false;
  42787. // default joystick color
  42788. this._joystickColor = "cyan";
  42789. this._joystickPointerID = -1;
  42790. // current joystick position
  42791. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42792. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42793. // origin joystick position
  42794. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42795. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42796. this._onPointerDownHandlerRef = function (evt) {
  42797. _this._onPointerDown(evt);
  42798. };
  42799. this._onPointerMoveHandlerRef = function (evt) {
  42800. _this._onPointerMove(evt);
  42801. };
  42802. this._onPointerOutHandlerRef = function (evt) {
  42803. _this._onPointerUp(evt);
  42804. };
  42805. this._onPointerUpHandlerRef = function (evt) {
  42806. _this._onPointerUp(evt);
  42807. };
  42808. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42809. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42810. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42811. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42812. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42813. evt.preventDefault(); // Disables system menu
  42814. }, false);
  42815. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42816. }
  42817. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42818. this._joystickSensibility = newJoystickSensibility;
  42819. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42820. };
  42821. VirtualJoystick.prototype._onPointerDown = function (e) {
  42822. var positionOnScreenCondition;
  42823. e.preventDefault();
  42824. if (this._leftJoystick === true) {
  42825. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  42826. }
  42827. else {
  42828. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  42829. }
  42830. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  42831. // First contact will be dedicated to the virtual joystick
  42832. this._joystickPointerID = e.pointerId;
  42833. this._joystickPointerStartPos.x = e.clientX;
  42834. this._joystickPointerStartPos.y = e.clientY;
  42835. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  42836. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  42837. this._deltaJoystickVector.x = 0;
  42838. this._deltaJoystickVector.y = 0;
  42839. this.pressed = true;
  42840. this._touches.add(e.pointerId.toString(), e);
  42841. }
  42842. else {
  42843. // You can only trigger the action buttons with a joystick declared
  42844. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  42845. this._action();
  42846. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  42847. }
  42848. }
  42849. };
  42850. VirtualJoystick.prototype._onPointerMove = function (e) {
  42851. // If the current pointer is the one associated to the joystick (first touch contact)
  42852. if (this._joystickPointerID == e.pointerId) {
  42853. this._joystickPointerPos.x = e.clientX;
  42854. this._joystickPointerPos.y = e.clientY;
  42855. this._deltaJoystickVector = this._joystickPointerPos.clone();
  42856. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  42857. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  42858. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  42859. switch (this._axisTargetedByLeftAndRight) {
  42860. case JoystickAxis.X:
  42861. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  42862. break;
  42863. case JoystickAxis.Y:
  42864. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  42865. break;
  42866. case JoystickAxis.Z:
  42867. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  42868. break;
  42869. }
  42870. var directionUpDown = this.reverseUpDown ? 1 : -1;
  42871. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  42872. switch (this._axisTargetedByUpAndDown) {
  42873. case JoystickAxis.X:
  42874. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  42875. break;
  42876. case JoystickAxis.Y:
  42877. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  42878. break;
  42879. case JoystickAxis.Z:
  42880. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  42881. break;
  42882. }
  42883. }
  42884. else {
  42885. var data = this._touches.get(e.pointerId.toString());
  42886. if (data) {
  42887. data.x = e.clientX;
  42888. data.y = e.clientY;
  42889. }
  42890. }
  42891. };
  42892. VirtualJoystick.prototype._onPointerUp = function (e) {
  42893. if (this._joystickPointerID == e.pointerId) {
  42894. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  42895. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  42896. this._joystickPointerID = -1;
  42897. this.pressed = false;
  42898. }
  42899. else {
  42900. var touch = this._touches.get(e.pointerId.toString());
  42901. if (touch) {
  42902. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42903. }
  42904. }
  42905. this._deltaJoystickVector.x = 0;
  42906. this._deltaJoystickVector.y = 0;
  42907. this._touches.remove(e.pointerId.toString());
  42908. };
  42909. /**
  42910. * Change the color of the virtual joystick
  42911. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  42912. */
  42913. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  42914. this._joystickColor = newColor;
  42915. };
  42916. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  42917. this._action = action;
  42918. };
  42919. // Define which axis you'd like to control for left & right
  42920. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  42921. switch (axis) {
  42922. case JoystickAxis.X:
  42923. case JoystickAxis.Y:
  42924. case JoystickAxis.Z:
  42925. this._axisTargetedByLeftAndRight = axis;
  42926. break;
  42927. default:
  42928. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42929. break;
  42930. }
  42931. };
  42932. // Define which axis you'd like to control for up & down
  42933. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  42934. switch (axis) {
  42935. case JoystickAxis.X:
  42936. case JoystickAxis.Y:
  42937. case JoystickAxis.Z:
  42938. this._axisTargetedByUpAndDown = axis;
  42939. break;
  42940. default:
  42941. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42942. break;
  42943. }
  42944. };
  42945. VirtualJoystick.prototype._clearCanvas = function () {
  42946. if (this._leftJoystick) {
  42947. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  42948. }
  42949. else {
  42950. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  42951. }
  42952. };
  42953. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  42954. var _this = this;
  42955. if (this.pressed) {
  42956. this._touches.forEach(function (touch) {
  42957. if (touch.pointerId === _this._joystickPointerID) {
  42958. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  42959. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  42960. VirtualJoystick.vjCanvasContext.beginPath();
  42961. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42962. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42963. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  42964. VirtualJoystick.vjCanvasContext.stroke();
  42965. VirtualJoystick.vjCanvasContext.closePath();
  42966. VirtualJoystick.vjCanvasContext.beginPath();
  42967. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42968. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42969. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  42970. VirtualJoystick.vjCanvasContext.stroke();
  42971. VirtualJoystick.vjCanvasContext.closePath();
  42972. VirtualJoystick.vjCanvasContext.beginPath();
  42973. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42974. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  42975. VirtualJoystick.vjCanvasContext.stroke();
  42976. VirtualJoystick.vjCanvasContext.closePath();
  42977. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  42978. }
  42979. else {
  42980. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42981. VirtualJoystick.vjCanvasContext.beginPath();
  42982. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  42983. VirtualJoystick.vjCanvasContext.beginPath();
  42984. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  42985. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42986. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  42987. VirtualJoystick.vjCanvasContext.stroke();
  42988. VirtualJoystick.vjCanvasContext.closePath();
  42989. touch.prevX = touch.x;
  42990. touch.prevY = touch.y;
  42991. }
  42992. ;
  42993. });
  42994. }
  42995. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42996. };
  42997. VirtualJoystick.prototype.releaseCanvas = function () {
  42998. if (VirtualJoystick.vjCanvas) {
  42999. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  43000. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  43001. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  43002. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  43003. window.removeEventListener("resize", this._onResize);
  43004. document.body.removeChild(VirtualJoystick.vjCanvas);
  43005. VirtualJoystick.vjCanvas = null;
  43006. }
  43007. };
  43008. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  43009. VirtualJoystick._globalJoystickIndex = 0;
  43010. return VirtualJoystick;
  43011. }());
  43012. BABYLON.VirtualJoystick = VirtualJoystick;
  43013. })(BABYLON || (BABYLON = {}));
  43014. var BABYLON;
  43015. (function (BABYLON) {
  43016. // We're mainly based on the logic defined into the FreeCamera code
  43017. var VirtualJoysticksCamera = (function (_super) {
  43018. __extends(VirtualJoysticksCamera, _super);
  43019. function VirtualJoysticksCamera(name, position, scene) {
  43020. _super.call(this, name, position, scene);
  43021. this.inputs.addVirtualJoystick();
  43022. }
  43023. return VirtualJoysticksCamera;
  43024. }(BABYLON.FreeCamera));
  43025. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  43026. })(BABYLON || (BABYLON = {}));
  43027. var BABYLON;
  43028. (function (BABYLON) {
  43029. var FreeCameraVirtualJoystickInput = (function () {
  43030. function FreeCameraVirtualJoystickInput() {
  43031. }
  43032. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  43033. return this._leftjoystick;
  43034. };
  43035. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  43036. return this._rightjoystick;
  43037. };
  43038. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  43039. if (this._leftjoystick) {
  43040. var camera = this.camera;
  43041. var speed = camera._computeLocalCameraSpeed() * 50;
  43042. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  43043. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  43044. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  43045. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  43046. if (!this._leftjoystick.pressed) {
  43047. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  43048. }
  43049. if (!this._rightjoystick.pressed) {
  43050. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  43051. }
  43052. }
  43053. };
  43054. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  43055. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  43056. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  43057. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  43058. this._leftjoystick.setJoystickSensibility(0.15);
  43059. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  43060. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  43061. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  43062. this._rightjoystick.reverseUpDown = true;
  43063. this._rightjoystick.setJoystickSensibility(0.05);
  43064. this._rightjoystick.setJoystickColor("yellow");
  43065. };
  43066. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  43067. this._leftjoystick.releaseCanvas();
  43068. this._rightjoystick.releaseCanvas();
  43069. };
  43070. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  43071. return "FreeCameraVirtualJoystickInput";
  43072. };
  43073. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  43074. return "virtualJoystick";
  43075. };
  43076. return FreeCameraVirtualJoystickInput;
  43077. }());
  43078. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  43079. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  43080. })(BABYLON || (BABYLON = {}));
  43081. var BABYLON;
  43082. (function (BABYLON) {
  43083. var AnaglyphPostProcess = (function (_super) {
  43084. __extends(AnaglyphPostProcess, _super);
  43085. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  43086. var _this = this;
  43087. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  43088. this._passedProcess = rigCameras[0]._rigPostProcess;
  43089. this.onApplyObservable.add(function (effect) {
  43090. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  43091. });
  43092. }
  43093. return AnaglyphPostProcess;
  43094. }(BABYLON.PostProcess));
  43095. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  43096. })(BABYLON || (BABYLON = {}));
  43097. var BABYLON;
  43098. (function (BABYLON) {
  43099. var OutlineRenderer = (function () {
  43100. function OutlineRenderer(scene) {
  43101. this._scene = scene;
  43102. }
  43103. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  43104. var _this = this;
  43105. if (useOverlay === void 0) { useOverlay = false; }
  43106. var scene = this._scene;
  43107. var engine = this._scene.getEngine();
  43108. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43109. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  43110. return;
  43111. }
  43112. var mesh = subMesh.getRenderingMesh();
  43113. var material = subMesh.getMaterial();
  43114. engine.enableEffect(this._effect);
  43115. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  43116. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  43117. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  43118. // Bones
  43119. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43120. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43121. }
  43122. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  43123. // Alpha test
  43124. if (material && material.needAlphaTesting()) {
  43125. var alphaTexture = material.getAlphaTestTexture();
  43126. this._effect.setTexture("diffuseSampler", alphaTexture);
  43127. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43128. }
  43129. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  43130. };
  43131. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  43132. var defines = [];
  43133. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  43134. var mesh = subMesh.getMesh();
  43135. var material = subMesh.getMaterial();
  43136. // Alpha test
  43137. if (material && material.needAlphaTesting()) {
  43138. defines.push("#define ALPHATEST");
  43139. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43140. attribs.push(BABYLON.VertexBuffer.UVKind);
  43141. defines.push("#define UV1");
  43142. }
  43143. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43145. defines.push("#define UV2");
  43146. }
  43147. }
  43148. // Bones
  43149. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43152. if (mesh.numBoneInfluencers > 4) {
  43153. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43154. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43155. }
  43156. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43157. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43158. }
  43159. else {
  43160. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43161. }
  43162. // Instances
  43163. if (useInstances) {
  43164. defines.push("#define INSTANCES");
  43165. attribs.push("world0");
  43166. attribs.push("world1");
  43167. attribs.push("world2");
  43168. attribs.push("world3");
  43169. }
  43170. // Get correct effect
  43171. var join = defines.join("\n");
  43172. if (this._cachedDefines !== join) {
  43173. this._cachedDefines = join;
  43174. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  43175. }
  43176. return this._effect.isReady();
  43177. };
  43178. return OutlineRenderer;
  43179. }());
  43180. BABYLON.OutlineRenderer = OutlineRenderer;
  43181. })(BABYLON || (BABYLON = {}));
  43182. var BABYLON;
  43183. (function (BABYLON) {
  43184. var MeshAssetTask = (function () {
  43185. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  43186. this.name = name;
  43187. this.meshesNames = meshesNames;
  43188. this.rootUrl = rootUrl;
  43189. this.sceneFilename = sceneFilename;
  43190. this.isCompleted = false;
  43191. }
  43192. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43193. var _this = this;
  43194. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  43195. _this.loadedMeshes = meshes;
  43196. _this.loadedParticleSystems = particleSystems;
  43197. _this.loadedSkeletons = skeletons;
  43198. _this.isCompleted = true;
  43199. if (_this.onSuccess) {
  43200. _this.onSuccess(_this);
  43201. }
  43202. onSuccess();
  43203. }, null, function () {
  43204. if (_this.onError) {
  43205. _this.onError(_this);
  43206. }
  43207. onError();
  43208. });
  43209. };
  43210. return MeshAssetTask;
  43211. }());
  43212. BABYLON.MeshAssetTask = MeshAssetTask;
  43213. var TextFileAssetTask = (function () {
  43214. function TextFileAssetTask(name, url) {
  43215. this.name = name;
  43216. this.url = url;
  43217. this.isCompleted = false;
  43218. }
  43219. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43220. var _this = this;
  43221. BABYLON.Tools.LoadFile(this.url, function (data) {
  43222. _this.text = data;
  43223. _this.isCompleted = true;
  43224. if (_this.onSuccess) {
  43225. _this.onSuccess(_this);
  43226. }
  43227. onSuccess();
  43228. }, null, scene.database, false, function () {
  43229. if (_this.onError) {
  43230. _this.onError(_this);
  43231. }
  43232. onError();
  43233. });
  43234. };
  43235. return TextFileAssetTask;
  43236. }());
  43237. BABYLON.TextFileAssetTask = TextFileAssetTask;
  43238. var BinaryFileAssetTask = (function () {
  43239. function BinaryFileAssetTask(name, url) {
  43240. this.name = name;
  43241. this.url = url;
  43242. this.isCompleted = false;
  43243. }
  43244. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43245. var _this = this;
  43246. BABYLON.Tools.LoadFile(this.url, function (data) {
  43247. _this.data = data;
  43248. _this.isCompleted = true;
  43249. if (_this.onSuccess) {
  43250. _this.onSuccess(_this);
  43251. }
  43252. onSuccess();
  43253. }, null, scene.database, true, function () {
  43254. if (_this.onError) {
  43255. _this.onError(_this);
  43256. }
  43257. onError();
  43258. });
  43259. };
  43260. return BinaryFileAssetTask;
  43261. }());
  43262. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  43263. var ImageAssetTask = (function () {
  43264. function ImageAssetTask(name, url) {
  43265. this.name = name;
  43266. this.url = url;
  43267. this.isCompleted = false;
  43268. }
  43269. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43270. var _this = this;
  43271. var img = new Image();
  43272. BABYLON.Tools.SetCorsBehavior(this.url, img);
  43273. img.onload = function () {
  43274. _this.image = img;
  43275. _this.isCompleted = true;
  43276. if (_this.onSuccess) {
  43277. _this.onSuccess(_this);
  43278. }
  43279. onSuccess();
  43280. };
  43281. img.onerror = function () {
  43282. if (_this.onError) {
  43283. _this.onError(_this);
  43284. }
  43285. onError();
  43286. };
  43287. img.src = this.url;
  43288. };
  43289. return ImageAssetTask;
  43290. }());
  43291. BABYLON.ImageAssetTask = ImageAssetTask;
  43292. var TextureAssetTask = (function () {
  43293. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  43294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43295. this.name = name;
  43296. this.url = url;
  43297. this.noMipmap = noMipmap;
  43298. this.invertY = invertY;
  43299. this.samplingMode = samplingMode;
  43300. this.isCompleted = false;
  43301. }
  43302. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43303. var _this = this;
  43304. var onload = function () {
  43305. _this.isCompleted = true;
  43306. if (_this.onSuccess) {
  43307. _this.onSuccess(_this);
  43308. }
  43309. onSuccess();
  43310. };
  43311. var onerror = function () {
  43312. if (_this.onError) {
  43313. _this.onError(_this);
  43314. }
  43315. onError();
  43316. };
  43317. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  43318. };
  43319. return TextureAssetTask;
  43320. }());
  43321. BABYLON.TextureAssetTask = TextureAssetTask;
  43322. var CubeTextureAssetTask = (function () {
  43323. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  43324. this.name = name;
  43325. this.url = url;
  43326. this.extensions = extensions;
  43327. this.noMipmap = noMipmap;
  43328. this.files = files;
  43329. this.isCompleted = false;
  43330. }
  43331. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43332. var _this = this;
  43333. var onload = function () {
  43334. _this.isCompleted = true;
  43335. if (_this.onSuccess) {
  43336. _this.onSuccess(_this);
  43337. }
  43338. onSuccess();
  43339. };
  43340. var onerror = function () {
  43341. if (_this.onError) {
  43342. _this.onError(_this);
  43343. }
  43344. onError();
  43345. };
  43346. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  43347. };
  43348. return CubeTextureAssetTask;
  43349. }());
  43350. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  43351. var AssetsManager = (function () {
  43352. function AssetsManager(scene) {
  43353. this.tasks = new Array();
  43354. this.waitingTasksCount = 0;
  43355. this.useDefaultLoadingScreen = true;
  43356. this._scene = scene;
  43357. }
  43358. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  43359. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  43360. this.tasks.push(task);
  43361. return task;
  43362. };
  43363. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  43364. var task = new TextFileAssetTask(taskName, url);
  43365. this.tasks.push(task);
  43366. return task;
  43367. };
  43368. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  43369. var task = new BinaryFileAssetTask(taskName, url);
  43370. this.tasks.push(task);
  43371. return task;
  43372. };
  43373. AssetsManager.prototype.addImageTask = function (taskName, url) {
  43374. var task = new ImageAssetTask(taskName, url);
  43375. this.tasks.push(task);
  43376. return task;
  43377. };
  43378. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  43379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43380. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  43381. this.tasks.push(task);
  43382. return task;
  43383. };
  43384. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  43385. this.waitingTasksCount--;
  43386. if (this.waitingTasksCount === 0) {
  43387. if (this.onFinish) {
  43388. this.onFinish(this.tasks);
  43389. }
  43390. this._scene.getEngine().hideLoadingUI();
  43391. }
  43392. };
  43393. AssetsManager.prototype._runTask = function (task) {
  43394. var _this = this;
  43395. task.run(this._scene, function () {
  43396. if (_this.onTaskSuccess) {
  43397. _this.onTaskSuccess(task);
  43398. }
  43399. _this._decreaseWaitingTasksCount();
  43400. }, function () {
  43401. if (_this.onTaskError) {
  43402. _this.onTaskError(task);
  43403. }
  43404. _this._decreaseWaitingTasksCount();
  43405. });
  43406. };
  43407. AssetsManager.prototype.reset = function () {
  43408. this.tasks = new Array();
  43409. return this;
  43410. };
  43411. AssetsManager.prototype.load = function () {
  43412. this.waitingTasksCount = this.tasks.length;
  43413. if (this.waitingTasksCount === 0) {
  43414. if (this.onFinish) {
  43415. this.onFinish(this.tasks);
  43416. }
  43417. return this;
  43418. }
  43419. if (this.useDefaultLoadingScreen) {
  43420. this._scene.getEngine().displayLoadingUI();
  43421. }
  43422. for (var index = 0; index < this.tasks.length; index++) {
  43423. var task = this.tasks[index];
  43424. this._runTask(task);
  43425. }
  43426. return this;
  43427. };
  43428. return AssetsManager;
  43429. }());
  43430. BABYLON.AssetsManager = AssetsManager;
  43431. })(BABYLON || (BABYLON = {}));
  43432. var BABYLON;
  43433. (function (BABYLON) {
  43434. var VRCameraMetrics = (function () {
  43435. function VRCameraMetrics() {
  43436. this.compensateDistortion = true;
  43437. }
  43438. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  43439. get: function () {
  43440. return this.hResolution / (2 * this.vResolution);
  43441. },
  43442. enumerable: true,
  43443. configurable: true
  43444. });
  43445. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  43446. get: function () {
  43447. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  43448. },
  43449. enumerable: true,
  43450. configurable: true
  43451. });
  43452. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  43453. get: function () {
  43454. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43455. var h = (4 * meters) / this.hScreenSize;
  43456. return BABYLON.Matrix.Translation(h, 0, 0);
  43457. },
  43458. enumerable: true,
  43459. configurable: true
  43460. });
  43461. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  43462. get: function () {
  43463. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43464. var h = (4 * meters) / this.hScreenSize;
  43465. return BABYLON.Matrix.Translation(-h, 0, 0);
  43466. },
  43467. enumerable: true,
  43468. configurable: true
  43469. });
  43470. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  43471. get: function () {
  43472. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  43473. },
  43474. enumerable: true,
  43475. configurable: true
  43476. });
  43477. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  43478. get: function () {
  43479. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  43480. },
  43481. enumerable: true,
  43482. configurable: true
  43483. });
  43484. VRCameraMetrics.GetDefault = function () {
  43485. var result = new VRCameraMetrics();
  43486. result.hResolution = 1280;
  43487. result.vResolution = 800;
  43488. result.hScreenSize = 0.149759993;
  43489. result.vScreenSize = 0.0935999975;
  43490. result.vScreenCenter = 0.0467999987,
  43491. result.eyeToScreenDistance = 0.0410000011;
  43492. result.lensSeparationDistance = 0.0635000020;
  43493. result.interpupillaryDistance = 0.0640000030;
  43494. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  43495. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  43496. result.postProcessScaleFactor = 1.714605507808412;
  43497. result.lensCenterOffset = 0.151976421;
  43498. return result;
  43499. };
  43500. return VRCameraMetrics;
  43501. }());
  43502. BABYLON.VRCameraMetrics = VRCameraMetrics;
  43503. })(BABYLON || (BABYLON = {}));
  43504. var BABYLON;
  43505. (function (BABYLON) {
  43506. var WebVRFreeCamera = (function (_super) {
  43507. __extends(WebVRFreeCamera, _super);
  43508. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  43509. var _this = this;
  43510. if (compensateDistortion === void 0) { compensateDistortion = false; }
  43511. if (webVROptions === void 0) { webVROptions = {}; }
  43512. _super.call(this, name, position, scene);
  43513. this.webVROptions = webVROptions;
  43514. this._vrDevice = null;
  43515. this._cacheState = null;
  43516. this._vrEnabled = false;
  43517. this._attached = false;
  43518. //enable VR
  43519. this.getEngine().initWebVR();
  43520. if (!this.getEngine().vrDisplaysPromise) {
  43521. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  43522. }
  43523. else {
  43524. //TODO get the metrics updated using the device's eye parameters!
  43525. //TODO also check that the device has the right capabilities!
  43526. this._frameData = new VRFrameData();
  43527. this.getEngine().vrDisplaysPromise.then(function (devices) {
  43528. if (devices.length > 0) {
  43529. _this._vrEnabled = true;
  43530. if (_this.webVROptions.displayName) {
  43531. var found = devices.some(function (device) {
  43532. if (device.displayName === _this.webVROptions.displayName) {
  43533. _this._vrDevice = device;
  43534. return true;
  43535. }
  43536. else {
  43537. return false;
  43538. }
  43539. });
  43540. if (!found) {
  43541. _this._vrDevice = devices[0];
  43542. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  43543. }
  43544. }
  43545. else {
  43546. //choose the first one
  43547. _this._vrDevice = devices[0];
  43548. }
  43549. //reset the rig parameters.
  43550. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  43551. if (_this._attached) {
  43552. _this.getEngine().enableVR(_this._vrDevice);
  43553. }
  43554. }
  43555. else {
  43556. BABYLON.Tools.Error("No WebVR devices found!");
  43557. }
  43558. });
  43559. }
  43560. this.rotationQuaternion = new BABYLON.Quaternion();
  43561. this._quaternionCache = new BABYLON.Quaternion();
  43562. }
  43563. WebVRFreeCamera.prototype._checkInputs = function () {
  43564. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  43565. var currentPost = this._frameData.pose;
  43566. //make sure we have data
  43567. if (currentPost && currentPost.orientation) {
  43568. this._cacheState = currentPost;
  43569. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  43570. if (this.webVROptions.trackPosition && this._cacheState.position) {
  43571. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  43572. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  43573. }
  43574. }
  43575. }
  43576. _super.prototype._checkInputs.call(this);
  43577. };
  43578. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43579. _super.prototype.attachControl.call(this, element, noPreventDefault);
  43580. this._attached = true;
  43581. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43582. if (this._vrEnabled) {
  43583. this.getEngine().enableVR(this._vrDevice);
  43584. }
  43585. };
  43586. WebVRFreeCamera.prototype.detachControl = function (element) {
  43587. _super.prototype.detachControl.call(this, element);
  43588. this._vrEnabled = false;
  43589. this._attached = false;
  43590. this.getEngine().disableVR();
  43591. };
  43592. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  43593. //Backwards comp.
  43594. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  43595. //this.getEngine().switchFullscreen(requestPointerlock);
  43596. };
  43597. WebVRFreeCamera.prototype.getTypeName = function () {
  43598. return "WebVRFreeCamera";
  43599. };
  43600. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  43601. //uses the vrDisplay's "resetPose()".
  43602. //pitch and roll won't be affected.
  43603. this._vrDevice.resetPose();
  43604. };
  43605. return WebVRFreeCamera;
  43606. }(BABYLON.FreeCamera));
  43607. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  43608. })(BABYLON || (BABYLON = {}));
  43609. var BABYLON;
  43610. (function (BABYLON) {
  43611. // Standard optimizations
  43612. var SceneOptimization = (function () {
  43613. function SceneOptimization(priority) {
  43614. if (priority === void 0) { priority = 0; }
  43615. this.priority = priority;
  43616. this.apply = function (scene) {
  43617. return true; // Return true if everything that can be done was applied
  43618. };
  43619. }
  43620. return SceneOptimization;
  43621. }());
  43622. BABYLON.SceneOptimization = SceneOptimization;
  43623. var TextureOptimization = (function (_super) {
  43624. __extends(TextureOptimization, _super);
  43625. function TextureOptimization(priority, maximumSize) {
  43626. var _this = this;
  43627. if (priority === void 0) { priority = 0; }
  43628. if (maximumSize === void 0) { maximumSize = 1024; }
  43629. _super.call(this, priority);
  43630. this.priority = priority;
  43631. this.maximumSize = maximumSize;
  43632. this.apply = function (scene) {
  43633. var allDone = true;
  43634. for (var index = 0; index < scene.textures.length; index++) {
  43635. var texture = scene.textures[index];
  43636. if (!texture.canRescale) {
  43637. continue;
  43638. }
  43639. var currentSize = texture.getSize();
  43640. var maxDimension = Math.max(currentSize.width, currentSize.height);
  43641. if (maxDimension > _this.maximumSize) {
  43642. texture.scale(0.5);
  43643. allDone = false;
  43644. }
  43645. }
  43646. return allDone;
  43647. };
  43648. }
  43649. return TextureOptimization;
  43650. }(SceneOptimization));
  43651. BABYLON.TextureOptimization = TextureOptimization;
  43652. var HardwareScalingOptimization = (function (_super) {
  43653. __extends(HardwareScalingOptimization, _super);
  43654. function HardwareScalingOptimization(priority, maximumScale) {
  43655. var _this = this;
  43656. if (priority === void 0) { priority = 0; }
  43657. if (maximumScale === void 0) { maximumScale = 2; }
  43658. _super.call(this, priority);
  43659. this.priority = priority;
  43660. this.maximumScale = maximumScale;
  43661. this._currentScale = 1;
  43662. this.apply = function (scene) {
  43663. _this._currentScale++;
  43664. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  43665. return _this._currentScale >= _this.maximumScale;
  43666. };
  43667. }
  43668. return HardwareScalingOptimization;
  43669. }(SceneOptimization));
  43670. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  43671. var ShadowsOptimization = (function (_super) {
  43672. __extends(ShadowsOptimization, _super);
  43673. function ShadowsOptimization() {
  43674. _super.apply(this, arguments);
  43675. this.apply = function (scene) {
  43676. scene.shadowsEnabled = false;
  43677. return true;
  43678. };
  43679. }
  43680. return ShadowsOptimization;
  43681. }(SceneOptimization));
  43682. BABYLON.ShadowsOptimization = ShadowsOptimization;
  43683. var PostProcessesOptimization = (function (_super) {
  43684. __extends(PostProcessesOptimization, _super);
  43685. function PostProcessesOptimization() {
  43686. _super.apply(this, arguments);
  43687. this.apply = function (scene) {
  43688. scene.postProcessesEnabled = false;
  43689. return true;
  43690. };
  43691. }
  43692. return PostProcessesOptimization;
  43693. }(SceneOptimization));
  43694. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  43695. var LensFlaresOptimization = (function (_super) {
  43696. __extends(LensFlaresOptimization, _super);
  43697. function LensFlaresOptimization() {
  43698. _super.apply(this, arguments);
  43699. this.apply = function (scene) {
  43700. scene.lensFlaresEnabled = false;
  43701. return true;
  43702. };
  43703. }
  43704. return LensFlaresOptimization;
  43705. }(SceneOptimization));
  43706. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43707. var ParticlesOptimization = (function (_super) {
  43708. __extends(ParticlesOptimization, _super);
  43709. function ParticlesOptimization() {
  43710. _super.apply(this, arguments);
  43711. this.apply = function (scene) {
  43712. scene.particlesEnabled = false;
  43713. return true;
  43714. };
  43715. }
  43716. return ParticlesOptimization;
  43717. }(SceneOptimization));
  43718. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43719. var RenderTargetsOptimization = (function (_super) {
  43720. __extends(RenderTargetsOptimization, _super);
  43721. function RenderTargetsOptimization() {
  43722. _super.apply(this, arguments);
  43723. this.apply = function (scene) {
  43724. scene.renderTargetsEnabled = false;
  43725. return true;
  43726. };
  43727. }
  43728. return RenderTargetsOptimization;
  43729. }(SceneOptimization));
  43730. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43731. var MergeMeshesOptimization = (function (_super) {
  43732. __extends(MergeMeshesOptimization, _super);
  43733. function MergeMeshesOptimization() {
  43734. var _this = this;
  43735. _super.apply(this, arguments);
  43736. this._canBeMerged = function (abstractMesh) {
  43737. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43738. return false;
  43739. }
  43740. var mesh = abstractMesh;
  43741. if (!mesh.isVisible || !mesh.isEnabled()) {
  43742. return false;
  43743. }
  43744. if (mesh.instances.length > 0) {
  43745. return false;
  43746. }
  43747. if (mesh.skeleton || mesh.hasLODLevels) {
  43748. return false;
  43749. }
  43750. if (mesh.parent) {
  43751. return false;
  43752. }
  43753. return true;
  43754. };
  43755. this.apply = function (scene, updateSelectionTree) {
  43756. var globalPool = scene.meshes.slice(0);
  43757. var globalLength = globalPool.length;
  43758. for (var index = 0; index < globalLength; index++) {
  43759. var currentPool = new Array();
  43760. var current = globalPool[index];
  43761. // Checks
  43762. if (!_this._canBeMerged(current)) {
  43763. continue;
  43764. }
  43765. currentPool.push(current);
  43766. // Find compatible meshes
  43767. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43768. var otherMesh = globalPool[subIndex];
  43769. if (!_this._canBeMerged(otherMesh)) {
  43770. continue;
  43771. }
  43772. if (otherMesh.material !== current.material) {
  43773. continue;
  43774. }
  43775. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43776. continue;
  43777. }
  43778. currentPool.push(otherMesh);
  43779. globalLength--;
  43780. globalPool.splice(subIndex, 1);
  43781. subIndex--;
  43782. }
  43783. if (currentPool.length < 2) {
  43784. continue;
  43785. }
  43786. // Merge meshes
  43787. BABYLON.Mesh.MergeMeshes(currentPool);
  43788. }
  43789. if (updateSelectionTree != undefined) {
  43790. if (updateSelectionTree) {
  43791. scene.createOrUpdateSelectionOctree();
  43792. }
  43793. }
  43794. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43795. scene.createOrUpdateSelectionOctree();
  43796. }
  43797. return true;
  43798. };
  43799. }
  43800. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43801. get: function () {
  43802. return MergeMeshesOptimization._UpdateSelectionTree;
  43803. },
  43804. set: function (value) {
  43805. MergeMeshesOptimization._UpdateSelectionTree = value;
  43806. },
  43807. enumerable: true,
  43808. configurable: true
  43809. });
  43810. MergeMeshesOptimization._UpdateSelectionTree = false;
  43811. return MergeMeshesOptimization;
  43812. }(SceneOptimization));
  43813. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43814. // Options
  43815. var SceneOptimizerOptions = (function () {
  43816. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43817. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43818. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43819. this.targetFrameRate = targetFrameRate;
  43820. this.trackerDuration = trackerDuration;
  43821. this.optimizations = new Array();
  43822. }
  43823. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43824. var result = new SceneOptimizerOptions(targetFrameRate);
  43825. var priority = 0;
  43826. result.optimizations.push(new MergeMeshesOptimization(priority));
  43827. result.optimizations.push(new ShadowsOptimization(priority));
  43828. result.optimizations.push(new LensFlaresOptimization(priority));
  43829. // Next priority
  43830. priority++;
  43831. result.optimizations.push(new PostProcessesOptimization(priority));
  43832. result.optimizations.push(new ParticlesOptimization(priority));
  43833. // Next priority
  43834. priority++;
  43835. result.optimizations.push(new TextureOptimization(priority, 1024));
  43836. return result;
  43837. };
  43838. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43839. var result = new SceneOptimizerOptions(targetFrameRate);
  43840. var priority = 0;
  43841. result.optimizations.push(new MergeMeshesOptimization(priority));
  43842. result.optimizations.push(new ShadowsOptimization(priority));
  43843. result.optimizations.push(new LensFlaresOptimization(priority));
  43844. // Next priority
  43845. priority++;
  43846. result.optimizations.push(new PostProcessesOptimization(priority));
  43847. result.optimizations.push(new ParticlesOptimization(priority));
  43848. // Next priority
  43849. priority++;
  43850. result.optimizations.push(new TextureOptimization(priority, 512));
  43851. // Next priority
  43852. priority++;
  43853. result.optimizations.push(new RenderTargetsOptimization(priority));
  43854. // Next priority
  43855. priority++;
  43856. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  43857. return result;
  43858. };
  43859. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  43860. var result = new SceneOptimizerOptions(targetFrameRate);
  43861. var priority = 0;
  43862. result.optimizations.push(new MergeMeshesOptimization(priority));
  43863. result.optimizations.push(new ShadowsOptimization(priority));
  43864. result.optimizations.push(new LensFlaresOptimization(priority));
  43865. // Next priority
  43866. priority++;
  43867. result.optimizations.push(new PostProcessesOptimization(priority));
  43868. result.optimizations.push(new ParticlesOptimization(priority));
  43869. // Next priority
  43870. priority++;
  43871. result.optimizations.push(new TextureOptimization(priority, 256));
  43872. // Next priority
  43873. priority++;
  43874. result.optimizations.push(new RenderTargetsOptimization(priority));
  43875. // Next priority
  43876. priority++;
  43877. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  43878. return result;
  43879. };
  43880. return SceneOptimizerOptions;
  43881. }());
  43882. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  43883. // Scene optimizer tool
  43884. var SceneOptimizer = (function () {
  43885. function SceneOptimizer() {
  43886. }
  43887. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  43888. // TODO: add an epsilon
  43889. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  43890. if (onSuccess) {
  43891. onSuccess();
  43892. }
  43893. return;
  43894. }
  43895. // Apply current level of optimizations
  43896. var allDone = true;
  43897. var noOptimizationApplied = true;
  43898. for (var index = 0; index < options.optimizations.length; index++) {
  43899. var optimization = options.optimizations[index];
  43900. if (optimization.priority === currentPriorityLevel) {
  43901. noOptimizationApplied = false;
  43902. allDone = allDone && optimization.apply(scene);
  43903. }
  43904. }
  43905. // If no optimization was applied, this is a failure :(
  43906. if (noOptimizationApplied) {
  43907. if (onFailure) {
  43908. onFailure();
  43909. }
  43910. return;
  43911. }
  43912. // If all optimizations were done, move to next level
  43913. if (allDone) {
  43914. currentPriorityLevel++;
  43915. }
  43916. // Let's the system running for a specific amount of time before checking FPS
  43917. scene.executeWhenReady(function () {
  43918. setTimeout(function () {
  43919. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  43920. }, options.trackerDuration);
  43921. });
  43922. };
  43923. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  43924. if (!options) {
  43925. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  43926. }
  43927. // Let's the system running for a specific amount of time before checking FPS
  43928. scene.executeWhenReady(function () {
  43929. setTimeout(function () {
  43930. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  43931. }, options.trackerDuration);
  43932. });
  43933. };
  43934. return SceneOptimizer;
  43935. }());
  43936. BABYLON.SceneOptimizer = SceneOptimizer;
  43937. })(BABYLON || (BABYLON = {}));
  43938. var BABYLON;
  43939. (function (BABYLON) {
  43940. var Internals;
  43941. (function (Internals) {
  43942. var MeshLODLevel = (function () {
  43943. function MeshLODLevel(distance, mesh) {
  43944. this.distance = distance;
  43945. this.mesh = mesh;
  43946. }
  43947. return MeshLODLevel;
  43948. }());
  43949. Internals.MeshLODLevel = MeshLODLevel;
  43950. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43951. })(BABYLON || (BABYLON = {}));
  43952. var BABYLON;
  43953. (function (BABYLON) {
  43954. var RawTexture = (function (_super) {
  43955. __extends(RawTexture, _super);
  43956. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43957. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43958. if (invertY === void 0) { invertY = false; }
  43959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43960. _super.call(this, null, scene, !generateMipMaps, invertY);
  43961. this.format = format;
  43962. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43963. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43964. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43965. }
  43966. RawTexture.prototype.update = function (data) {
  43967. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43968. };
  43969. // Statics
  43970. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43971. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43972. if (invertY === void 0) { invertY = false; }
  43973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43974. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43975. };
  43976. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43977. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43978. if (invertY === void 0) { invertY = false; }
  43979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43980. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43981. };
  43982. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43984. if (invertY === void 0) { invertY = false; }
  43985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43986. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43987. };
  43988. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43989. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43990. if (invertY === void 0) { invertY = false; }
  43991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43992. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43993. };
  43994. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43995. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43996. if (invertY === void 0) { invertY = false; }
  43997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43998. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43999. };
  44000. return RawTexture;
  44001. }(BABYLON.Texture));
  44002. BABYLON.RawTexture = RawTexture;
  44003. })(BABYLON || (BABYLON = {}));
  44004. var BABYLON;
  44005. (function (BABYLON) {
  44006. var IndexedVector2 = (function (_super) {
  44007. __extends(IndexedVector2, _super);
  44008. function IndexedVector2(original, index) {
  44009. _super.call(this, original.x, original.y);
  44010. this.index = index;
  44011. }
  44012. return IndexedVector2;
  44013. }(BABYLON.Vector2));
  44014. var PolygonPoints = (function () {
  44015. function PolygonPoints() {
  44016. this.elements = new Array();
  44017. }
  44018. PolygonPoints.prototype.add = function (originalPoints) {
  44019. var _this = this;
  44020. var result = new Array();
  44021. originalPoints.forEach(function (point) {
  44022. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  44023. var newPoint = new IndexedVector2(point, _this.elements.length);
  44024. result.push(newPoint);
  44025. _this.elements.push(newPoint);
  44026. }
  44027. });
  44028. return result;
  44029. };
  44030. PolygonPoints.prototype.computeBounds = function () {
  44031. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44032. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44033. this.elements.forEach(function (point) {
  44034. // x
  44035. if (point.x < lmin.x) {
  44036. lmin.x = point.x;
  44037. }
  44038. else if (point.x > lmax.x) {
  44039. lmax.x = point.x;
  44040. }
  44041. // y
  44042. if (point.y < lmin.y) {
  44043. lmin.y = point.y;
  44044. }
  44045. else if (point.y > lmax.y) {
  44046. lmax.y = point.y;
  44047. }
  44048. });
  44049. return {
  44050. min: lmin,
  44051. max: lmax,
  44052. width: lmax.x - lmin.x,
  44053. height: lmax.y - lmin.y
  44054. };
  44055. };
  44056. return PolygonPoints;
  44057. }());
  44058. var Polygon = (function () {
  44059. function Polygon() {
  44060. }
  44061. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  44062. return [
  44063. new BABYLON.Vector2(xmin, ymin),
  44064. new BABYLON.Vector2(xmax, ymin),
  44065. new BABYLON.Vector2(xmax, ymax),
  44066. new BABYLON.Vector2(xmin, ymax)
  44067. ];
  44068. };
  44069. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  44070. if (cx === void 0) { cx = 0; }
  44071. if (cy === void 0) { cy = 0; }
  44072. if (numberOfSides === void 0) { numberOfSides = 32; }
  44073. var result = new Array();
  44074. var angle = 0;
  44075. var increment = (Math.PI * 2) / numberOfSides;
  44076. for (var i = 0; i < numberOfSides; i++) {
  44077. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  44078. angle -= increment;
  44079. }
  44080. return result;
  44081. };
  44082. Polygon.Parse = function (input) {
  44083. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  44084. var i, result = [];
  44085. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  44086. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  44087. }
  44088. return result;
  44089. };
  44090. Polygon.StartingAt = function (x, y) {
  44091. return BABYLON.Path2.StartingAt(x, y);
  44092. };
  44093. return Polygon;
  44094. }());
  44095. BABYLON.Polygon = Polygon;
  44096. var PolygonMeshBuilder = (function () {
  44097. function PolygonMeshBuilder(name, contours, scene) {
  44098. this._points = new PolygonPoints();
  44099. this._outlinepoints = new PolygonPoints();
  44100. this._holes = [];
  44101. this._epoints = new Array();
  44102. this._eholes = new Array();
  44103. this._name = name;
  44104. this._scene = scene;
  44105. var points;
  44106. if (contours instanceof BABYLON.Path2) {
  44107. points = contours.getPoints();
  44108. }
  44109. else {
  44110. points = contours;
  44111. }
  44112. this._addToepoint(points);
  44113. this._points.add(points);
  44114. this._outlinepoints.add(points);
  44115. }
  44116. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  44117. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  44118. var p = points_1[_i];
  44119. this._epoints.push(p.x, p.y);
  44120. }
  44121. };
  44122. PolygonMeshBuilder.prototype.addHole = function (hole) {
  44123. this._points.add(hole);
  44124. var holepoints = new PolygonPoints();
  44125. holepoints.add(hole);
  44126. this._holes.push(holepoints);
  44127. this._eholes.push(this._epoints.length / 2);
  44128. this._addToepoint(hole);
  44129. return this;
  44130. };
  44131. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  44132. var _this = this;
  44133. if (updatable === void 0) { updatable = false; }
  44134. var result = new BABYLON.Mesh(this._name, this._scene);
  44135. var normals = [];
  44136. var positions = [];
  44137. var uvs = [];
  44138. var bounds = this._points.computeBounds();
  44139. this._points.elements.forEach(function (p) {
  44140. normals.push(0, 1.0, 0);
  44141. positions.push(p.x, 0, p.y);
  44142. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  44143. });
  44144. var indices = [];
  44145. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  44146. for (var i = 0; i < res.length; i++) {
  44147. indices.push(res[i]);
  44148. }
  44149. if (depth > 0) {
  44150. var positionscount = (positions.length / 3); //get the current pointcount
  44151. this._points.elements.forEach(function (p) {
  44152. normals.push(0, -1.0, 0);
  44153. positions.push(p.x, -depth, p.y);
  44154. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  44155. });
  44156. var totalCount = indices.length;
  44157. for (var i = 0; i < totalCount; i += 3) {
  44158. var i0 = indices[i + 0];
  44159. var i1 = indices[i + 1];
  44160. var i2 = indices[i + 2];
  44161. indices.push(i2 + positionscount);
  44162. indices.push(i1 + positionscount);
  44163. indices.push(i0 + positionscount);
  44164. }
  44165. //Add the sides
  44166. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  44167. this._holes.forEach(function (hole) {
  44168. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  44169. });
  44170. }
  44171. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  44172. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  44173. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  44174. result.setIndices(indices);
  44175. return result;
  44176. };
  44177. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  44178. var StartIndex = positions.length / 3;
  44179. var ulength = 0;
  44180. for (var i = 0; i < points.elements.length; i++) {
  44181. var p = points.elements[i];
  44182. var p1;
  44183. if ((i + 1) > points.elements.length - 1) {
  44184. p1 = points.elements[0];
  44185. }
  44186. else {
  44187. p1 = points.elements[i + 1];
  44188. }
  44189. positions.push(p.x, 0, p.y);
  44190. positions.push(p.x, -depth, p.y);
  44191. positions.push(p1.x, 0, p1.y);
  44192. positions.push(p1.x, -depth, p1.y);
  44193. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  44194. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  44195. var v3 = v2.subtract(v1);
  44196. var v4 = new BABYLON.Vector3(0, 1, 0);
  44197. var vn = BABYLON.Vector3.Cross(v3, v4);
  44198. vn = vn.normalize();
  44199. uvs.push(ulength / bounds.width, 0);
  44200. uvs.push(ulength / bounds.width, 1);
  44201. ulength += v3.length();
  44202. uvs.push((ulength / bounds.width), 0);
  44203. uvs.push((ulength / bounds.width), 1);
  44204. if (!flip) {
  44205. normals.push(-vn.x, -vn.y, -vn.z);
  44206. normals.push(-vn.x, -vn.y, -vn.z);
  44207. normals.push(-vn.x, -vn.y, -vn.z);
  44208. normals.push(-vn.x, -vn.y, -vn.z);
  44209. indices.push(StartIndex);
  44210. indices.push(StartIndex + 1);
  44211. indices.push(StartIndex + 2);
  44212. indices.push(StartIndex + 1);
  44213. indices.push(StartIndex + 3);
  44214. indices.push(StartIndex + 2);
  44215. }
  44216. else {
  44217. normals.push(vn.x, vn.y, vn.z);
  44218. normals.push(vn.x, vn.y, vn.z);
  44219. normals.push(vn.x, vn.y, vn.z);
  44220. normals.push(vn.x, vn.y, vn.z);
  44221. indices.push(StartIndex);
  44222. indices.push(StartIndex + 2);
  44223. indices.push(StartIndex + 1);
  44224. indices.push(StartIndex + 1);
  44225. indices.push(StartIndex + 2);
  44226. indices.push(StartIndex + 3);
  44227. }
  44228. StartIndex += 4;
  44229. }
  44230. ;
  44231. };
  44232. return PolygonMeshBuilder;
  44233. }());
  44234. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  44235. })(BABYLON || (BABYLON = {}));
  44236. var BABYLON;
  44237. (function (BABYLON) {
  44238. var Octree = (function () {
  44239. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  44240. if (maxDepth === void 0) { maxDepth = 2; }
  44241. this.maxDepth = maxDepth;
  44242. this.dynamicContent = new Array();
  44243. this._maxBlockCapacity = maxBlockCapacity || 64;
  44244. this._selectionContent = new BABYLON.SmartArray(1024);
  44245. this._creationFunc = creationFunc;
  44246. }
  44247. // Methods
  44248. Octree.prototype.update = function (worldMin, worldMax, entries) {
  44249. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  44250. };
  44251. Octree.prototype.addMesh = function (entry) {
  44252. for (var index = 0; index < this.blocks.length; index++) {
  44253. var block = this.blocks[index];
  44254. block.addEntry(entry);
  44255. }
  44256. };
  44257. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  44258. this._selectionContent.reset();
  44259. for (var index = 0; index < this.blocks.length; index++) {
  44260. var block = this.blocks[index];
  44261. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  44262. }
  44263. if (allowDuplicate) {
  44264. this._selectionContent.concat(this.dynamicContent);
  44265. }
  44266. else {
  44267. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44268. }
  44269. return this._selectionContent;
  44270. };
  44271. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  44272. this._selectionContent.reset();
  44273. for (var index = 0; index < this.blocks.length; index++) {
  44274. var block = this.blocks[index];
  44275. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  44276. }
  44277. if (allowDuplicate) {
  44278. this._selectionContent.concat(this.dynamicContent);
  44279. }
  44280. else {
  44281. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44282. }
  44283. return this._selectionContent;
  44284. };
  44285. Octree.prototype.intersectsRay = function (ray) {
  44286. this._selectionContent.reset();
  44287. for (var index = 0; index < this.blocks.length; index++) {
  44288. var block = this.blocks[index];
  44289. block.intersectsRay(ray, this._selectionContent);
  44290. }
  44291. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44292. return this._selectionContent;
  44293. };
  44294. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  44295. target.blocks = new Array();
  44296. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  44297. // Segmenting space
  44298. for (var x = 0; x < 2; x++) {
  44299. for (var y = 0; y < 2; y++) {
  44300. for (var z = 0; z < 2; z++) {
  44301. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  44302. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  44303. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  44304. block.addEntries(entries);
  44305. target.blocks.push(block);
  44306. }
  44307. }
  44308. }
  44309. };
  44310. Octree.CreationFuncForMeshes = function (entry, block) {
  44311. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44312. block.entries.push(entry);
  44313. }
  44314. };
  44315. Octree.CreationFuncForSubMeshes = function (entry, block) {
  44316. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44317. block.entries.push(entry);
  44318. }
  44319. };
  44320. return Octree;
  44321. }());
  44322. BABYLON.Octree = Octree;
  44323. })(BABYLON || (BABYLON = {}));
  44324. var BABYLON;
  44325. (function (BABYLON) {
  44326. var OctreeBlock = (function () {
  44327. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  44328. this.entries = new Array();
  44329. this._boundingVectors = new Array();
  44330. this._capacity = capacity;
  44331. this._depth = depth;
  44332. this._maxDepth = maxDepth;
  44333. this._creationFunc = creationFunc;
  44334. this._minPoint = minPoint;
  44335. this._maxPoint = maxPoint;
  44336. this._boundingVectors.push(minPoint.clone());
  44337. this._boundingVectors.push(maxPoint.clone());
  44338. this._boundingVectors.push(minPoint.clone());
  44339. this._boundingVectors[2].x = maxPoint.x;
  44340. this._boundingVectors.push(minPoint.clone());
  44341. this._boundingVectors[3].y = maxPoint.y;
  44342. this._boundingVectors.push(minPoint.clone());
  44343. this._boundingVectors[4].z = maxPoint.z;
  44344. this._boundingVectors.push(maxPoint.clone());
  44345. this._boundingVectors[5].z = minPoint.z;
  44346. this._boundingVectors.push(maxPoint.clone());
  44347. this._boundingVectors[6].x = minPoint.x;
  44348. this._boundingVectors.push(maxPoint.clone());
  44349. this._boundingVectors[7].y = minPoint.y;
  44350. }
  44351. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  44352. // Property
  44353. get: function () {
  44354. return this._capacity;
  44355. },
  44356. enumerable: true,
  44357. configurable: true
  44358. });
  44359. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  44360. get: function () {
  44361. return this._minPoint;
  44362. },
  44363. enumerable: true,
  44364. configurable: true
  44365. });
  44366. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  44367. get: function () {
  44368. return this._maxPoint;
  44369. },
  44370. enumerable: true,
  44371. configurable: true
  44372. });
  44373. // Methods
  44374. OctreeBlock.prototype.addEntry = function (entry) {
  44375. if (this.blocks) {
  44376. for (var index = 0; index < this.blocks.length; index++) {
  44377. var block = this.blocks[index];
  44378. block.addEntry(entry);
  44379. }
  44380. return;
  44381. }
  44382. this._creationFunc(entry, this);
  44383. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  44384. this.createInnerBlocks();
  44385. }
  44386. };
  44387. OctreeBlock.prototype.addEntries = function (entries) {
  44388. for (var index = 0; index < entries.length; index++) {
  44389. var mesh = entries[index];
  44390. this.addEntry(mesh);
  44391. }
  44392. };
  44393. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  44394. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  44395. if (this.blocks) {
  44396. for (var index = 0; index < this.blocks.length; index++) {
  44397. var block = this.blocks[index];
  44398. block.select(frustumPlanes, selection, allowDuplicate);
  44399. }
  44400. return;
  44401. }
  44402. if (allowDuplicate) {
  44403. selection.concat(this.entries);
  44404. }
  44405. else {
  44406. selection.concatWithNoDuplicate(this.entries);
  44407. }
  44408. }
  44409. };
  44410. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  44411. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  44412. if (this.blocks) {
  44413. for (var index = 0; index < this.blocks.length; index++) {
  44414. var block = this.blocks[index];
  44415. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  44416. }
  44417. return;
  44418. }
  44419. if (allowDuplicate) {
  44420. selection.concat(this.entries);
  44421. }
  44422. else {
  44423. selection.concatWithNoDuplicate(this.entries);
  44424. }
  44425. }
  44426. };
  44427. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  44428. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  44429. if (this.blocks) {
  44430. for (var index = 0; index < this.blocks.length; index++) {
  44431. var block = this.blocks[index];
  44432. block.intersectsRay(ray, selection);
  44433. }
  44434. return;
  44435. }
  44436. selection.concatWithNoDuplicate(this.entries);
  44437. }
  44438. };
  44439. OctreeBlock.prototype.createInnerBlocks = function () {
  44440. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  44441. };
  44442. return OctreeBlock;
  44443. }());
  44444. BABYLON.OctreeBlock = OctreeBlock;
  44445. })(BABYLON || (BABYLON = {}));
  44446. var BABYLON;
  44447. (function (BABYLON) {
  44448. var BlurPostProcess = (function (_super) {
  44449. __extends(BlurPostProcess, _super);
  44450. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44451. var _this = this;
  44452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44453. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  44454. this.direction = direction;
  44455. this.blurWidth = blurWidth;
  44456. this.onApplyObservable.add(function (effect) {
  44457. effect.setFloat2("screenSize", _this.width, _this.height);
  44458. effect.setVector2("direction", _this.direction);
  44459. effect.setFloat("blurWidth", _this.blurWidth);
  44460. });
  44461. }
  44462. return BlurPostProcess;
  44463. }(BABYLON.PostProcess));
  44464. BABYLON.BlurPostProcess = BlurPostProcess;
  44465. })(BABYLON || (BABYLON = {}));
  44466. var BABYLON;
  44467. (function (BABYLON) {
  44468. var RefractionPostProcess = (function (_super) {
  44469. __extends(RefractionPostProcess, _super);
  44470. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  44471. var _this = this;
  44472. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  44473. this.color = color;
  44474. this.depth = depth;
  44475. this.colorLevel = colorLevel;
  44476. this.onActivateObservable.add(function (cam) {
  44477. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  44478. });
  44479. this.onApplyObservable.add(function (effect) {
  44480. effect.setColor3("baseColor", _this.color);
  44481. effect.setFloat("depth", _this.depth);
  44482. effect.setFloat("colorLevel", _this.colorLevel);
  44483. effect.setTexture("refractionSampler", _this._refRexture);
  44484. });
  44485. }
  44486. // Methods
  44487. RefractionPostProcess.prototype.dispose = function (camera) {
  44488. if (this._refRexture) {
  44489. this._refRexture.dispose();
  44490. }
  44491. _super.prototype.dispose.call(this, camera);
  44492. };
  44493. return RefractionPostProcess;
  44494. }(BABYLON.PostProcess));
  44495. BABYLON.RefractionPostProcess = RefractionPostProcess;
  44496. })(BABYLON || (BABYLON = {}));
  44497. var BABYLON;
  44498. (function (BABYLON) {
  44499. var BlackAndWhitePostProcess = (function (_super) {
  44500. __extends(BlackAndWhitePostProcess, _super);
  44501. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  44502. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  44503. }
  44504. return BlackAndWhitePostProcess;
  44505. }(BABYLON.PostProcess));
  44506. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  44507. })(BABYLON || (BABYLON = {}));
  44508. var BABYLON;
  44509. (function (BABYLON) {
  44510. var ConvolutionPostProcess = (function (_super) {
  44511. __extends(ConvolutionPostProcess, _super);
  44512. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  44513. var _this = this;
  44514. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  44515. this.kernel = kernel;
  44516. this.onApply = function (effect) {
  44517. effect.setFloat2("screenSize", _this.width, _this.height);
  44518. effect.setArray("kernel", _this.kernel);
  44519. };
  44520. }
  44521. // Statics
  44522. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  44523. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  44524. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  44525. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  44526. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  44527. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  44528. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  44529. return ConvolutionPostProcess;
  44530. }(BABYLON.PostProcess));
  44531. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  44532. })(BABYLON || (BABYLON = {}));
  44533. var BABYLON;
  44534. (function (BABYLON) {
  44535. var FilterPostProcess = (function (_super) {
  44536. __extends(FilterPostProcess, _super);
  44537. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  44538. var _this = this;
  44539. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  44540. this.kernelMatrix = kernelMatrix;
  44541. this.onApply = function (effect) {
  44542. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  44543. };
  44544. }
  44545. return FilterPostProcess;
  44546. }(BABYLON.PostProcess));
  44547. BABYLON.FilterPostProcess = FilterPostProcess;
  44548. })(BABYLON || (BABYLON = {}));
  44549. var BABYLON;
  44550. (function (BABYLON) {
  44551. var FxaaPostProcess = (function (_super) {
  44552. __extends(FxaaPostProcess, _super);
  44553. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44554. var _this = this;
  44555. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  44556. this.onSizeChangedObservable.add(function () {
  44557. _this.texelWidth = 1.0 / _this.width;
  44558. _this.texelHeight = 1.0 / _this.height;
  44559. });
  44560. this.onApplyObservable.add(function (effect) {
  44561. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  44562. });
  44563. }
  44564. return FxaaPostProcess;
  44565. }(BABYLON.PostProcess));
  44566. BABYLON.FxaaPostProcess = FxaaPostProcess;
  44567. })(BABYLON || (BABYLON = {}));
  44568. var BABYLON;
  44569. (function (BABYLON) {
  44570. var StereoscopicInterlacePostProcess = (function (_super) {
  44571. __extends(StereoscopicInterlacePostProcess, _super);
  44572. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  44573. var _this = this;
  44574. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  44575. this._passedProcess = rigCameras[0]._rigPostProcess;
  44576. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  44577. this.onSizeChangedObservable.add(function () {
  44578. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  44579. });
  44580. this.onApplyObservable.add(function (effect) {
  44581. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  44582. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  44583. });
  44584. }
  44585. return StereoscopicInterlacePostProcess;
  44586. }(BABYLON.PostProcess));
  44587. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  44588. })(BABYLON || (BABYLON = {}));
  44589. var BABYLON;
  44590. (function (BABYLON) {
  44591. var LensFlare = (function () {
  44592. function LensFlare(size, position, color, imgUrl, system) {
  44593. this.size = size;
  44594. this.position = position;
  44595. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  44596. this.dispose = function () {
  44597. if (this.texture) {
  44598. this.texture.dispose();
  44599. }
  44600. // Remove from scene
  44601. var index = this._system.lensFlares.indexOf(this);
  44602. this._system.lensFlares.splice(index, 1);
  44603. };
  44604. this.color = color || new BABYLON.Color3(1, 1, 1);
  44605. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  44606. this._system = system;
  44607. system.lensFlares.push(this);
  44608. }
  44609. return LensFlare;
  44610. }());
  44611. BABYLON.LensFlare = LensFlare;
  44612. })(BABYLON || (BABYLON = {}));
  44613. var BABYLON;
  44614. (function (BABYLON) {
  44615. var LensFlareSystem = (function () {
  44616. function LensFlareSystem(name, emitter, scene) {
  44617. this.name = name;
  44618. this.lensFlares = new Array();
  44619. this.borderLimit = 300;
  44620. this.viewportBorder = 0;
  44621. this.layerMask = 0x0FFFFFFF;
  44622. this._vertexBuffers = {};
  44623. this._isEnabled = true;
  44624. this._scene = scene;
  44625. this._emitter = emitter;
  44626. this.id = name;
  44627. scene.lensFlareSystems.push(this);
  44628. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  44629. var engine = scene.getEngine();
  44630. // VBO
  44631. var vertices = [];
  44632. vertices.push(1, 1);
  44633. vertices.push(-1, 1);
  44634. vertices.push(-1, -1);
  44635. vertices.push(1, -1);
  44636. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44637. // Indices
  44638. var indices = [];
  44639. indices.push(0);
  44640. indices.push(1);
  44641. indices.push(2);
  44642. indices.push(0);
  44643. indices.push(2);
  44644. indices.push(3);
  44645. this._indexBuffer = engine.createIndexBuffer(indices);
  44646. // Effects
  44647. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  44648. }
  44649. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  44650. get: function () {
  44651. return this._isEnabled;
  44652. },
  44653. set: function (value) {
  44654. this._isEnabled = value;
  44655. },
  44656. enumerable: true,
  44657. configurable: true
  44658. });
  44659. LensFlareSystem.prototype.getScene = function () {
  44660. return this._scene;
  44661. };
  44662. LensFlareSystem.prototype.getEmitter = function () {
  44663. return this._emitter;
  44664. };
  44665. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  44666. this._emitter = newEmitter;
  44667. };
  44668. LensFlareSystem.prototype.getEmitterPosition = function () {
  44669. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  44670. };
  44671. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  44672. var position = this.getEmitterPosition();
  44673. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  44674. this._positionX = position.x;
  44675. this._positionY = position.y;
  44676. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  44677. if (this.viewportBorder > 0) {
  44678. globalViewport.x -= this.viewportBorder;
  44679. globalViewport.y -= this.viewportBorder;
  44680. globalViewport.width += this.viewportBorder * 2;
  44681. globalViewport.height += this.viewportBorder * 2;
  44682. position.x += this.viewportBorder;
  44683. position.y += this.viewportBorder;
  44684. this._positionX += this.viewportBorder;
  44685. this._positionY += this.viewportBorder;
  44686. }
  44687. if (position.z > 0) {
  44688. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  44689. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  44690. return true;
  44691. }
  44692. return true;
  44693. }
  44694. return false;
  44695. };
  44696. LensFlareSystem.prototype._isVisible = function () {
  44697. if (!this._isEnabled) {
  44698. return false;
  44699. }
  44700. var emitterPosition = this.getEmitterPosition();
  44701. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  44702. var distance = direction.length();
  44703. direction.normalize();
  44704. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  44705. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44706. return !pickInfo.hit || pickInfo.distance > distance;
  44707. };
  44708. LensFlareSystem.prototype.render = function () {
  44709. if (!this._effect.isReady())
  44710. return false;
  44711. var engine = this._scene.getEngine();
  44712. var viewport = this._scene.activeCamera.viewport;
  44713. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44714. // Position
  44715. if (!this.computeEffectivePosition(globalViewport)) {
  44716. return false;
  44717. }
  44718. // Visibility
  44719. if (!this._isVisible()) {
  44720. return false;
  44721. }
  44722. // Intensity
  44723. var awayX;
  44724. var awayY;
  44725. if (this._positionX < this.borderLimit + globalViewport.x) {
  44726. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44727. }
  44728. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44729. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44730. }
  44731. else {
  44732. awayX = 0;
  44733. }
  44734. if (this._positionY < this.borderLimit + globalViewport.y) {
  44735. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44736. }
  44737. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44738. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44739. }
  44740. else {
  44741. awayY = 0;
  44742. }
  44743. var away = (awayX > awayY) ? awayX : awayY;
  44744. away -= this.viewportBorder;
  44745. if (away > this.borderLimit) {
  44746. away = this.borderLimit;
  44747. }
  44748. var intensity = 1.0 - (away / this.borderLimit);
  44749. if (intensity < 0) {
  44750. return false;
  44751. }
  44752. if (intensity > 1.0) {
  44753. intensity = 1.0;
  44754. }
  44755. if (this.viewportBorder > 0) {
  44756. globalViewport.x += this.viewportBorder;
  44757. globalViewport.y += this.viewportBorder;
  44758. globalViewport.width -= this.viewportBorder * 2;
  44759. globalViewport.height -= this.viewportBorder * 2;
  44760. this._positionX -= this.viewportBorder;
  44761. this._positionY -= this.viewportBorder;
  44762. }
  44763. // Position
  44764. var centerX = globalViewport.x + globalViewport.width / 2;
  44765. var centerY = globalViewport.y + globalViewport.height / 2;
  44766. var distX = centerX - this._positionX;
  44767. var distY = centerY - this._positionY;
  44768. // Effects
  44769. engine.enableEffect(this._effect);
  44770. engine.setState(false);
  44771. engine.setDepthBuffer(false);
  44772. // VBOs
  44773. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44774. // Flares
  44775. for (var index = 0; index < this.lensFlares.length; index++) {
  44776. var flare = this.lensFlares[index];
  44777. engine.setAlphaMode(flare.alphaMode);
  44778. var x = centerX - (distX * flare.position);
  44779. var y = centerY - (distY * flare.position);
  44780. var cw = flare.size;
  44781. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44782. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  44783. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  44784. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44785. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44786. // Texture
  44787. this._effect.setTexture("textureSampler", flare.texture);
  44788. // Color
  44789. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44790. // Draw order
  44791. engine.draw(true, 0, 6);
  44792. }
  44793. engine.setDepthBuffer(true);
  44794. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44795. return true;
  44796. };
  44797. LensFlareSystem.prototype.dispose = function () {
  44798. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44799. if (vertexBuffer) {
  44800. vertexBuffer.dispose();
  44801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44802. }
  44803. if (this._indexBuffer) {
  44804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44805. this._indexBuffer = null;
  44806. }
  44807. while (this.lensFlares.length) {
  44808. this.lensFlares[0].dispose();
  44809. }
  44810. // Remove from scene
  44811. var index = this._scene.lensFlareSystems.indexOf(this);
  44812. this._scene.lensFlareSystems.splice(index, 1);
  44813. };
  44814. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44815. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44816. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44817. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44818. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44819. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44820. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44821. var parsedFlare = parsedLensFlareSystem.flares[index];
  44822. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44823. }
  44824. return lensFlareSystem;
  44825. };
  44826. LensFlareSystem.prototype.serialize = function () {
  44827. var serializationObject = {};
  44828. serializationObject.id = this.id;
  44829. serializationObject.name = this.name;
  44830. serializationObject.emitterId = this.getEmitter().id;
  44831. serializationObject.borderLimit = this.borderLimit;
  44832. serializationObject.flares = [];
  44833. for (var index = 0; index < this.lensFlares.length; index++) {
  44834. var flare = this.lensFlares[index];
  44835. serializationObject.flares.push({
  44836. size: flare.size,
  44837. position: flare.position,
  44838. color: flare.color.asArray(),
  44839. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44840. });
  44841. }
  44842. return serializationObject;
  44843. };
  44844. return LensFlareSystem;
  44845. }());
  44846. BABYLON.LensFlareSystem = LensFlareSystem;
  44847. })(BABYLON || (BABYLON = {}));
  44848. var BABYLON;
  44849. (function (BABYLON) {
  44850. // We're mainly based on the logic defined into the FreeCamera code
  44851. var DeviceOrientationCamera = (function (_super) {
  44852. __extends(DeviceOrientationCamera, _super);
  44853. function DeviceOrientationCamera(name, position, scene) {
  44854. _super.call(this, name, position, scene);
  44855. this._quaternionCache = new BABYLON.Quaternion();
  44856. this.inputs.addDeviceOrientation();
  44857. }
  44858. DeviceOrientationCamera.prototype.getTypeName = function () {
  44859. return "DeviceOrientationCamera";
  44860. };
  44861. DeviceOrientationCamera.prototype._checkInputs = function () {
  44862. _super.prototype._checkInputs.call(this);
  44863. this._quaternionCache.copyFrom(this.rotationQuaternion);
  44864. if (this._initialQuaternion) {
  44865. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44866. }
  44867. };
  44868. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  44869. var _this = this;
  44870. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  44871. //can only work if this camera has a rotation quaternion already.
  44872. if (!this.rotationQuaternion)
  44873. return;
  44874. if (!this._initialQuaternion) {
  44875. this._initialQuaternion = new BABYLON.Quaternion();
  44876. }
  44877. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  44878. ['x', 'y', 'z'].forEach(function (axisName) {
  44879. if (!axis[axisName]) {
  44880. _this._initialQuaternion[axisName] = 0;
  44881. }
  44882. else {
  44883. _this._initialQuaternion[axisName] *= -1;
  44884. }
  44885. });
  44886. this._initialQuaternion.normalize();
  44887. //force rotation update
  44888. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44889. };
  44890. return DeviceOrientationCamera;
  44891. }(BABYLON.FreeCamera));
  44892. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  44893. })(BABYLON || (BABYLON = {}));
  44894. var BABYLON;
  44895. (function (BABYLON) {
  44896. var VRDeviceOrientationFreeCamera = (function (_super) {
  44897. __extends(VRDeviceOrientationFreeCamera, _super);
  44898. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  44899. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44900. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44901. _super.call(this, name, position, scene);
  44902. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44903. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44904. }
  44905. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  44906. return "VRDeviceOrientationFreeCamera";
  44907. };
  44908. return VRDeviceOrientationFreeCamera;
  44909. }(BABYLON.DeviceOrientationCamera));
  44910. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  44911. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  44912. __extends(VRDeviceOrientationArcRotateCamera, _super);
  44913. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  44914. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44915. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44916. _super.call(this, name, alpha, beta, radius, target, scene);
  44917. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44918. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44919. this.inputs.addVRDeviceOrientation();
  44920. }
  44921. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  44922. return "VRDeviceOrientationArcRotateCamera";
  44923. };
  44924. return VRDeviceOrientationArcRotateCamera;
  44925. }(BABYLON.ArcRotateCamera));
  44926. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  44927. })(BABYLON || (BABYLON = {}));
  44928. var BABYLON;
  44929. (function (BABYLON) {
  44930. // We're mainly based on the logic defined into the FreeCamera code
  44931. var UniversalCamera = (function (_super) {
  44932. __extends(UniversalCamera, _super);
  44933. //-- end properties for backward compatibility for inputs
  44934. function UniversalCamera(name, position, scene) {
  44935. _super.call(this, name, position, scene);
  44936. this.inputs.addGamepad();
  44937. }
  44938. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  44939. //-- Begin properties for backward compatibility for inputs
  44940. get: function () {
  44941. var gamepad = this.inputs.attached["gamepad"];
  44942. if (gamepad)
  44943. return gamepad.gamepadAngularSensibility;
  44944. },
  44945. set: function (value) {
  44946. var gamepad = this.inputs.attached["gamepad"];
  44947. if (gamepad)
  44948. gamepad.gamepadAngularSensibility = value;
  44949. },
  44950. enumerable: true,
  44951. configurable: true
  44952. });
  44953. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  44954. get: function () {
  44955. var gamepad = this.inputs.attached["gamepad"];
  44956. if (gamepad)
  44957. return gamepad.gamepadMoveSensibility;
  44958. },
  44959. set: function (value) {
  44960. var gamepad = this.inputs.attached["gamepad"];
  44961. if (gamepad)
  44962. gamepad.gamepadMoveSensibility = value;
  44963. },
  44964. enumerable: true,
  44965. configurable: true
  44966. });
  44967. UniversalCamera.prototype.getTypeName = function () {
  44968. return "UniversalCamera";
  44969. };
  44970. return UniversalCamera;
  44971. }(BABYLON.TouchCamera));
  44972. BABYLON.UniversalCamera = UniversalCamera;
  44973. })(BABYLON || (BABYLON = {}));
  44974. var BABYLON;
  44975. (function (BABYLON) {
  44976. var Gamepads = (function () {
  44977. function Gamepads(ongamedpadconnected) {
  44978. var _this = this;
  44979. this.babylonGamepads = [];
  44980. this.oneGamepadConnected = false;
  44981. this.isMonitoring = false;
  44982. this.gamepadEventSupported = 'GamepadEvent' in window;
  44983. this.gamepadSupportAvailable = (navigator.getGamepads ||
  44984. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  44985. this._callbackGamepadConnected = ongamedpadconnected;
  44986. if (this.gamepadSupportAvailable) {
  44987. // Checking if the gamepad connected event is supported (like in Firefox)
  44988. if (this.gamepadEventSupported) {
  44989. this._onGamepadConnectedEvent = function (evt) {
  44990. _this._onGamepadConnected(evt);
  44991. };
  44992. this._onGamepadDisonnectedEvent = function (evt) {
  44993. _this._onGamepadDisconnected(evt);
  44994. };
  44995. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44996. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44997. }
  44998. else {
  44999. this._startMonitoringGamepads();
  45000. }
  45001. }
  45002. }
  45003. Gamepads.prototype.dispose = function () {
  45004. if (Gamepads.gamepadDOMInfo) {
  45005. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45006. }
  45007. if (this._onGamepadConnectedEvent) {
  45008. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45009. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45010. this._onGamepadConnectedEvent = null;
  45011. this._onGamepadDisonnectedEvent = null;
  45012. }
  45013. };
  45014. Gamepads.prototype._onGamepadConnected = function (evt) {
  45015. var newGamepad = this._addNewGamepad(evt.gamepad);
  45016. if (this._callbackGamepadConnected)
  45017. this._callbackGamepadConnected(newGamepad);
  45018. this._startMonitoringGamepads();
  45019. };
  45020. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45021. if (!this.oneGamepadConnected) {
  45022. this.oneGamepadConnected = true;
  45023. if (Gamepads.gamepadDOMInfo) {
  45024. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45025. Gamepads.gamepadDOMInfo = null;
  45026. }
  45027. }
  45028. var newGamepad;
  45029. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45030. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  45031. }
  45032. else {
  45033. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45034. }
  45035. this.babylonGamepads.push(newGamepad);
  45036. return newGamepad;
  45037. };
  45038. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45039. // Remove the gamepad from the list of gamepads to monitor.
  45040. for (var i in this.babylonGamepads) {
  45041. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45042. this.babylonGamepads.splice(+i, 1);
  45043. break;
  45044. }
  45045. }
  45046. // If no gamepads are left, stop the polling loop.
  45047. if (this.babylonGamepads.length == 0) {
  45048. this._stopMonitoringGamepads();
  45049. }
  45050. };
  45051. Gamepads.prototype._startMonitoringGamepads = function () {
  45052. if (!this.isMonitoring) {
  45053. this.isMonitoring = true;
  45054. this._checkGamepadsStatus();
  45055. }
  45056. };
  45057. Gamepads.prototype._stopMonitoringGamepads = function () {
  45058. this.isMonitoring = false;
  45059. };
  45060. Gamepads.prototype._checkGamepadsStatus = function () {
  45061. var _this = this;
  45062. // updating gamepad objects
  45063. this._updateGamepadObjects();
  45064. for (var i in this.babylonGamepads) {
  45065. this.babylonGamepads[i].update();
  45066. }
  45067. if (this.isMonitoring) {
  45068. if (window.requestAnimationFrame) {
  45069. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45070. }
  45071. else if (window.mozRequestAnimationFrame) {
  45072. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45073. }
  45074. else if (window.webkitRequestAnimationFrame) {
  45075. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45076. }
  45077. }
  45078. };
  45079. // This function is called only on Chrome, which does not yet support
  45080. // connection/disconnection events, but requires you to monitor
  45081. // an array for changes.
  45082. Gamepads.prototype._updateGamepadObjects = function () {
  45083. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45084. for (var i = 0; i < gamepads.length; i++) {
  45085. if (gamepads[i]) {
  45086. if (!(gamepads[i].index in this.babylonGamepads)) {
  45087. var newGamepad = this._addNewGamepad(gamepads[i]);
  45088. if (this._callbackGamepadConnected) {
  45089. this._callbackGamepadConnected(newGamepad);
  45090. }
  45091. }
  45092. else {
  45093. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45094. }
  45095. }
  45096. }
  45097. };
  45098. return Gamepads;
  45099. }());
  45100. BABYLON.Gamepads = Gamepads;
  45101. var StickValues = (function () {
  45102. function StickValues(x, y) {
  45103. this.x = x;
  45104. this.y = y;
  45105. }
  45106. return StickValues;
  45107. }());
  45108. BABYLON.StickValues = StickValues;
  45109. var Gamepad = (function () {
  45110. function Gamepad(id, index, browserGamepad) {
  45111. this.id = id;
  45112. this.index = index;
  45113. this.browserGamepad = browserGamepad;
  45114. if (this.browserGamepad.axes.length >= 2) {
  45115. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45116. }
  45117. if (this.browserGamepad.axes.length >= 4) {
  45118. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45119. }
  45120. }
  45121. Gamepad.prototype.onleftstickchanged = function (callback) {
  45122. this._onleftstickchanged = callback;
  45123. };
  45124. Gamepad.prototype.onrightstickchanged = function (callback) {
  45125. this._onrightstickchanged = callback;
  45126. };
  45127. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45128. get: function () {
  45129. return this._leftStick;
  45130. },
  45131. set: function (newValues) {
  45132. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45133. this._onleftstickchanged(newValues);
  45134. }
  45135. this._leftStick = newValues;
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45141. get: function () {
  45142. return this._rightStick;
  45143. },
  45144. set: function (newValues) {
  45145. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45146. this._onrightstickchanged(newValues);
  45147. }
  45148. this._rightStick = newValues;
  45149. },
  45150. enumerable: true,
  45151. configurable: true
  45152. });
  45153. Gamepad.prototype.update = function () {
  45154. if (this._leftStick) {
  45155. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45156. }
  45157. if (this._rightStick) {
  45158. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45159. }
  45160. };
  45161. return Gamepad;
  45162. }());
  45163. BABYLON.Gamepad = Gamepad;
  45164. var GenericPad = (function (_super) {
  45165. __extends(GenericPad, _super);
  45166. function GenericPad(id, index, gamepad) {
  45167. _super.call(this, id, index, gamepad);
  45168. this.id = id;
  45169. this.index = index;
  45170. this.gamepad = gamepad;
  45171. this._buttons = new Array(gamepad.buttons.length);
  45172. }
  45173. GenericPad.prototype.onbuttondown = function (callback) {
  45174. this._onbuttondown = callback;
  45175. };
  45176. GenericPad.prototype.onbuttonup = function (callback) {
  45177. this._onbuttonup = callback;
  45178. };
  45179. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45180. if (newValue !== currentValue) {
  45181. if (this._onbuttondown && newValue === 1) {
  45182. this._onbuttondown(buttonIndex);
  45183. }
  45184. if (this._onbuttonup && newValue === 0) {
  45185. this._onbuttonup(buttonIndex);
  45186. }
  45187. }
  45188. return newValue;
  45189. };
  45190. GenericPad.prototype.update = function () {
  45191. _super.prototype.update.call(this);
  45192. for (var index = 0; index < this._buttons.length; index++) {
  45193. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45194. }
  45195. };
  45196. return GenericPad;
  45197. }(Gamepad));
  45198. BABYLON.GenericPad = GenericPad;
  45199. (function (Xbox360Button) {
  45200. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45201. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45202. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45203. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45204. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45205. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45206. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45207. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45208. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45209. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45210. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45211. var Xbox360Button = BABYLON.Xbox360Button;
  45212. (function (Xbox360Dpad) {
  45213. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45214. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45215. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45216. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45217. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45218. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  45219. var Xbox360Pad = (function (_super) {
  45220. __extends(Xbox360Pad, _super);
  45221. function Xbox360Pad() {
  45222. _super.apply(this, arguments);
  45223. this._leftTrigger = 0;
  45224. this._rightTrigger = 0;
  45225. this._buttonA = 0;
  45226. this._buttonB = 0;
  45227. this._buttonX = 0;
  45228. this._buttonY = 0;
  45229. this._buttonBack = 0;
  45230. this._buttonStart = 0;
  45231. this._buttonLB = 0;
  45232. this._buttonRB = 0;
  45233. this._buttonLeftStick = 0;
  45234. this._buttonRightStick = 0;
  45235. this._dPadUp = 0;
  45236. this._dPadDown = 0;
  45237. this._dPadLeft = 0;
  45238. this._dPadRight = 0;
  45239. }
  45240. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45241. this._onlefttriggerchanged = callback;
  45242. };
  45243. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45244. this._onrighttriggerchanged = callback;
  45245. };
  45246. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45247. get: function () {
  45248. return this._leftTrigger;
  45249. },
  45250. set: function (newValue) {
  45251. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45252. this._onlefttriggerchanged(newValue);
  45253. }
  45254. this._leftTrigger = newValue;
  45255. },
  45256. enumerable: true,
  45257. configurable: true
  45258. });
  45259. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45260. get: function () {
  45261. return this._rightTrigger;
  45262. },
  45263. set: function (newValue) {
  45264. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45265. this._onrighttriggerchanged(newValue);
  45266. }
  45267. this._rightTrigger = newValue;
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45273. this._onbuttondown = callback;
  45274. };
  45275. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45276. this._onbuttonup = callback;
  45277. };
  45278. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45279. this._ondpaddown = callback;
  45280. };
  45281. Xbox360Pad.prototype.ondpadup = function (callback) {
  45282. this._ondpadup = callback;
  45283. };
  45284. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45285. if (newValue !== currentValue) {
  45286. if (this._onbuttondown && newValue === 1) {
  45287. this._onbuttondown(buttonType);
  45288. }
  45289. if (this._onbuttonup && newValue === 0) {
  45290. this._onbuttonup(buttonType);
  45291. }
  45292. }
  45293. return newValue;
  45294. };
  45295. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45296. if (newValue !== currentValue) {
  45297. if (this._ondpaddown && newValue === 1) {
  45298. this._ondpaddown(buttonType);
  45299. }
  45300. if (this._ondpadup && newValue === 0) {
  45301. this._ondpadup(buttonType);
  45302. }
  45303. }
  45304. return newValue;
  45305. };
  45306. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45307. get: function () {
  45308. return this._buttonA;
  45309. },
  45310. set: function (value) {
  45311. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45312. },
  45313. enumerable: true,
  45314. configurable: true
  45315. });
  45316. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45317. get: function () {
  45318. return this._buttonB;
  45319. },
  45320. set: function (value) {
  45321. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45322. },
  45323. enumerable: true,
  45324. configurable: true
  45325. });
  45326. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45327. get: function () {
  45328. return this._buttonX;
  45329. },
  45330. set: function (value) {
  45331. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45332. },
  45333. enumerable: true,
  45334. configurable: true
  45335. });
  45336. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45337. get: function () {
  45338. return this._buttonY;
  45339. },
  45340. set: function (value) {
  45341. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45347. get: function () {
  45348. return this._buttonStart;
  45349. },
  45350. set: function (value) {
  45351. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45357. get: function () {
  45358. return this._buttonBack;
  45359. },
  45360. set: function (value) {
  45361. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45362. },
  45363. enumerable: true,
  45364. configurable: true
  45365. });
  45366. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45367. get: function () {
  45368. return this._buttonLB;
  45369. },
  45370. set: function (value) {
  45371. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45372. },
  45373. enumerable: true,
  45374. configurable: true
  45375. });
  45376. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45377. get: function () {
  45378. return this._buttonRB;
  45379. },
  45380. set: function (value) {
  45381. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45382. },
  45383. enumerable: true,
  45384. configurable: true
  45385. });
  45386. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45387. get: function () {
  45388. return this._buttonLeftStick;
  45389. },
  45390. set: function (value) {
  45391. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45392. },
  45393. enumerable: true,
  45394. configurable: true
  45395. });
  45396. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45397. get: function () {
  45398. return this._buttonRightStick;
  45399. },
  45400. set: function (value) {
  45401. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45402. },
  45403. enumerable: true,
  45404. configurable: true
  45405. });
  45406. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45407. get: function () {
  45408. return this._dPadUp;
  45409. },
  45410. set: function (value) {
  45411. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45412. },
  45413. enumerable: true,
  45414. configurable: true
  45415. });
  45416. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45417. get: function () {
  45418. return this._dPadDown;
  45419. },
  45420. set: function (value) {
  45421. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45427. get: function () {
  45428. return this._dPadLeft;
  45429. },
  45430. set: function (value) {
  45431. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45432. },
  45433. enumerable: true,
  45434. configurable: true
  45435. });
  45436. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45437. get: function () {
  45438. return this._dPadRight;
  45439. },
  45440. set: function (value) {
  45441. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45442. },
  45443. enumerable: true,
  45444. configurable: true
  45445. });
  45446. Xbox360Pad.prototype.update = function () {
  45447. _super.prototype.update.call(this);
  45448. this.buttonA = this.browserGamepad.buttons[0].value;
  45449. this.buttonB = this.browserGamepad.buttons[1].value;
  45450. this.buttonX = this.browserGamepad.buttons[2].value;
  45451. this.buttonY = this.browserGamepad.buttons[3].value;
  45452. this.buttonLB = this.browserGamepad.buttons[4].value;
  45453. this.buttonRB = this.browserGamepad.buttons[5].value;
  45454. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45455. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45456. this.buttonBack = this.browserGamepad.buttons[8].value;
  45457. this.buttonStart = this.browserGamepad.buttons[9].value;
  45458. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45459. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45460. this.dPadUp = this.browserGamepad.buttons[12].value;
  45461. this.dPadDown = this.browserGamepad.buttons[13].value;
  45462. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45463. this.dPadRight = this.browserGamepad.buttons[15].value;
  45464. };
  45465. return Xbox360Pad;
  45466. }(Gamepad));
  45467. BABYLON.Xbox360Pad = Xbox360Pad;
  45468. })(BABYLON || (BABYLON = {}));
  45469. var BABYLON;
  45470. (function (BABYLON) {
  45471. // We're mainly based on the logic defined into the FreeCamera code
  45472. var GamepadCamera = (function (_super) {
  45473. __extends(GamepadCamera, _super);
  45474. //-- end properties for backward compatibility for inputs
  45475. function GamepadCamera(name, position, scene) {
  45476. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  45477. _super.call(this, name, position, scene);
  45478. }
  45479. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45480. //-- Begin properties for backward compatibility for inputs
  45481. get: function () {
  45482. var gamepad = this.inputs.attached["gamepad"];
  45483. if (gamepad)
  45484. return gamepad.gamepadAngularSensibility;
  45485. },
  45486. set: function (value) {
  45487. var gamepad = this.inputs.attached["gamepad"];
  45488. if (gamepad)
  45489. gamepad.gamepadAngularSensibility = value;
  45490. },
  45491. enumerable: true,
  45492. configurable: true
  45493. });
  45494. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45495. get: function () {
  45496. var gamepad = this.inputs.attached["gamepad"];
  45497. if (gamepad)
  45498. return gamepad.gamepadMoveSensibility;
  45499. },
  45500. set: function (value) {
  45501. var gamepad = this.inputs.attached["gamepad"];
  45502. if (gamepad)
  45503. gamepad.gamepadMoveSensibility = value;
  45504. },
  45505. enumerable: true,
  45506. configurable: true
  45507. });
  45508. GamepadCamera.prototype.getTypeName = function () {
  45509. return "GamepadCamera";
  45510. };
  45511. return GamepadCamera;
  45512. }(BABYLON.UniversalCamera));
  45513. BABYLON.GamepadCamera = GamepadCamera;
  45514. })(BABYLON || (BABYLON = {}));
  45515. var BABYLON;
  45516. (function (BABYLON) {
  45517. var Analyser = (function () {
  45518. function Analyser(scene) {
  45519. this.SMOOTHING = 0.75;
  45520. this.FFT_SIZE = 512;
  45521. this.BARGRAPHAMPLITUDE = 256;
  45522. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45523. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45524. this._scene = scene;
  45525. this._audioEngine = BABYLON.Engine.audioEngine;
  45526. if (this._audioEngine.canUseWebAudio) {
  45527. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45528. this._webAudioAnalyser.minDecibels = -140;
  45529. this._webAudioAnalyser.maxDecibels = 0;
  45530. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45531. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45532. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45533. }
  45534. }
  45535. Analyser.prototype.getFrequencyBinCount = function () {
  45536. if (this._audioEngine.canUseWebAudio) {
  45537. return this._webAudioAnalyser.frequencyBinCount;
  45538. }
  45539. else {
  45540. return 0;
  45541. }
  45542. };
  45543. Analyser.prototype.getByteFrequencyData = function () {
  45544. if (this._audioEngine.canUseWebAudio) {
  45545. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45546. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45547. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45548. }
  45549. return this._byteFreqs;
  45550. };
  45551. Analyser.prototype.getByteTimeDomainData = function () {
  45552. if (this._audioEngine.canUseWebAudio) {
  45553. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45554. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45555. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45556. }
  45557. return this._byteTime;
  45558. };
  45559. Analyser.prototype.getFloatFrequencyData = function () {
  45560. if (this._audioEngine.canUseWebAudio) {
  45561. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45562. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45563. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45564. }
  45565. return this._floatFreqs;
  45566. };
  45567. Analyser.prototype.drawDebugCanvas = function () {
  45568. var _this = this;
  45569. if (this._audioEngine.canUseWebAudio) {
  45570. if (!this._debugCanvas) {
  45571. this._debugCanvas = document.createElement("canvas");
  45572. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45573. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45574. this._debugCanvas.style.position = "absolute";
  45575. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45576. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45577. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45578. document.body.appendChild(this._debugCanvas);
  45579. this._registerFunc = function () {
  45580. _this.drawDebugCanvas();
  45581. };
  45582. this._scene.registerBeforeRender(this._registerFunc);
  45583. }
  45584. if (this._registerFunc) {
  45585. var workingArray = this.getByteFrequencyData();
  45586. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45587. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45588. // Draw the frequency domain chart.
  45589. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45590. var value = workingArray[i];
  45591. var percent = value / this.BARGRAPHAMPLITUDE;
  45592. var height = this.DEBUGCANVASSIZE.height * percent;
  45593. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45594. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45595. var hue = i / this.getFrequencyBinCount() * 360;
  45596. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45597. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45598. }
  45599. }
  45600. }
  45601. };
  45602. Analyser.prototype.stopDebugCanvas = function () {
  45603. if (this._debugCanvas) {
  45604. this._scene.unregisterBeforeRender(this._registerFunc);
  45605. this._registerFunc = null;
  45606. document.body.removeChild(this._debugCanvas);
  45607. this._debugCanvas = null;
  45608. this._debugCanvasContext = null;
  45609. }
  45610. };
  45611. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45612. if (this._audioEngine.canUseWebAudio) {
  45613. inputAudioNode.connect(this._webAudioAnalyser);
  45614. this._webAudioAnalyser.connect(outputAudioNode);
  45615. }
  45616. };
  45617. Analyser.prototype.dispose = function () {
  45618. if (this._audioEngine.canUseWebAudio) {
  45619. this._webAudioAnalyser.disconnect();
  45620. }
  45621. };
  45622. return Analyser;
  45623. }());
  45624. BABYLON.Analyser = Analyser;
  45625. })(BABYLON || (BABYLON = {}));
  45626. var BABYLON;
  45627. (function (BABYLON) {
  45628. var DepthRenderer = (function () {
  45629. function DepthRenderer(scene, type) {
  45630. var _this = this;
  45631. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45632. this._viewMatrix = BABYLON.Matrix.Zero();
  45633. this._projectionMatrix = BABYLON.Matrix.Zero();
  45634. this._transformMatrix = BABYLON.Matrix.Zero();
  45635. this._worldViewProjection = BABYLON.Matrix.Zero();
  45636. this._scene = scene;
  45637. var engine = scene.getEngine();
  45638. // Render target
  45639. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45640. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45641. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45642. this._depthMap.refreshRate = 1;
  45643. this._depthMap.renderParticles = false;
  45644. this._depthMap.renderList = null;
  45645. // set default depth value to 1.0 (far away)
  45646. this._depthMap.onClearObservable.add(function (engine) {
  45647. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45648. });
  45649. // Custom render function
  45650. var renderSubMesh = function (subMesh) {
  45651. var mesh = subMesh.getRenderingMesh();
  45652. var scene = _this._scene;
  45653. var engine = scene.getEngine();
  45654. // Culling
  45655. engine.setState(subMesh.getMaterial().backFaceCulling);
  45656. // Managing instances
  45657. var batch = mesh._getInstancesRenderList(subMesh._id);
  45658. if (batch.mustReturn) {
  45659. return;
  45660. }
  45661. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45662. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45663. engine.enableEffect(_this._effect);
  45664. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45665. var material = subMesh.getMaterial();
  45666. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45667. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45668. // Alpha test
  45669. if (material && material.needAlphaTesting()) {
  45670. var alphaTexture = material.getAlphaTestTexture();
  45671. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45672. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45673. }
  45674. // Bones
  45675. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45676. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45677. }
  45678. // Draw
  45679. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45680. }
  45681. };
  45682. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45683. var index;
  45684. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45685. renderSubMesh(opaqueSubMeshes.data[index]);
  45686. }
  45687. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45688. renderSubMesh(alphaTestSubMeshes.data[index]);
  45689. }
  45690. };
  45691. }
  45692. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45693. var material = subMesh.getMaterial();
  45694. if (material.disableDepthWrite) {
  45695. return false;
  45696. }
  45697. var defines = [];
  45698. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45699. var mesh = subMesh.getMesh();
  45700. var scene = mesh.getScene();
  45701. // Alpha test
  45702. if (material && material.needAlphaTesting()) {
  45703. defines.push("#define ALPHATEST");
  45704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45705. attribs.push(BABYLON.VertexBuffer.UVKind);
  45706. defines.push("#define UV1");
  45707. }
  45708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45709. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45710. defines.push("#define UV2");
  45711. }
  45712. }
  45713. // Bones
  45714. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45717. if (mesh.numBoneInfluencers > 4) {
  45718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45720. }
  45721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45722. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45723. }
  45724. else {
  45725. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45726. }
  45727. // Instances
  45728. if (useInstances) {
  45729. defines.push("#define INSTANCES");
  45730. attribs.push("world0");
  45731. attribs.push("world1");
  45732. attribs.push("world2");
  45733. attribs.push("world3");
  45734. }
  45735. // Get correct effect
  45736. var join = defines.join("\n");
  45737. if (this._cachedDefines !== join) {
  45738. this._cachedDefines = join;
  45739. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45740. }
  45741. return this._effect.isReady();
  45742. };
  45743. DepthRenderer.prototype.getDepthMap = function () {
  45744. return this._depthMap;
  45745. };
  45746. // Methods
  45747. DepthRenderer.prototype.dispose = function () {
  45748. this._depthMap.dispose();
  45749. };
  45750. return DepthRenderer;
  45751. }());
  45752. BABYLON.DepthRenderer = DepthRenderer;
  45753. })(BABYLON || (BABYLON = {}));
  45754. var BABYLON;
  45755. (function (BABYLON) {
  45756. var SSAORenderingPipeline = (function (_super) {
  45757. __extends(SSAORenderingPipeline, _super);
  45758. /**
  45759. * @constructor
  45760. * @param {string} name - The rendering pipeline name
  45761. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45762. * @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 }
  45763. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45764. */
  45765. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45766. var _this = this;
  45767. _super.call(this, scene.getEngine(), name);
  45768. // Members
  45769. /**
  45770. * The PassPostProcess id in the pipeline that contains the original scene color
  45771. * @type {string}
  45772. */
  45773. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45774. /**
  45775. * The SSAO PostProcess id in the pipeline
  45776. * @type {string}
  45777. */
  45778. this.SSAORenderEffect = "SSAORenderEffect";
  45779. /**
  45780. * The horizontal blur PostProcess id in the pipeline
  45781. * @type {string}
  45782. */
  45783. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45784. /**
  45785. * The vertical blur PostProcess id in the pipeline
  45786. * @type {string}
  45787. */
  45788. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45789. /**
  45790. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45791. * @type {string}
  45792. */
  45793. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45794. /**
  45795. * The output strength of the SSAO post-process. Default value is 1.0.
  45796. * @type {number}
  45797. */
  45798. this.totalStrength = 1.0;
  45799. /**
  45800. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45801. * @type {number}
  45802. */
  45803. this.radius = 0.0001;
  45804. /**
  45805. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45806. * Must not be equal to fallOff and superior to fallOff.
  45807. * Default value is 0.975
  45808. * @type {number}
  45809. */
  45810. this.area = 0.0075;
  45811. /**
  45812. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45813. * Must not be equal to area and inferior to area.
  45814. * Default value is 0.0
  45815. * @type {number}
  45816. */
  45817. this.fallOff = 0.000001;
  45818. /**
  45819. * The base color of the SSAO post-process
  45820. * The final result is "base + ssao" between [0, 1]
  45821. * @type {number}
  45822. */
  45823. this.base = 0.5;
  45824. this._firstUpdate = true;
  45825. this._scene = scene;
  45826. // Set up assets
  45827. this._createRandomTexture();
  45828. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45829. var ssaoRatio = ratio.ssaoRatio || ratio;
  45830. var combineRatio = ratio.combineRatio || ratio;
  45831. this._ratio = {
  45832. ssaoRatio: ssaoRatio,
  45833. combineRatio: combineRatio
  45834. };
  45835. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45836. this._createSSAOPostProcess(ssaoRatio);
  45837. this._createBlurPostProcess(ssaoRatio);
  45838. this._createSSAOCombinePostProcess(combineRatio);
  45839. // Set up pipeline
  45840. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45842. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45843. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45845. // Finish
  45846. scene.postProcessRenderPipelineManager.addPipeline(this);
  45847. if (cameras)
  45848. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45849. }
  45850. // Public Methods
  45851. /**
  45852. * Returns the horizontal blur PostProcess
  45853. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45854. */
  45855. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45856. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  45857. return null;
  45858. };
  45859. /**
  45860. * Returns the vertical blur PostProcess
  45861. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45862. */
  45863. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45864. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  45865. return null;
  45866. };
  45867. /**
  45868. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45869. */
  45870. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45871. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45872. for (var i = 0; i < this._scene.cameras.length; i++) {
  45873. var camera = this._scene.cameras[i];
  45874. this._originalColorPostProcess.dispose(camera);
  45875. this._ssaoPostProcess.dispose(camera);
  45876. this._blurHPostProcess.dispose(camera);
  45877. this._blurVPostProcess.dispose(camera);
  45878. this._ssaoCombinePostProcess.dispose(camera);
  45879. }
  45880. this._randomTexture.dispose();
  45881. if (disableDepthRender)
  45882. this._scene.disableDepthRenderer();
  45883. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45884. };
  45885. // Private Methods
  45886. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  45887. var _this = this;
  45888. /*
  45889. var samplerOffsets = [
  45890. -8.0, -6.0, -4.0, -2.0,
  45891. 0.0,
  45892. 2.0, 4.0, 6.0, 8.0
  45893. ];
  45894. */
  45895. var samples = 16;
  45896. var samplerOffsets = [];
  45897. for (var i = -8; i < 8; i++) {
  45898. samplerOffsets.push(i * 2);
  45899. }
  45900. 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");
  45901. this._blurHPostProcess.onApply = function (effect) {
  45902. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  45903. effect.setTexture("depthSampler", _this._depthTexture);
  45904. if (_this._firstUpdate) {
  45905. effect.setArray("samplerOffsets", samplerOffsets);
  45906. }
  45907. };
  45908. 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");
  45909. this._blurVPostProcess.onApply = function (effect) {
  45910. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  45911. effect.setTexture("depthSampler", _this._depthTexture);
  45912. if (_this._firstUpdate) {
  45913. effect.setArray("samplerOffsets", samplerOffsets);
  45914. _this._firstUpdate = false;
  45915. }
  45916. };
  45917. };
  45918. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  45919. var _this = this;
  45920. var numSamples = 16;
  45921. var sampleSphere = [
  45922. 0.5381, 0.1856, -0.4319,
  45923. 0.1379, 0.2486, 0.4430,
  45924. 0.3371, 0.5679, -0.0057,
  45925. -0.6999, -0.0451, -0.0019,
  45926. 0.0689, -0.1598, -0.8547,
  45927. 0.0560, 0.0069, -0.1843,
  45928. -0.0146, 0.1402, 0.0762,
  45929. 0.0100, -0.1924, -0.0344,
  45930. -0.3577, -0.5301, -0.4358,
  45931. -0.3169, 0.1063, 0.0158,
  45932. 0.0103, -0.5869, 0.0046,
  45933. -0.0897, -0.4940, 0.3287,
  45934. 0.7119, -0.0154, -0.0918,
  45935. -0.0533, 0.0596, -0.5411,
  45936. 0.0352, -0.0631, 0.5460,
  45937. -0.4776, 0.2847, -0.0271
  45938. ];
  45939. var samplesFactor = 1.0 / numSamples;
  45940. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  45941. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  45942. "area", "fallOff", "base", "range", "viewport"
  45943. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  45944. var viewport = new BABYLON.Vector2(0, 0);
  45945. this._ssaoPostProcess.onApply = function (effect) {
  45946. if (_this._firstUpdate) {
  45947. effect.setArray3("sampleSphere", sampleSphere);
  45948. effect.setFloat("samplesFactor", samplesFactor);
  45949. effect.setFloat("randTextureTiles", 4.0);
  45950. }
  45951. effect.setFloat("totalStrength", _this.totalStrength);
  45952. effect.setFloat("radius", _this.radius);
  45953. effect.setFloat("area", _this.area);
  45954. effect.setFloat("fallOff", _this.fallOff);
  45955. effect.setFloat("base", _this.base);
  45956. effect.setTexture("textureSampler", _this._depthTexture);
  45957. effect.setTexture("randomSampler", _this._randomTexture);
  45958. };
  45959. };
  45960. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  45961. var _this = this;
  45962. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45963. this._ssaoCombinePostProcess.onApply = function (effect) {
  45964. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  45965. };
  45966. };
  45967. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  45968. var size = 512;
  45969. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45970. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45971. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45972. var context = this._randomTexture.getContext();
  45973. var rand = function (min, max) {
  45974. return Math.random() * (max - min) + min;
  45975. };
  45976. var randVector = BABYLON.Vector3.Zero();
  45977. for (var x = 0; x < size; x++) {
  45978. for (var y = 0; y < size; y++) {
  45979. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  45980. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  45981. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  45982. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  45983. context.fillRect(x, y, 1, 1);
  45984. }
  45985. }
  45986. this._randomTexture.update(false);
  45987. };
  45988. __decorate([
  45989. BABYLON.serialize()
  45990. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  45991. __decorate([
  45992. BABYLON.serialize()
  45993. ], SSAORenderingPipeline.prototype, "radius", void 0);
  45994. __decorate([
  45995. BABYLON.serialize()
  45996. ], SSAORenderingPipeline.prototype, "area", void 0);
  45997. __decorate([
  45998. BABYLON.serialize()
  45999. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  46000. __decorate([
  46001. BABYLON.serialize()
  46002. ], SSAORenderingPipeline.prototype, "base", void 0);
  46003. __decorate([
  46004. BABYLON.serialize()
  46005. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  46006. return SSAORenderingPipeline;
  46007. }(BABYLON.PostProcessRenderPipeline));
  46008. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46009. })(BABYLON || (BABYLON = {}));
  46010. var BABYLON;
  46011. (function (BABYLON) {
  46012. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  46013. var VolumetricLightScatteringPostProcess = (function (_super) {
  46014. __extends(VolumetricLightScatteringPostProcess, _super);
  46015. /**
  46016. * @constructor
  46017. * @param {string} name - The post-process name
  46018. * @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)
  46019. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  46020. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  46021. * @param {number} samples - The post-process quality, default 100
  46022. * @param {number} samplingMode - The post-process filtering mode
  46023. * @param {BABYLON.Engine} engine - The babylon engine
  46024. * @param {boolean} reusable - If the post-process is reusable
  46025. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  46026. */
  46027. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  46028. var _this = this;
  46029. if (samples === void 0) { samples = 100; }
  46030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46031. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  46032. this._screenCoordinates = BABYLON.Vector2.Zero();
  46033. /**
  46034. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  46035. * @type {Vector3}
  46036. */
  46037. this.customMeshPosition = BABYLON.Vector3.Zero();
  46038. /**
  46039. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  46040. * @type {boolean}
  46041. */
  46042. this.useCustomMeshPosition = false;
  46043. /**
  46044. * If the post-process should inverse the light scattering direction
  46045. * @type {boolean}
  46046. */
  46047. this.invert = true;
  46048. /**
  46049. * Array containing the excluded meshes not rendered in the internal pass
  46050. */
  46051. this.excludedMeshes = new Array();
  46052. /**
  46053. * Controls the overall intensity of the post-process
  46054. * @type {number}
  46055. */
  46056. this.exposure = 0.3;
  46057. /**
  46058. * Dissipates each sample's contribution in range [0, 1]
  46059. * @type {number}
  46060. */
  46061. this.decay = 0.96815;
  46062. /**
  46063. * Controls the overall intensity of each sample
  46064. * @type {number}
  46065. */
  46066. this.weight = 0.58767;
  46067. /**
  46068. * Controls the density of each sample
  46069. * @type {number}
  46070. */
  46071. this.density = 0.926;
  46072. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  46073. var engine = scene.getEngine();
  46074. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46075. // Configure mesh
  46076. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  46077. // Configure
  46078. this._createPass(scene, ratio.passRatio || ratio);
  46079. this.onActivate = function (camera) {
  46080. if (!_this.isSupported) {
  46081. _this.dispose(camera);
  46082. }
  46083. _this.onActivate = null;
  46084. };
  46085. this.onApplyObservable.add(function (effect) {
  46086. _this._updateMeshScreenCoordinates(scene);
  46087. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  46088. effect.setFloat("exposure", _this.exposure);
  46089. effect.setFloat("decay", _this.decay);
  46090. effect.setFloat("weight", _this.weight);
  46091. effect.setFloat("density", _this.density);
  46092. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  46093. });
  46094. }
  46095. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  46096. get: function () {
  46097. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46098. return false;
  46099. },
  46100. set: function (useDiffuseColor) {
  46101. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46102. },
  46103. enumerable: true,
  46104. configurable: true
  46105. });
  46106. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  46107. var mesh = subMesh.getMesh();
  46108. // Render this.mesh as default
  46109. if (mesh === this.mesh) {
  46110. return mesh.material.isReady(mesh);
  46111. }
  46112. var defines = [];
  46113. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46114. var material = subMesh.getMaterial();
  46115. var needUV = false;
  46116. // Alpha test
  46117. if (material) {
  46118. if (material.needAlphaTesting()) {
  46119. defines.push("#define ALPHATEST");
  46120. }
  46121. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46122. attribs.push(BABYLON.VertexBuffer.UVKind);
  46123. defines.push("#define UV1");
  46124. }
  46125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46126. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46127. defines.push("#define UV2");
  46128. }
  46129. }
  46130. // Bones
  46131. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46132. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46133. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46134. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46135. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46136. }
  46137. else {
  46138. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46139. }
  46140. // Instances
  46141. if (useInstances) {
  46142. defines.push("#define INSTANCES");
  46143. attribs.push("world0");
  46144. attribs.push("world1");
  46145. attribs.push("world2");
  46146. attribs.push("world3");
  46147. }
  46148. // Get correct effect
  46149. var join = defines.join("\n");
  46150. if (this._cachedDefines !== join) {
  46151. this._cachedDefines = join;
  46152. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  46153. }
  46154. return this._volumetricLightScatteringPass.isReady();
  46155. };
  46156. /**
  46157. * Sets the new light position for light scattering effect
  46158. * @param {BABYLON.Vector3} The new custom light position
  46159. */
  46160. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  46161. this.customMeshPosition = position;
  46162. };
  46163. /**
  46164. * Returns the light position for light scattering effect
  46165. * @return {BABYLON.Vector3} The custom light position
  46166. */
  46167. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  46168. return this.customMeshPosition;
  46169. };
  46170. /**
  46171. * Disposes the internal assets and detaches the post-process from the camera
  46172. */
  46173. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  46174. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  46175. if (rttIndex !== -1) {
  46176. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  46177. }
  46178. this._volumetricLightScatteringRTT.dispose();
  46179. _super.prototype.dispose.call(this, camera);
  46180. };
  46181. /**
  46182. * Returns the render target texture used by the post-process
  46183. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  46184. */
  46185. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  46186. return this._volumetricLightScatteringRTT;
  46187. };
  46188. // Private methods
  46189. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  46190. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  46191. return true;
  46192. }
  46193. return false;
  46194. };
  46195. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  46196. var _this = this;
  46197. var engine = scene.getEngine();
  46198. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  46199. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46200. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46201. this._volumetricLightScatteringRTT.renderList = null;
  46202. this._volumetricLightScatteringRTT.renderParticles = false;
  46203. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  46204. // Custom render function for submeshes
  46205. var renderSubMesh = function (subMesh) {
  46206. var mesh = subMesh.getRenderingMesh();
  46207. if (_this._meshExcluded(mesh)) {
  46208. return;
  46209. }
  46210. var scene = mesh.getScene();
  46211. var engine = scene.getEngine();
  46212. // Culling
  46213. engine.setState(subMesh.getMaterial().backFaceCulling);
  46214. // Managing instances
  46215. var batch = mesh._getInstancesRenderList(subMesh._id);
  46216. if (batch.mustReturn) {
  46217. return;
  46218. }
  46219. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46220. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46221. var effect = _this._volumetricLightScatteringPass;
  46222. if (mesh === _this.mesh) {
  46223. effect = subMesh.getMaterial().getEffect();
  46224. }
  46225. engine.enableEffect(effect);
  46226. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  46227. if (mesh === _this.mesh) {
  46228. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  46229. }
  46230. else {
  46231. var material = subMesh.getMaterial();
  46232. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  46233. // Alpha test
  46234. if (material && material.needAlphaTesting()) {
  46235. var alphaTexture = material.getAlphaTestTexture();
  46236. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  46237. if (alphaTexture) {
  46238. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46239. }
  46240. }
  46241. // Bones
  46242. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46243. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46244. }
  46245. }
  46246. // Draw
  46247. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  46248. }
  46249. };
  46250. // Render target texture callbacks
  46251. var savedSceneClearColor;
  46252. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  46253. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  46254. savedSceneClearColor = scene.clearColor;
  46255. scene.clearColor = sceneClearColor;
  46256. });
  46257. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  46258. scene.clearColor = savedSceneClearColor;
  46259. });
  46260. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46261. var engine = scene.getEngine();
  46262. var index;
  46263. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46264. renderSubMesh(opaqueSubMeshes.data[index]);
  46265. }
  46266. engine.setAlphaTesting(true);
  46267. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46268. renderSubMesh(alphaTestSubMeshes.data[index]);
  46269. }
  46270. engine.setAlphaTesting(false);
  46271. if (transparentSubMeshes.length) {
  46272. // Sort sub meshes
  46273. for (index = 0; index < transparentSubMeshes.length; index++) {
  46274. var submesh = transparentSubMeshes.data[index];
  46275. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  46276. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  46277. }
  46278. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  46279. sortedArray.sort(function (a, b) {
  46280. // Alpha index first
  46281. if (a._alphaIndex > b._alphaIndex) {
  46282. return 1;
  46283. }
  46284. if (a._alphaIndex < b._alphaIndex) {
  46285. return -1;
  46286. }
  46287. // Then distance to camera
  46288. if (a._distanceToCamera < b._distanceToCamera) {
  46289. return 1;
  46290. }
  46291. if (a._distanceToCamera > b._distanceToCamera) {
  46292. return -1;
  46293. }
  46294. return 0;
  46295. });
  46296. // Render sub meshes
  46297. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46298. for (index = 0; index < sortedArray.length; index++) {
  46299. renderSubMesh(sortedArray[index]);
  46300. }
  46301. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46302. }
  46303. };
  46304. };
  46305. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  46306. var transform = scene.getTransformMatrix();
  46307. var meshPosition;
  46308. if (this.useCustomMeshPosition) {
  46309. meshPosition = this.customMeshPosition;
  46310. }
  46311. else if (this.attachedNode) {
  46312. meshPosition = this.attachedNode.position;
  46313. }
  46314. else {
  46315. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  46316. }
  46317. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  46318. this._screenCoordinates.x = pos.x / this._viewPort.width;
  46319. this._screenCoordinates.y = pos.y / this._viewPort.height;
  46320. if (this.invert)
  46321. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  46322. };
  46323. // Static methods
  46324. /**
  46325. * Creates a default mesh for the Volumeric Light Scattering post-process
  46326. * @param {string} The mesh name
  46327. * @param {BABYLON.Scene} The scene where to create the mesh
  46328. * @return {BABYLON.Mesh} the default mesh
  46329. */
  46330. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  46331. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  46332. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  46333. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  46334. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  46335. mesh.material = material;
  46336. return mesh;
  46337. };
  46338. __decorate([
  46339. BABYLON.serializeAsVector3()
  46340. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  46341. __decorate([
  46342. BABYLON.serialize()
  46343. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  46344. __decorate([
  46345. BABYLON.serialize()
  46346. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  46347. __decorate([
  46348. BABYLON.serializeAsMeshReference()
  46349. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  46350. __decorate([
  46351. BABYLON.serialize()
  46352. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  46353. __decorate([
  46354. BABYLON.serialize()
  46355. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  46356. __decorate([
  46357. BABYLON.serialize()
  46358. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  46359. __decorate([
  46360. BABYLON.serialize()
  46361. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  46362. __decorate([
  46363. BABYLON.serialize()
  46364. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  46365. return VolumetricLightScatteringPostProcess;
  46366. }(BABYLON.PostProcess));
  46367. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  46368. })(BABYLON || (BABYLON = {}));
  46369. // BABYLON.JS Chromatic Aberration GLSL Shader
  46370. // Author: Olivier Guyot
  46371. // Separates very slightly R, G and B colors on the edges of the screen
  46372. // Inspired by Francois Tarlier & Martins Upitis
  46373. var BABYLON;
  46374. (function (BABYLON) {
  46375. var LensRenderingPipeline = (function (_super) {
  46376. __extends(LensRenderingPipeline, _super);
  46377. /**
  46378. * @constructor
  46379. *
  46380. * Effect parameters are as follow:
  46381. * {
  46382. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46383. * edge_blur: number; // from 0 to x (1 for realism)
  46384. * distortion: number; // from 0 to x (1 for realism)
  46385. * grain_amount: number; // from 0 to 1
  46386. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46387. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46388. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46389. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46390. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46391. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46392. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46393. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46394. * }
  46395. * Note: if an effect parameter is unset, effect is disabled
  46396. *
  46397. * @param {string} name - The rendering pipeline name
  46398. * @param {object} parameters - An object containing all parameters (see above)
  46399. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46400. * @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)
  46401. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46402. */
  46403. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46404. var _this = this;
  46405. if (ratio === void 0) { ratio = 1.0; }
  46406. _super.call(this, scene.getEngine(), name);
  46407. // Lens effects can be of the following:
  46408. // - chromatic aberration (slight shift of RGB colors)
  46409. // - blur on the edge of the lens
  46410. // - lens distortion
  46411. // - depth-of-field blur & highlights enhancing
  46412. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46413. // - grain effect (noise or custom texture)
  46414. // Two additional texture samplers are needed:
  46415. // - depth map (for depth-of-field)
  46416. // - grain texture
  46417. /**
  46418. * The chromatic aberration PostProcess id in the pipeline
  46419. * @type {string}
  46420. */
  46421. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46422. /**
  46423. * The highlights enhancing PostProcess id in the pipeline
  46424. * @type {string}
  46425. */
  46426. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46427. /**
  46428. * The depth-of-field PostProcess id in the pipeline
  46429. * @type {string}
  46430. */
  46431. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46432. this._scene = scene;
  46433. // Fetch texture samplers
  46434. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46435. if (parameters.grain_texture) {
  46436. this._grainTexture = parameters.grain_texture;
  46437. }
  46438. else {
  46439. this._createGrainTexture();
  46440. }
  46441. // save parameters
  46442. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46443. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46444. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46445. this._distortion = parameters.distortion ? parameters.distortion : 0;
  46446. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46447. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46448. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46449. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46450. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46451. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46452. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46453. // Create effects
  46454. this._createChromaticAberrationPostProcess(ratio);
  46455. this._createHighlightsPostProcess(ratio);
  46456. this._createDepthOfFieldPostProcess(ratio / 4);
  46457. // Set up pipeline
  46458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46459. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46460. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46461. if (this._highlightsGain === -1) {
  46462. this._disableEffect(this.HighlightsEnhancingEffect, null);
  46463. }
  46464. // Finish
  46465. scene.postProcessRenderPipelineManager.addPipeline(this);
  46466. if (cameras) {
  46467. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46468. }
  46469. }
  46470. // public methods (self explanatory)
  46471. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46472. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46473. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46474. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46475. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46476. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46477. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46478. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46479. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46480. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46481. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46482. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46483. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46484. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46485. };
  46486. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46487. this._highlightsPostProcess.updateEffect();
  46488. };
  46489. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46490. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46491. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46492. this._highlightsGain = amount;
  46493. };
  46494. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46495. if (this._highlightsGain === -1) {
  46496. this._highlightsGain = 1.0;
  46497. }
  46498. this._highlightsThreshold = amount;
  46499. };
  46500. LensRenderingPipeline.prototype.disableHighlights = function () {
  46501. this._highlightsGain = -1;
  46502. };
  46503. /**
  46504. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46505. */
  46506. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46507. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46508. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46509. this._chromaticAberrationPostProcess = undefined;
  46510. this._highlightsPostProcess = undefined;
  46511. this._depthOfFieldPostProcess = undefined;
  46512. this._grainTexture.dispose();
  46513. if (disableDepthRender)
  46514. this._scene.disableDepthRenderer();
  46515. };
  46516. // colors shifting and distortion
  46517. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46518. var _this = this;
  46519. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46520. [], // samplers
  46521. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46522. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46523. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46524. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46525. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46526. };
  46527. };
  46528. // highlights enhancing
  46529. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46530. var _this = this;
  46531. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46532. [], // samplers
  46533. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46534. this._highlightsPostProcess.onApply = function (effect) {
  46535. effect.setFloat('gain', _this._highlightsGain);
  46536. effect.setFloat('threshold', _this._highlightsThreshold);
  46537. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46538. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46539. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46540. };
  46541. };
  46542. // colors shifting and distortion
  46543. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46544. var _this = this;
  46545. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46546. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46547. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46548. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46549. this._depthOfFieldPostProcess.onApply = function (effect) {
  46550. effect.setTexture("depthSampler", _this._depthTexture);
  46551. effect.setTexture("grainSampler", _this._grainTexture);
  46552. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46553. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46554. effect.setFloat('grain_amount', _this._grainAmount);
  46555. effect.setBool('blur_noise', _this._blurNoise);
  46556. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46557. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46558. effect.setFloat('distortion', _this._distortion);
  46559. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46560. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46561. effect.setFloat('aperture', _this._dofAperture);
  46562. effect.setFloat('darken', _this._dofDarken);
  46563. effect.setFloat('edge_blur', _this._edgeBlur);
  46564. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46565. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46566. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46567. };
  46568. };
  46569. // creates a black and white random noise texture, 512x512
  46570. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46571. var size = 512;
  46572. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46573. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46574. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46575. var context = this._grainTexture.getContext();
  46576. var rand = function (min, max) {
  46577. return Math.random() * (max - min) + min;
  46578. };
  46579. var value;
  46580. for (var x = 0; x < size; x++) {
  46581. for (var y = 0; y < size; y++) {
  46582. value = Math.floor(rand(0.42, 0.58) * 255);
  46583. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46584. context.fillRect(x, y, 1, 1);
  46585. }
  46586. }
  46587. this._grainTexture.update(false);
  46588. };
  46589. return LensRenderingPipeline;
  46590. }(BABYLON.PostProcessRenderPipeline));
  46591. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46592. })(BABYLON || (BABYLON = {}));
  46593. //
  46594. // This post-process allows the modification of rendered colors by using
  46595. // a 'look-up table' (LUT). This effect is also called Color Grading.
  46596. //
  46597. // The object needs to be provided an url to a texture containing the color
  46598. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  46599. // Use an image editing software to tweak the LUT to match your needs.
  46600. //
  46601. // For an example of a color LUT, see here:
  46602. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  46603. // For explanations on color grading, see here:
  46604. // http://udn.epicgames.com/Three/ColorGrading.html
  46605. //
  46606. var BABYLON;
  46607. (function (BABYLON) {
  46608. var ColorCorrectionPostProcess = (function (_super) {
  46609. __extends(ColorCorrectionPostProcess, _super);
  46610. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  46611. var _this = this;
  46612. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  46613. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46614. this._colorTableTexture.anisotropicFilteringLevel = 1;
  46615. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46616. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46617. this.onApply = function (effect) {
  46618. effect.setTexture("colorTable", _this._colorTableTexture);
  46619. };
  46620. }
  46621. return ColorCorrectionPostProcess;
  46622. }(BABYLON.PostProcess));
  46623. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  46624. })(BABYLON || (BABYLON = {}));
  46625. var BABYLON;
  46626. (function (BABYLON) {
  46627. var AnaglyphFreeCamera = (function (_super) {
  46628. __extends(AnaglyphFreeCamera, _super);
  46629. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  46630. _super.call(this, name, position, scene);
  46631. this.interaxialDistance = interaxialDistance;
  46632. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46633. }
  46634. AnaglyphFreeCamera.prototype.getTypeName = function () {
  46635. return "AnaglyphFreeCamera";
  46636. };
  46637. return AnaglyphFreeCamera;
  46638. }(BABYLON.FreeCamera));
  46639. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  46640. var AnaglyphArcRotateCamera = (function (_super) {
  46641. __extends(AnaglyphArcRotateCamera, _super);
  46642. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  46643. _super.call(this, name, alpha, beta, radius, target, scene);
  46644. this.interaxialDistance = interaxialDistance;
  46645. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46646. }
  46647. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  46648. return "AnaglyphArcRotateCamera";
  46649. };
  46650. return AnaglyphArcRotateCamera;
  46651. }(BABYLON.ArcRotateCamera));
  46652. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  46653. var AnaglyphGamepadCamera = (function (_super) {
  46654. __extends(AnaglyphGamepadCamera, _super);
  46655. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  46656. _super.call(this, name, position, scene);
  46657. this.interaxialDistance = interaxialDistance;
  46658. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46659. }
  46660. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  46661. return "AnaglyphGamepadCamera";
  46662. };
  46663. return AnaglyphGamepadCamera;
  46664. }(BABYLON.GamepadCamera));
  46665. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  46666. var AnaglyphUniversalCamera = (function (_super) {
  46667. __extends(AnaglyphUniversalCamera, _super);
  46668. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  46669. _super.call(this, name, position, scene);
  46670. this.interaxialDistance = interaxialDistance;
  46671. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46672. }
  46673. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  46674. return "AnaglyphUniversalCamera";
  46675. };
  46676. return AnaglyphUniversalCamera;
  46677. }(BABYLON.UniversalCamera));
  46678. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  46679. var StereoscopicFreeCamera = (function (_super) {
  46680. __extends(StereoscopicFreeCamera, _super);
  46681. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46682. _super.call(this, name, position, scene);
  46683. this.interaxialDistance = interaxialDistance;
  46684. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46685. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46686. }
  46687. StereoscopicFreeCamera.prototype.getTypeName = function () {
  46688. return "StereoscopicFreeCamera";
  46689. };
  46690. return StereoscopicFreeCamera;
  46691. }(BABYLON.FreeCamera));
  46692. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  46693. var StereoscopicArcRotateCamera = (function (_super) {
  46694. __extends(StereoscopicArcRotateCamera, _super);
  46695. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  46696. _super.call(this, name, alpha, beta, radius, target, scene);
  46697. this.interaxialDistance = interaxialDistance;
  46698. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46699. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46700. }
  46701. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  46702. return "StereoscopicArcRotateCamera";
  46703. };
  46704. return StereoscopicArcRotateCamera;
  46705. }(BABYLON.ArcRotateCamera));
  46706. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46707. var StereoscopicGamepadCamera = (function (_super) {
  46708. __extends(StereoscopicGamepadCamera, _super);
  46709. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46710. _super.call(this, name, position, scene);
  46711. this.interaxialDistance = interaxialDistance;
  46712. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46713. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46714. }
  46715. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46716. return "StereoscopicGamepadCamera";
  46717. };
  46718. return StereoscopicGamepadCamera;
  46719. }(BABYLON.GamepadCamera));
  46720. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46721. var StereoscopicUniversalCamera = (function (_super) {
  46722. __extends(StereoscopicUniversalCamera, _super);
  46723. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46724. _super.call(this, name, position, scene);
  46725. this.interaxialDistance = interaxialDistance;
  46726. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46727. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46728. }
  46729. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46730. return "StereoscopicUniversalCamera";
  46731. };
  46732. return StereoscopicUniversalCamera;
  46733. }(BABYLON.UniversalCamera));
  46734. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46735. })(BABYLON || (BABYLON = {}));
  46736. var BABYLON;
  46737. (function (BABYLON) {
  46738. var HDRRenderingPipeline = (function (_super) {
  46739. __extends(HDRRenderingPipeline, _super);
  46740. /**
  46741. * @constructor
  46742. * @param {string} name - The rendering pipeline name
  46743. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46744. * @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)
  46745. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46746. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46747. */
  46748. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46749. var _this = this;
  46750. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46751. _super.call(this, scene.getEngine(), name);
  46752. /**
  46753. * Public members
  46754. */
  46755. // Gaussian Blur
  46756. /**
  46757. * Gaussian blur coefficient
  46758. * @type {number}
  46759. */
  46760. this.gaussCoeff = 0.3;
  46761. /**
  46762. * Gaussian blur mean
  46763. * @type {number}
  46764. */
  46765. this.gaussMean = 1.0;
  46766. /**
  46767. * Gaussian blur standard deviation
  46768. * @type {number}
  46769. */
  46770. this.gaussStandDev = 0.8;
  46771. /**
  46772. * Gaussian blur multiplier. Multiplies the blur effect
  46773. * @type {number}
  46774. */
  46775. this.gaussMultiplier = 4.0;
  46776. // HDR
  46777. /**
  46778. * Exposure, controls the overall intensity of the pipeline
  46779. * @type {number}
  46780. */
  46781. this.exposure = 1.0;
  46782. /**
  46783. * Minimum luminance that the post-process can output. Luminance is >= 0
  46784. * @type {number}
  46785. */
  46786. this.minimumLuminance = 1.0;
  46787. /**
  46788. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46789. * @type {number}
  46790. */
  46791. this.maximumLuminance = 1e20;
  46792. /**
  46793. * Increase rate for luminance: eye adaptation speed to dark
  46794. * @type {number}
  46795. */
  46796. this.luminanceIncreaserate = 0.5;
  46797. /**
  46798. * Decrease rate for luminance: eye adaptation speed to bright
  46799. * @type {number}
  46800. */
  46801. this.luminanceDecreaseRate = 0.5;
  46802. // Bright pass
  46803. /**
  46804. * Minimum luminance needed to compute HDR
  46805. * @type {number}
  46806. */
  46807. this.brightThreshold = 0.8;
  46808. this._needUpdate = true;
  46809. this._scene = scene;
  46810. // Bright pass
  46811. this._createBrightPassPostProcess(scene, ratio);
  46812. // Down sample X4
  46813. this._createDownSampleX4PostProcess(scene, ratio);
  46814. // Create gaussian blur post-processes
  46815. this._createGaussianBlurPostProcess(scene, ratio);
  46816. // Texture adder
  46817. this._createTextureAdderPostProcess(scene, ratio);
  46818. // Luminance generator
  46819. this._createLuminanceGeneratorPostProcess(scene);
  46820. // HDR
  46821. this._createHDRPostProcess(scene, ratio);
  46822. // Pass postprocess
  46823. if (originalPostProcess === null) {
  46824. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46825. }
  46826. else {
  46827. this._originalPostProcess = originalPostProcess;
  46828. }
  46829. // Configure pipeline
  46830. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46831. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46832. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46836. var addDownSamplerPostProcess = function (id) {
  46837. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46838. };
  46839. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46840. addDownSamplerPostProcess(i);
  46841. }
  46842. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46843. // Finish
  46844. scene.postProcessRenderPipelineManager.addPipeline(this);
  46845. if (cameras !== null) {
  46846. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46847. }
  46848. this.update();
  46849. }
  46850. /**
  46851. * Tells the pipeline to update its post-processes
  46852. */
  46853. HDRRenderingPipeline.prototype.update = function () {
  46854. this._needUpdate = true;
  46855. };
  46856. /**
  46857. * Returns the current calculated luminance
  46858. */
  46859. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46860. return this._hdrCurrentLuminance;
  46861. };
  46862. /**
  46863. * Returns the currently drawn luminance
  46864. */
  46865. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46866. return this._hdrOutputLuminance;
  46867. };
  46868. /**
  46869. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46870. */
  46871. HDRRenderingPipeline.prototype.dispose = function () {
  46872. this._originalPostProcess = undefined;
  46873. this._brightPassPostProcess = undefined;
  46874. this._downSampleX4PostProcess = undefined;
  46875. this._guassianBlurHPostProcess = undefined;
  46876. this._guassianBlurVPostProcess = undefined;
  46877. this._textureAdderPostProcess = undefined;
  46878. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46879. this._downSamplePostProcesses[i] = undefined;
  46880. }
  46881. this._hdrPostProcess = undefined;
  46882. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46883. };
  46884. /**
  46885. * Creates the HDR post-process and computes the luminance adaptation
  46886. */
  46887. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46888. var _this = this;
  46889. var hdrLastLuminance = 0.0;
  46890. this._hdrOutputLuminance = -1.0;
  46891. this._hdrCurrentLuminance = 1.0;
  46892. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46893. this._hdrPostProcess.onApply = function (effect) {
  46894. if (_this._hdrOutputLuminance < 0.0) {
  46895. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46896. }
  46897. else {
  46898. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46899. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46900. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46901. }
  46902. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46903. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46904. }
  46905. else {
  46906. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46907. }
  46908. }
  46909. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46910. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46911. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46912. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46913. effect.setFloat("exposure", _this.exposure);
  46914. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46915. _this._needUpdate = false;
  46916. };
  46917. };
  46918. /**
  46919. * Texture Adder post-process
  46920. */
  46921. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46922. var _this = this;
  46923. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46924. this._textureAdderPostProcess.onApply = function (effect) {
  46925. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46926. };
  46927. };
  46928. /**
  46929. * Down sample X4 post-process
  46930. */
  46931. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46932. var _this = this;
  46933. var downSampleX4Offsets = new Array(32);
  46934. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46935. this._downSampleX4PostProcess.onApply = function (effect) {
  46936. if (_this._needUpdate) {
  46937. var id = 0;
  46938. for (var i = -2; i < 2; i++) {
  46939. for (var j = -2; j < 2; j++) {
  46940. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46941. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46942. id += 2;
  46943. }
  46944. }
  46945. }
  46946. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46947. };
  46948. };
  46949. /**
  46950. * Bright pass post-process
  46951. */
  46952. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46953. var _this = this;
  46954. var brightOffsets = new Array(8);
  46955. var brightPassCallback = function (effect) {
  46956. if (_this._needUpdate) {
  46957. var sU = (1.0 / _this._brightPassPostProcess.width);
  46958. var sV = (1.0 / _this._brightPassPostProcess.height);
  46959. brightOffsets[0] = -0.5 * sU;
  46960. brightOffsets[1] = 0.5 * sV;
  46961. brightOffsets[2] = 0.5 * sU;
  46962. brightOffsets[3] = 0.5 * sV;
  46963. brightOffsets[4] = -0.5 * sU;
  46964. brightOffsets[5] = -0.5 * sV;
  46965. brightOffsets[6] = 0.5 * sU;
  46966. brightOffsets[7] = -0.5 * sV;
  46967. }
  46968. effect.setArray2("dsOffsets", brightOffsets);
  46969. effect.setFloat("brightThreshold", _this.brightThreshold);
  46970. };
  46971. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46972. this._brightPassPostProcess.onApply = brightPassCallback;
  46973. };
  46974. /**
  46975. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46976. */
  46977. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46978. var _this = this;
  46979. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46980. var luminanceOffsets = new Array(8);
  46981. var downSampleOffsets = new Array(18);
  46982. var halfDestPixelSize;
  46983. this._downSamplePostProcesses = new Array(lumSteps);
  46984. // Utils for luminance
  46985. var luminanceUpdateSourceOffsets = function (width, height) {
  46986. var sU = (1.0 / width);
  46987. var sV = (1.0 / height);
  46988. luminanceOffsets[0] = -0.5 * sU;
  46989. luminanceOffsets[1] = 0.5 * sV;
  46990. luminanceOffsets[2] = 0.5 * sU;
  46991. luminanceOffsets[3] = 0.5 * sV;
  46992. luminanceOffsets[4] = -0.5 * sU;
  46993. luminanceOffsets[5] = -0.5 * sV;
  46994. luminanceOffsets[6] = 0.5 * sU;
  46995. luminanceOffsets[7] = -0.5 * sV;
  46996. };
  46997. var luminanceUpdateDestOffsets = function (width, height) {
  46998. var id = 0;
  46999. for (var x = -1; x < 2; x++) {
  47000. for (var y = -1; y < 2; y++) {
  47001. downSampleOffsets[id] = (x) / width;
  47002. downSampleOffsets[id + 1] = (y) / height;
  47003. id += 2;
  47004. }
  47005. }
  47006. };
  47007. // Luminance callback
  47008. var luminanceCallback = function (effect) {
  47009. if (_this._needUpdate) {
  47010. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47011. }
  47012. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47013. effect.setArray2("lumOffsets", luminanceOffsets);
  47014. };
  47015. // Down sample callbacks
  47016. var downSampleCallback = function (indice) {
  47017. var i = indice;
  47018. return function (effect) {
  47019. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47020. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47021. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47022. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47023. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47024. effect.setArray2("dsOffsets", downSampleOffsets);
  47025. };
  47026. };
  47027. var downSampleAfterRenderCallback = function (effect) {
  47028. // Unpack result
  47029. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47030. 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);
  47031. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47032. };
  47033. // Create luminance post-process
  47034. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47035. 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);
  47036. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47037. // Create down sample post-processes
  47038. for (var i = lumSteps - 2; i >= 0; i--) {
  47039. var length = Math.pow(3, i);
  47040. ratio = { width: length, height: length };
  47041. var defines = "#define DOWN_SAMPLE\n";
  47042. if (i === 0) {
  47043. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47044. }
  47045. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47046. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47047. if (i === 0) {
  47048. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47049. }
  47050. }
  47051. };
  47052. /**
  47053. * Gaussian blur post-processes. Horizontal and Vertical
  47054. */
  47055. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47056. var _this = this;
  47057. var blurOffsetsW = new Array(9);
  47058. var blurOffsetsH = new Array(9);
  47059. var blurWeights = new Array(9);
  47060. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47061. // Utils for gaussian blur
  47062. var calculateBlurOffsets = function (height) {
  47063. var lastOutputDimensions = {
  47064. width: scene.getEngine().getRenderWidth(),
  47065. height: scene.getEngine().getRenderHeight()
  47066. };
  47067. for (var i = 0; i < 9; i++) {
  47068. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47069. if (height) {
  47070. blurOffsetsH[i] = value;
  47071. }
  47072. else {
  47073. blurOffsetsW[i] = value;
  47074. }
  47075. }
  47076. };
  47077. var calculateWeights = function () {
  47078. var x = 0.0;
  47079. for (var i = 0; i < 9; i++) {
  47080. x = (i - 4.0) / 4.0;
  47081. 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));
  47082. }
  47083. };
  47084. // Callback
  47085. var gaussianBlurCallback = function (height) {
  47086. return function (effect) {
  47087. if (_this._needUpdate) {
  47088. calculateWeights();
  47089. calculateBlurOffsets(height);
  47090. }
  47091. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47092. effect.setArray("blurWeights", blurWeights);
  47093. effect.setFloat("multiplier", _this.gaussMultiplier);
  47094. };
  47095. };
  47096. // Create horizontal gaussian blur post-processes
  47097. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47098. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47099. // Create vertical gaussian blur post-process
  47100. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47101. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47102. };
  47103. // Luminance generator
  47104. HDRRenderingPipeline.LUM_STEPS = 6;
  47105. return HDRRenderingPipeline;
  47106. }(BABYLON.PostProcessRenderPipeline));
  47107. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47108. })(BABYLON || (BABYLON = {}));
  47109. var BABYLON;
  47110. (function (BABYLON) {
  47111. var FaceAdjacencies = (function () {
  47112. function FaceAdjacencies() {
  47113. this.edges = new Array();
  47114. this.edgesConnectedCount = 0;
  47115. }
  47116. return FaceAdjacencies;
  47117. }());
  47118. var EdgesRenderer = (function () {
  47119. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  47120. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  47121. if (epsilon === void 0) { epsilon = 0.95; }
  47122. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  47123. this.edgesWidthScalerForOrthographic = 1000.0;
  47124. this.edgesWidthScalerForPerspective = 50.0;
  47125. this._linesPositions = new Array();
  47126. this._linesNormals = new Array();
  47127. this._linesIndices = new Array();
  47128. this._buffers = {};
  47129. this._checkVerticesInsteadOfIndices = false;
  47130. this._source = source;
  47131. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  47132. this._epsilon = epsilon;
  47133. this._prepareRessources();
  47134. this._generateEdgesLines();
  47135. }
  47136. EdgesRenderer.prototype._prepareRessources = function () {
  47137. if (this._lineShader) {
  47138. return;
  47139. }
  47140. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  47141. attributes: ["position", "normal"],
  47142. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  47143. });
  47144. this._lineShader.disableDepthWrite = true;
  47145. this._lineShader.backFaceCulling = false;
  47146. };
  47147. EdgesRenderer.prototype.dispose = function () {
  47148. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  47149. if (buffer) {
  47150. buffer.dispose();
  47151. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  47152. }
  47153. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  47154. if (buffer) {
  47155. buffer.dispose();
  47156. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  47157. }
  47158. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  47159. this._lineShader.dispose();
  47160. };
  47161. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  47162. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  47163. return 0;
  47164. }
  47165. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  47166. return 1;
  47167. }
  47168. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  47169. return 2;
  47170. }
  47171. return -1;
  47172. };
  47173. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  47174. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  47175. return 0;
  47176. }
  47177. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  47178. return 1;
  47179. }
  47180. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  47181. return 2;
  47182. }
  47183. return -1;
  47184. };
  47185. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  47186. var needToCreateLine;
  47187. if (edge === undefined) {
  47188. needToCreateLine = true;
  47189. }
  47190. else {
  47191. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  47192. needToCreateLine = dotProduct < this._epsilon;
  47193. }
  47194. if (needToCreateLine) {
  47195. var offset = this._linesPositions.length / 3;
  47196. var normal = p0.subtract(p1);
  47197. normal.normalize();
  47198. // Positions
  47199. this._linesPositions.push(p0.x);
  47200. this._linesPositions.push(p0.y);
  47201. this._linesPositions.push(p0.z);
  47202. this._linesPositions.push(p0.x);
  47203. this._linesPositions.push(p0.y);
  47204. this._linesPositions.push(p0.z);
  47205. this._linesPositions.push(p1.x);
  47206. this._linesPositions.push(p1.y);
  47207. this._linesPositions.push(p1.z);
  47208. this._linesPositions.push(p1.x);
  47209. this._linesPositions.push(p1.y);
  47210. this._linesPositions.push(p1.z);
  47211. // Normals
  47212. this._linesNormals.push(p1.x);
  47213. this._linesNormals.push(p1.y);
  47214. this._linesNormals.push(p1.z);
  47215. this._linesNormals.push(-1);
  47216. this._linesNormals.push(p1.x);
  47217. this._linesNormals.push(p1.y);
  47218. this._linesNormals.push(p1.z);
  47219. this._linesNormals.push(1);
  47220. this._linesNormals.push(p0.x);
  47221. this._linesNormals.push(p0.y);
  47222. this._linesNormals.push(p0.z);
  47223. this._linesNormals.push(-1);
  47224. this._linesNormals.push(p0.x);
  47225. this._linesNormals.push(p0.y);
  47226. this._linesNormals.push(p0.z);
  47227. this._linesNormals.push(1);
  47228. // Indices
  47229. this._linesIndices.push(offset);
  47230. this._linesIndices.push(offset + 1);
  47231. this._linesIndices.push(offset + 2);
  47232. this._linesIndices.push(offset);
  47233. this._linesIndices.push(offset + 2);
  47234. this._linesIndices.push(offset + 3);
  47235. }
  47236. };
  47237. EdgesRenderer.prototype._generateEdgesLines = function () {
  47238. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47239. var indices = this._source.getIndices();
  47240. // First let's find adjacencies
  47241. var adjacencies = new Array();
  47242. var faceNormals = new Array();
  47243. var index;
  47244. var faceAdjacencies;
  47245. // Prepare faces
  47246. for (index = 0; index < indices.length; index += 3) {
  47247. faceAdjacencies = new FaceAdjacencies();
  47248. var p0Index = indices[index];
  47249. var p1Index = indices[index + 1];
  47250. var p2Index = indices[index + 2];
  47251. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  47252. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  47253. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  47254. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  47255. faceNormal.normalize();
  47256. faceNormals.push(faceNormal);
  47257. adjacencies.push(faceAdjacencies);
  47258. }
  47259. // Scan
  47260. for (index = 0; index < adjacencies.length; index++) {
  47261. faceAdjacencies = adjacencies[index];
  47262. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  47263. var otherFaceAdjacencies = adjacencies[otherIndex];
  47264. if (faceAdjacencies.edgesConnectedCount === 3) {
  47265. break;
  47266. }
  47267. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  47268. continue;
  47269. }
  47270. var otherP0 = indices[otherIndex * 3];
  47271. var otherP1 = indices[otherIndex * 3 + 1];
  47272. var otherP2 = indices[otherIndex * 3 + 2];
  47273. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  47274. var otherEdgeIndex;
  47275. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  47276. continue;
  47277. }
  47278. switch (edgeIndex) {
  47279. case 0:
  47280. if (this._checkVerticesInsteadOfIndices) {
  47281. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47282. }
  47283. else {
  47284. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  47285. }
  47286. break;
  47287. case 1:
  47288. if (this._checkVerticesInsteadOfIndices) {
  47289. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47290. }
  47291. else {
  47292. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  47293. }
  47294. break;
  47295. case 2:
  47296. if (this._checkVerticesInsteadOfIndices) {
  47297. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47298. }
  47299. else {
  47300. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  47301. }
  47302. break;
  47303. }
  47304. if (otherEdgeIndex === -1) {
  47305. continue;
  47306. }
  47307. faceAdjacencies.edges[edgeIndex] = otherIndex;
  47308. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  47309. faceAdjacencies.edgesConnectedCount++;
  47310. otherFaceAdjacencies.edgesConnectedCount++;
  47311. if (faceAdjacencies.edgesConnectedCount === 3) {
  47312. break;
  47313. }
  47314. }
  47315. }
  47316. }
  47317. // Create lines
  47318. for (index = 0; index < adjacencies.length; index++) {
  47319. // 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
  47320. var current = adjacencies[index];
  47321. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  47322. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  47323. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  47324. }
  47325. // Merge into a single mesh
  47326. var engine = this._source.getScene().getEngine();
  47327. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  47328. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  47329. this._ib = engine.createIndexBuffer(this._linesIndices);
  47330. this._indicesCount = this._linesIndices.length;
  47331. };
  47332. EdgesRenderer.prototype.render = function () {
  47333. if (!this._lineShader.isReady()) {
  47334. return;
  47335. }
  47336. var scene = this._source.getScene();
  47337. var engine = scene.getEngine();
  47338. this._lineShader._preBind();
  47339. // VBOs
  47340. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  47341. scene.resetCachedMaterial();
  47342. this._lineShader.setColor4("color", this._source.edgesColor);
  47343. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  47344. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  47345. }
  47346. else {
  47347. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  47348. }
  47349. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  47350. this._lineShader.bind(this._source.getWorldMatrix());
  47351. // Draw order
  47352. engine.draw(true, 0, this._indicesCount);
  47353. this._lineShader.unbind();
  47354. engine.setDepthWrite(true);
  47355. };
  47356. return EdgesRenderer;
  47357. }());
  47358. BABYLON.EdgesRenderer = EdgesRenderer;
  47359. })(BABYLON || (BABYLON = {}));
  47360. var BABYLON;
  47361. (function (BABYLON) {
  47362. (function (TonemappingOperator) {
  47363. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47364. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47365. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47366. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47367. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47368. var TonemappingOperator = BABYLON.TonemappingOperator;
  47369. ;
  47370. var TonemapPostProcess = (function (_super) {
  47371. __extends(TonemapPostProcess, _super);
  47372. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47373. var _this = this;
  47374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47375. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47376. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  47377. this._operator = _operator;
  47378. this.exposureAdjustment = exposureAdjustment;
  47379. var defines = "#define ";
  47380. if (this._operator === TonemappingOperator.Hable)
  47381. defines += "HABLE_TONEMAPPING";
  47382. else if (this._operator === TonemappingOperator.Reinhard)
  47383. defines += "REINHARD_TONEMAPPING";
  47384. else if (this._operator === TonemappingOperator.HejiDawson)
  47385. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47386. else if (this._operator === TonemappingOperator.Photographic)
  47387. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47388. //sadly a second call to create the effect.
  47389. this.updateEffect(defines);
  47390. this.onApply = function (effect) {
  47391. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47392. };
  47393. }
  47394. return TonemapPostProcess;
  47395. }(BABYLON.PostProcess));
  47396. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47397. })(BABYLON || (BABYLON = {}));
  47398. var BABYLON;
  47399. (function (BABYLON) {
  47400. var ReflectionProbe = (function () {
  47401. function ReflectionProbe(name, size, scene, generateMipMaps) {
  47402. var _this = this;
  47403. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47404. this.name = name;
  47405. this._viewMatrix = BABYLON.Matrix.Identity();
  47406. this._target = BABYLON.Vector3.Zero();
  47407. this._add = BABYLON.Vector3.Zero();
  47408. this.invertYAxis = false;
  47409. this.position = BABYLON.Vector3.Zero();
  47410. this._scene = scene;
  47411. this._scene.reflectionProbes.push(this);
  47412. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  47413. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  47414. switch (faceIndex) {
  47415. case 0:
  47416. _this._add.copyFromFloats(1, 0, 0);
  47417. break;
  47418. case 1:
  47419. _this._add.copyFromFloats(-1, 0, 0);
  47420. break;
  47421. case 2:
  47422. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  47423. break;
  47424. case 3:
  47425. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  47426. break;
  47427. case 4:
  47428. _this._add.copyFromFloats(0, 0, 1);
  47429. break;
  47430. case 5:
  47431. _this._add.copyFromFloats(0, 0, -1);
  47432. break;
  47433. }
  47434. if (_this._attachedMesh) {
  47435. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  47436. }
  47437. _this.position.addToRef(_this._add, _this._target);
  47438. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  47439. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  47440. });
  47441. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  47442. scene.updateTransformMatrix(true);
  47443. });
  47444. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  47445. }
  47446. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  47447. get: function () {
  47448. return this._renderTargetTexture.refreshRate;
  47449. },
  47450. set: function (value) {
  47451. this._renderTargetTexture.refreshRate = value;
  47452. },
  47453. enumerable: true,
  47454. configurable: true
  47455. });
  47456. ReflectionProbe.prototype.getScene = function () {
  47457. return this._scene;
  47458. };
  47459. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  47460. get: function () {
  47461. return this._renderTargetTexture;
  47462. },
  47463. enumerable: true,
  47464. configurable: true
  47465. });
  47466. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  47467. get: function () {
  47468. return this._renderTargetTexture.renderList;
  47469. },
  47470. enumerable: true,
  47471. configurable: true
  47472. });
  47473. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  47474. this._attachedMesh = mesh;
  47475. };
  47476. ReflectionProbe.prototype.dispose = function () {
  47477. var index = this._scene.reflectionProbes.indexOf(this);
  47478. if (index !== -1) {
  47479. // Remove from the scene if found
  47480. this._scene.reflectionProbes.splice(index, 1);
  47481. }
  47482. if (this._renderTargetTexture) {
  47483. this._renderTargetTexture.dispose();
  47484. this._renderTargetTexture = null;
  47485. }
  47486. };
  47487. return ReflectionProbe;
  47488. }());
  47489. BABYLON.ReflectionProbe = ReflectionProbe;
  47490. })(BABYLON || (BABYLON = {}));
  47491. var BABYLON;
  47492. (function (BABYLON) {
  47493. var SolidParticle = (function () {
  47494. /**
  47495. * Creates a Solid Particle object.
  47496. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  47497. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  47498. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  47499. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  47500. * `shapeId` (integer) is the model shape identifier in the SPS.
  47501. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  47502. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  47503. */
  47504. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  47505. this.idx = 0; // particle global index
  47506. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  47507. this.position = BABYLON.Vector3.Zero(); // position
  47508. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47509. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  47510. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  47511. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47512. this.alive = true; // alive
  47513. this.isVisible = true; // visibility
  47514. this._pos = 0; // index of this particle in the global "positions" array
  47515. this.shapeId = 0; // model shape id
  47516. this.idxInShape = 0; // index of the particle in its shape id
  47517. this.idx = particleIndex;
  47518. this._pos = positionIndex;
  47519. this._model = model;
  47520. this.shapeId = shapeId;
  47521. this.idxInShape = idxInShape;
  47522. this._sps = sps;
  47523. if (modelBoundingInfo) {
  47524. this._modelBoundingInfo = modelBoundingInfo;
  47525. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  47526. }
  47527. }
  47528. Object.defineProperty(SolidParticle.prototype, "scale", {
  47529. /**
  47530. * legacy support, changed scale to scaling
  47531. */
  47532. get: function () {
  47533. return this.scaling;
  47534. },
  47535. set: function (scale) {
  47536. this.scaling = scale;
  47537. },
  47538. enumerable: true,
  47539. configurable: true
  47540. });
  47541. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47542. /**
  47543. * legacy support, changed quaternion to rotationQuaternion
  47544. */
  47545. get: function () {
  47546. return this.rotationQuaternion;
  47547. },
  47548. set: function (q) {
  47549. this.rotationQuaternion = q;
  47550. },
  47551. enumerable: true,
  47552. configurable: true
  47553. });
  47554. /**
  47555. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  47556. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  47557. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  47558. */
  47559. SolidParticle.prototype.intersectsMesh = function (target) {
  47560. if (!this._boundingInfo || !target._boundingInfo) {
  47561. return false;
  47562. }
  47563. if (this._sps._bSphereOnly) {
  47564. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47565. }
  47566. return this._boundingInfo.intersects(target._boundingInfo, false);
  47567. };
  47568. return SolidParticle;
  47569. }());
  47570. BABYLON.SolidParticle = SolidParticle;
  47571. var ModelShape = (function () {
  47572. /**
  47573. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  47574. * SPS internal tool, don't use it manually.
  47575. */
  47576. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  47577. this.shapeID = id;
  47578. this._shape = shape;
  47579. this._shapeUV = shapeUV;
  47580. this._positionFunction = posFunction;
  47581. this._vertexFunction = vtxFunction;
  47582. }
  47583. return ModelShape;
  47584. }());
  47585. BABYLON.ModelShape = ModelShape;
  47586. })(BABYLON || (BABYLON = {}));
  47587. var BABYLON;
  47588. (function (BABYLON) {
  47589. /**
  47590. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47591. */
  47592. var SolidParticleSystem = (function () {
  47593. /**
  47594. * Creates a SPS (Solid Particle System) object.
  47595. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47596. * `scene` (Scene) is the scene in which the SPS is added.
  47597. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47598. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47599. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47600. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47601. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47602. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47603. */
  47604. function SolidParticleSystem(name, scene, options) {
  47605. // public members
  47606. /**
  47607. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47608. * Example : var p = SPS.particles[i];
  47609. */
  47610. this.particles = new Array();
  47611. /**
  47612. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47613. */
  47614. this.nbParticles = 0;
  47615. /**
  47616. * If the particles must ever face the camera (default false). Useful for planar particles.
  47617. */
  47618. this.billboard = false;
  47619. /**
  47620. * Recompute normals when adding a shape
  47621. */
  47622. this.recomputeNormals = true;
  47623. /**
  47624. * This a counter ofr your own usage. It's not set by any SPS functions.
  47625. */
  47626. this.counter = 0;
  47627. /**
  47628. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47629. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47630. */
  47631. this.vars = {};
  47632. this._positions = new Array();
  47633. this._indices = new Array();
  47634. this._normals = new Array();
  47635. this._colors = new Array();
  47636. this._uvs = new Array();
  47637. this._index = 0; // indices index
  47638. this._updatable = true;
  47639. this._pickable = false;
  47640. this._isVisibilityBoxLocked = false;
  47641. this._alwaysVisible = false;
  47642. this._shapeCounter = 0;
  47643. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  47644. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47645. this._computeParticleColor = true;
  47646. this._computeParticleTexture = true;
  47647. this._computeParticleRotation = true;
  47648. this._computeParticleVertex = false;
  47649. this._computeBoundingBox = false;
  47650. this._cam_axisZ = BABYLON.Vector3.Zero();
  47651. this._cam_axisY = BABYLON.Vector3.Zero();
  47652. this._cam_axisX = BABYLON.Vector3.Zero();
  47653. this._axisX = BABYLON.Axis.X;
  47654. this._axisY = BABYLON.Axis.Y;
  47655. this._axisZ = BABYLON.Axis.Z;
  47656. this._camDir = BABYLON.Vector3.Zero();
  47657. this._rotMatrix = new BABYLON.Matrix();
  47658. this._invertMatrix = new BABYLON.Matrix();
  47659. this._rotated = BABYLON.Vector3.Zero();
  47660. this._quaternion = new BABYLON.Quaternion();
  47661. this._vertex = BABYLON.Vector3.Zero();
  47662. this._normal = BABYLON.Vector3.Zero();
  47663. this._yaw = 0.0;
  47664. this._pitch = 0.0;
  47665. this._roll = 0.0;
  47666. this._halfroll = 0.0;
  47667. this._halfpitch = 0.0;
  47668. this._halfyaw = 0.0;
  47669. this._sinRoll = 0.0;
  47670. this._cosRoll = 0.0;
  47671. this._sinPitch = 0.0;
  47672. this._cosPitch = 0.0;
  47673. this._sinYaw = 0.0;
  47674. this._cosYaw = 0.0;
  47675. this._w = 0.0;
  47676. this._minimum = BABYLON.Tmp.Vector3[0];
  47677. this._maximum = BABYLON.Tmp.Vector3[1];
  47678. this._scale = BABYLON.Tmp.Vector3[2];
  47679. this._translation = BABYLON.Tmp.Vector3[3];
  47680. this._minBbox = BABYLON.Tmp.Vector3[4];
  47681. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47682. this._particlesIntersect = false;
  47683. this._bSphereOnly = false;
  47684. this._bSphereRadiusFactor = 1.0;
  47685. this.name = name;
  47686. this._scene = scene;
  47687. this._camera = scene.activeCamera;
  47688. this._pickable = options ? options.isPickable : false;
  47689. this._particlesIntersect = options ? options.particleIntersection : false;
  47690. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47691. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47692. if (options && options.updatable) {
  47693. this._updatable = options.updatable;
  47694. }
  47695. else {
  47696. this._updatable = true;
  47697. }
  47698. if (this._pickable) {
  47699. this.pickedParticles = [];
  47700. }
  47701. }
  47702. /**
  47703. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47704. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47705. */
  47706. SolidParticleSystem.prototype.buildMesh = function () {
  47707. if (this.nbParticles === 0) {
  47708. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47709. this.addShape(triangle, 1);
  47710. triangle.dispose();
  47711. }
  47712. this._positions32 = new Float32Array(this._positions);
  47713. this._uvs32 = new Float32Array(this._uvs);
  47714. this._colors32 = new Float32Array(this._colors);
  47715. if (this.recomputeNormals) {
  47716. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  47717. }
  47718. this._normals32 = new Float32Array(this._normals);
  47719. this._fixedNormal32 = new Float32Array(this._normals);
  47720. var vertexData = new BABYLON.VertexData();
  47721. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47722. vertexData.indices = this._indices;
  47723. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47724. if (this._uvs32) {
  47725. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47726. ;
  47727. }
  47728. if (this._colors32) {
  47729. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47730. }
  47731. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47732. vertexData.applyToMesh(mesh, this._updatable);
  47733. this.mesh = mesh;
  47734. this.mesh.isPickable = this._pickable;
  47735. // free memory
  47736. this._positions = null;
  47737. this._normals = null;
  47738. this._uvs = null;
  47739. this._colors = null;
  47740. if (!this._updatable) {
  47741. this.particles.length = 0;
  47742. }
  47743. return mesh;
  47744. };
  47745. /**
  47746. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47747. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47748. * Thus the particles generated from `digest()` have their property `position` set yet.
  47749. * `mesh` ( Mesh ) is the mesh to be digested
  47750. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47751. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47752. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47753. */
  47754. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47755. var size = (options && options.facetNb) || 1;
  47756. var number = (options && options.number);
  47757. var delta = (options && options.delta) || 0;
  47758. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47759. var meshInd = mesh.getIndices();
  47760. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47761. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47762. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47763. var f = 0; // facet counter
  47764. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47765. // compute size from number
  47766. if (number) {
  47767. number = (number > totalFacets) ? totalFacets : number;
  47768. size = Math.round(totalFacets / number);
  47769. delta = 0;
  47770. }
  47771. else {
  47772. size = (size > totalFacets) ? totalFacets : size;
  47773. }
  47774. var facetPos = []; // submesh positions
  47775. var facetInd = []; // submesh indices
  47776. var facetUV = []; // submesh UV
  47777. var facetCol = []; // submesh colors
  47778. var barycenter = BABYLON.Tmp.Vector3[0];
  47779. var rand;
  47780. var sizeO = size;
  47781. while (f < totalFacets) {
  47782. size = sizeO + Math.floor((1 + delta) * Math.random());
  47783. if (f > totalFacets - size) {
  47784. size = totalFacets - f;
  47785. }
  47786. // reset temp arrays
  47787. facetPos.length = 0;
  47788. facetInd.length = 0;
  47789. facetUV.length = 0;
  47790. facetCol.length = 0;
  47791. // iterate over "size" facets
  47792. var fi = 0;
  47793. for (var j = f * 3; j < (f + size) * 3; j++) {
  47794. facetInd.push(fi);
  47795. var i = meshInd[j];
  47796. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47797. if (meshUV) {
  47798. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47799. }
  47800. if (meshCol) {
  47801. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47802. }
  47803. fi++;
  47804. }
  47805. // create a model shape for each single particle
  47806. var idx = this.nbParticles;
  47807. var shape = this._posToShape(facetPos);
  47808. var shapeUV = this._uvsToShapeUV(facetUV);
  47809. // compute the barycenter of the shape
  47810. var v;
  47811. for (v = 0; v < shape.length; v++) {
  47812. barycenter.addInPlace(shape[v]);
  47813. }
  47814. barycenter.scaleInPlace(1 / shape.length);
  47815. // shift the shape from its barycenter to the origin
  47816. for (v = 0; v < shape.length; v++) {
  47817. shape[v].subtractInPlace(barycenter);
  47818. }
  47819. var bInfo;
  47820. if (this._particlesIntersect) {
  47821. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47822. }
  47823. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  47824. // add the particle in the SPS
  47825. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47826. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  47827. // initialize the particle position
  47828. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47829. this._index += shape.length;
  47830. idx++;
  47831. this.nbParticles++;
  47832. this._shapeCounter++;
  47833. f += size;
  47834. }
  47835. return this;
  47836. };
  47837. //reset copy
  47838. SolidParticleSystem.prototype._resetCopy = function () {
  47839. this._copy.position.x = 0;
  47840. this._copy.position.y = 0;
  47841. this._copy.position.z = 0;
  47842. this._copy.rotation.x = 0;
  47843. this._copy.rotation.y = 0;
  47844. this._copy.rotation.z = 0;
  47845. this._copy.rotationQuaternion = null;
  47846. this._copy.scaling.x = 1;
  47847. this._copy.scaling.y = 1;
  47848. this._copy.scaling.z = 1;
  47849. this._copy.uvs.x = 0;
  47850. this._copy.uvs.y = 0;
  47851. this._copy.uvs.z = 1;
  47852. this._copy.uvs.w = 1;
  47853. this._copy.color = null;
  47854. };
  47855. // _meshBuilder : inserts the shape model in the global SPS mesh
  47856. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47857. var i;
  47858. var u = 0;
  47859. var c = 0;
  47860. var n = 0;
  47861. this._resetCopy();
  47862. if (options && options.positionFunction) {
  47863. options.positionFunction(this._copy, idx, idxInShape);
  47864. }
  47865. if (this._copy.rotationQuaternion) {
  47866. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47867. }
  47868. else {
  47869. this._yaw = this._copy.rotation.y;
  47870. this._pitch = this._copy.rotation.x;
  47871. this._roll = this._copy.rotation.z;
  47872. this._quaternionRotationYPR();
  47873. }
  47874. this._quaternionToRotationMatrix();
  47875. for (i = 0; i < shape.length; i++) {
  47876. this._vertex.x = shape[i].x;
  47877. this._vertex.y = shape[i].y;
  47878. this._vertex.z = shape[i].z;
  47879. if (options && options.vertexFunction) {
  47880. options.vertexFunction(this._copy, this._vertex, i);
  47881. }
  47882. this._vertex.x *= this._copy.scaling.x;
  47883. this._vertex.y *= this._copy.scaling.y;
  47884. this._vertex.z *= this._copy.scaling.z;
  47885. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47886. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47887. if (meshUV) {
  47888. 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);
  47889. u += 2;
  47890. }
  47891. if (this._copy.color) {
  47892. this._color = this._copy.color;
  47893. }
  47894. else if (meshCol && meshCol[c] !== undefined) {
  47895. this._color.r = meshCol[c];
  47896. this._color.g = meshCol[c + 1];
  47897. this._color.b = meshCol[c + 2];
  47898. this._color.a = meshCol[c + 3];
  47899. }
  47900. else {
  47901. this._color.r = 1;
  47902. this._color.g = 1;
  47903. this._color.b = 1;
  47904. this._color.a = 1;
  47905. }
  47906. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47907. c += 4;
  47908. if (!this.recomputeNormals && meshNor) {
  47909. this._normal.x = meshNor[n];
  47910. this._normal.y = meshNor[n + 1];
  47911. this._normal.z = meshNor[n + 2];
  47912. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  47913. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47914. n += 3;
  47915. }
  47916. }
  47917. for (i = 0; i < meshInd.length; i++) {
  47918. indices.push(p + meshInd[i]);
  47919. }
  47920. if (this._pickable) {
  47921. var nbfaces = meshInd.length / 3;
  47922. for (i = 0; i < nbfaces; i++) {
  47923. this.pickedParticles.push({ idx: idx, faceId: i });
  47924. }
  47925. }
  47926. };
  47927. // returns a shape array from positions array
  47928. SolidParticleSystem.prototype._posToShape = function (positions) {
  47929. var shape = [];
  47930. for (var i = 0; i < positions.length; i += 3) {
  47931. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47932. }
  47933. return shape;
  47934. };
  47935. // returns a shapeUV array from a Vector4 uvs
  47936. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47937. var shapeUV = [];
  47938. if (uvs) {
  47939. for (var i = 0; i < uvs.length; i++)
  47940. shapeUV.push(uvs[i]);
  47941. }
  47942. return shapeUV;
  47943. };
  47944. // adds a new particle object in the particles array
  47945. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  47946. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  47947. };
  47948. /**
  47949. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47950. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47951. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47952. * `nb` (positive integer) the number of particles to be created from this model
  47953. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47954. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47955. */
  47956. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47957. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47958. var meshInd = mesh.getIndices();
  47959. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47960. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47961. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47962. var bbInfo;
  47963. if (this._particlesIntersect) {
  47964. bbInfo = mesh.getBoundingInfo();
  47965. }
  47966. var shape = this._posToShape(meshPos);
  47967. var shapeUV = this._uvsToShapeUV(meshUV);
  47968. var posfunc = options ? options.positionFunction : null;
  47969. var vtxfunc = options ? options.vertexFunction : null;
  47970. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  47971. // particles
  47972. var idx = this.nbParticles;
  47973. for (var i = 0; i < nb; i++) {
  47974. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47975. if (this._updatable) {
  47976. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  47977. }
  47978. this._index += shape.length;
  47979. idx++;
  47980. }
  47981. this.nbParticles += nb;
  47982. this._shapeCounter++;
  47983. return this._shapeCounter - 1;
  47984. };
  47985. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47986. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47987. this._resetCopy();
  47988. if (particle._model._positionFunction) {
  47989. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47990. }
  47991. if (this._copy.rotationQuaternion) {
  47992. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47993. }
  47994. else {
  47995. this._yaw = this._copy.rotation.y;
  47996. this._pitch = this._copy.rotation.x;
  47997. this._roll = this._copy.rotation.z;
  47998. this._quaternionRotationYPR();
  47999. }
  48000. this._quaternionToRotationMatrix();
  48001. this._shape = particle._model._shape;
  48002. for (var pt = 0; pt < this._shape.length; pt++) {
  48003. this._vertex.x = this._shape[pt].x;
  48004. this._vertex.y = this._shape[pt].y;
  48005. this._vertex.z = this._shape[pt].z;
  48006. if (particle._model._vertexFunction) {
  48007. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  48008. }
  48009. this._vertex.x *= this._copy.scaling.x;
  48010. this._vertex.y *= this._copy.scaling.y;
  48011. this._vertex.z *= this._copy.scaling.z;
  48012. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48013. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  48014. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  48015. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  48016. }
  48017. particle.position.x = 0.0;
  48018. particle.position.y = 0.0;
  48019. particle.position.z = 0.0;
  48020. particle.rotation.x = 0.0;
  48021. particle.rotation.y = 0.0;
  48022. particle.rotation.z = 0.0;
  48023. particle.rotationQuaternion = null;
  48024. particle.scaling.x = 1.0;
  48025. particle.scaling.y = 1.0;
  48026. particle.scaling.z = 1.0;
  48027. };
  48028. /**
  48029. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  48030. */
  48031. SolidParticleSystem.prototype.rebuildMesh = function () {
  48032. for (var p = 0; p < this.particles.length; p++) {
  48033. this._rebuildParticle(this.particles[p]);
  48034. }
  48035. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48036. };
  48037. /**
  48038. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  48039. * This method calls `updateParticle()` for each particle of the SPS.
  48040. * For an animated SPS, it is usually called within the render loop.
  48041. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  48042. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  48043. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  48044. */
  48045. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  48046. if (start === void 0) { start = 0; }
  48047. if (end === void 0) { end = this.nbParticles - 1; }
  48048. if (update === void 0) { update = true; }
  48049. if (!this._updatable) {
  48050. return;
  48051. }
  48052. // custom beforeUpdate
  48053. this.beforeUpdateParticles(start, end, update);
  48054. this._cam_axisX.x = 1.0;
  48055. this._cam_axisX.y = 0.0;
  48056. this._cam_axisX.z = 0.0;
  48057. this._cam_axisY.x = 0.0;
  48058. this._cam_axisY.y = 1.0;
  48059. this._cam_axisY.z = 0.0;
  48060. this._cam_axisZ.x = 0.0;
  48061. this._cam_axisZ.y = 0.0;
  48062. this._cam_axisZ.z = 1.0;
  48063. // if the particles will always face the camera
  48064. if (this.billboard) {
  48065. // compute the camera position and un-rotate it by the current mesh rotation
  48066. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  48067. this._quaternionToRotationMatrix();
  48068. this._rotMatrix.invertToRef(this._invertMatrix);
  48069. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  48070. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  48071. this._cam_axisZ.normalize();
  48072. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  48073. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  48074. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  48075. this._cam_axisY.normalize();
  48076. this._cam_axisX.normalize();
  48077. }
  48078. }
  48079. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  48080. var idx = 0;
  48081. var index = 0;
  48082. var colidx = 0;
  48083. var colorIndex = 0;
  48084. var uvidx = 0;
  48085. var uvIndex = 0;
  48086. var pt = 0;
  48087. if (this._computeBoundingBox) {
  48088. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  48089. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  48090. }
  48091. // particle loop
  48092. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  48093. for (var p = start; p <= end; p++) {
  48094. this._particle = this.particles[p];
  48095. this._shape = this._particle._model._shape;
  48096. this._shapeUV = this._particle._model._shapeUV;
  48097. // call to custom user function to update the particle properties
  48098. this.updateParticle(this._particle);
  48099. if (this._particle.isVisible) {
  48100. // particle rotation matrix
  48101. if (this.billboard) {
  48102. this._particle.rotation.x = 0.0;
  48103. this._particle.rotation.y = 0.0;
  48104. }
  48105. if (this._computeParticleRotation || this.billboard) {
  48106. if (this._particle.rotationQuaternion) {
  48107. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48108. }
  48109. else {
  48110. this._yaw = this._particle.rotation.y;
  48111. this._pitch = this._particle.rotation.x;
  48112. this._roll = this._particle.rotation.z;
  48113. this._quaternionRotationYPR();
  48114. }
  48115. this._quaternionToRotationMatrix();
  48116. }
  48117. // particle vertex loop
  48118. for (pt = 0; pt < this._shape.length; pt++) {
  48119. idx = index + pt * 3;
  48120. colidx = colorIndex + pt * 4;
  48121. uvidx = uvIndex + pt * 2;
  48122. this._vertex.x = this._shape[pt].x;
  48123. this._vertex.y = this._shape[pt].y;
  48124. this._vertex.z = this._shape[pt].z;
  48125. if (this._computeParticleVertex) {
  48126. this.updateParticleVertex(this._particle, this._vertex, pt);
  48127. }
  48128. // positions
  48129. this._vertex.x *= this._particle.scaling.x;
  48130. this._vertex.y *= this._particle.scaling.y;
  48131. this._vertex.z *= this._particle.scaling.z;
  48132. 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];
  48133. 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;
  48134. 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;
  48135. 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;
  48136. 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;
  48137. 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;
  48138. 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;
  48139. if (this._computeBoundingBox) {
  48140. if (this._positions32[idx] < this._minimum.x) {
  48141. this._minimum.x = this._positions32[idx];
  48142. }
  48143. if (this._positions32[idx] > this._maximum.x) {
  48144. this._maximum.x = this._positions32[idx];
  48145. }
  48146. if (this._positions32[idx + 1] < this._minimum.y) {
  48147. this._minimum.y = this._positions32[idx + 1];
  48148. }
  48149. if (this._positions32[idx + 1] > this._maximum.y) {
  48150. this._maximum.y = this._positions32[idx + 1];
  48151. }
  48152. if (this._positions32[idx + 2] < this._minimum.z) {
  48153. this._minimum.z = this._positions32[idx + 2];
  48154. }
  48155. if (this._positions32[idx + 2] > this._maximum.z) {
  48156. this._maximum.z = this._positions32[idx + 2];
  48157. }
  48158. }
  48159. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  48160. if (!this._computeParticleVertex) {
  48161. this._normal.x = this._fixedNormal32[idx];
  48162. this._normal.y = this._fixedNormal32[idx + 1];
  48163. this._normal.z = this._fixedNormal32[idx + 2];
  48164. 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];
  48165. 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;
  48166. 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;
  48167. 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;
  48168. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  48169. 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;
  48170. 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;
  48171. }
  48172. if (this._computeParticleColor) {
  48173. this._colors32[colidx] = this._particle.color.r;
  48174. this._colors32[colidx + 1] = this._particle.color.g;
  48175. this._colors32[colidx + 2] = this._particle.color.b;
  48176. this._colors32[colidx + 3] = this._particle.color.a;
  48177. }
  48178. if (this._computeParticleTexture) {
  48179. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48180. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48181. }
  48182. }
  48183. }
  48184. else {
  48185. for (pt = 0; pt < this._shape.length; pt++) {
  48186. idx = index + pt * 3;
  48187. colidx = colorIndex + pt * 4;
  48188. uvidx = uvIndex + pt * 2;
  48189. this._positions32[idx] = this._camera.position.x;
  48190. this._positions32[idx + 1] = this._camera.position.y;
  48191. this._positions32[idx + 2] = this._camera.position.z;
  48192. this._normals32[idx] = 0.0;
  48193. this._normals32[idx + 1] = 0.0;
  48194. this._normals32[idx + 2] = 0.0;
  48195. if (this._computeParticleColor) {
  48196. this._colors32[colidx] = this._particle.color.r;
  48197. this._colors32[colidx + 1] = this._particle.color.g;
  48198. this._colors32[colidx + 2] = this._particle.color.b;
  48199. this._colors32[colidx + 3] = this._particle.color.a;
  48200. }
  48201. if (this._computeParticleTexture) {
  48202. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48203. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48204. }
  48205. }
  48206. }
  48207. // if the particle intersections must be computed : update the bbInfo
  48208. if (this._particlesIntersect) {
  48209. var bInfo = this._particle._boundingInfo;
  48210. var bBox = bInfo.boundingBox;
  48211. var bSphere = bInfo.boundingSphere;
  48212. if (!this._bSphereOnly) {
  48213. // place, scale and rotate the particle bbox within the SPS local system, then update it
  48214. for (var b = 0; b < bBox.vectors.length; b++) {
  48215. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  48216. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  48217. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  48218. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  48219. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  48220. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  48221. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  48222. 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;
  48223. 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;
  48224. 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;
  48225. }
  48226. bBox._update(this.mesh._worldMatrix);
  48227. }
  48228. // place and scale the particle bouding sphere in the SPS local system, then update it
  48229. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  48230. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  48231. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  48232. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  48233. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  48234. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  48235. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  48236. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  48237. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  48238. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  48239. bSphere._update(this.mesh._worldMatrix);
  48240. }
  48241. // increment indexes for the next particle
  48242. index = idx + 3;
  48243. colorIndex = colidx + 4;
  48244. uvIndex = uvidx + 2;
  48245. }
  48246. // if the VBO must be updated
  48247. if (update) {
  48248. if (this._computeParticleColor) {
  48249. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  48250. }
  48251. if (this._computeParticleTexture) {
  48252. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  48253. }
  48254. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48255. if (!this.mesh.areNormalsFrozen) {
  48256. if (this._computeParticleVertex) {
  48257. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  48258. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  48259. for (var i = 0; i < this._normals32.length; i++) {
  48260. this._fixedNormal32[i] = this._normals32[i];
  48261. }
  48262. }
  48263. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  48264. }
  48265. }
  48266. if (this._computeBoundingBox) {
  48267. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  48268. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  48269. }
  48270. this.afterUpdateParticles(start, end, update);
  48271. };
  48272. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  48273. this._halfroll = this._roll * 0.5;
  48274. this._halfpitch = this._pitch * 0.5;
  48275. this._halfyaw = this._yaw * 0.5;
  48276. this._sinRoll = Math.sin(this._halfroll);
  48277. this._cosRoll = Math.cos(this._halfroll);
  48278. this._sinPitch = Math.sin(this._halfpitch);
  48279. this._cosPitch = Math.cos(this._halfpitch);
  48280. this._sinYaw = Math.sin(this._halfyaw);
  48281. this._cosYaw = Math.cos(this._halfyaw);
  48282. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  48283. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  48284. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  48285. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  48286. };
  48287. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  48288. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  48289. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  48290. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  48291. this._rotMatrix.m[3] = 0;
  48292. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  48293. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  48294. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  48295. this._rotMatrix.m[7] = 0;
  48296. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  48297. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  48298. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  48299. this._rotMatrix.m[11] = 0;
  48300. this._rotMatrix.m[12] = 0;
  48301. this._rotMatrix.m[13] = 0;
  48302. this._rotMatrix.m[14] = 0;
  48303. this._rotMatrix.m[15] = 1.0;
  48304. };
  48305. /**
  48306. * Disposes the SPS
  48307. */
  48308. SolidParticleSystem.prototype.dispose = function () {
  48309. this.mesh.dispose();
  48310. this.vars = null;
  48311. // drop references to internal big arrays for the GC
  48312. this._positions = null;
  48313. this._indices = null;
  48314. this._normals = null;
  48315. this._uvs = null;
  48316. this._colors = null;
  48317. this._positions32 = null;
  48318. this._normals32 = null;
  48319. this._fixedNormal32 = null;
  48320. this._uvs32 = null;
  48321. this._colors32 = null;
  48322. this.pickedParticles = null;
  48323. };
  48324. /**
  48325. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48326. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48327. */
  48328. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48329. if (!this._isVisibilityBoxLocked) {
  48330. this.mesh.refreshBoundingInfo();
  48331. }
  48332. };
  48333. /**
  48334. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48335. * @param size the size (float) of the visibility box
  48336. * note : this doesn't lock the SPS mesh bounding box.
  48337. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48338. */
  48339. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48340. var vis = size / 2;
  48341. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48342. };
  48343. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48344. // getter and setter
  48345. get: function () {
  48346. return this._alwaysVisible;
  48347. },
  48348. /**
  48349. * Sets the SPS as always visible or not
  48350. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48351. */
  48352. set: function (val) {
  48353. this._alwaysVisible = val;
  48354. this.mesh.alwaysSelectAsActiveMesh = val;
  48355. },
  48356. enumerable: true,
  48357. configurable: true
  48358. });
  48359. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48360. get: function () {
  48361. return this._isVisibilityBoxLocked;
  48362. },
  48363. /**
  48364. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48365. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48366. */
  48367. set: function (val) {
  48368. this._isVisibilityBoxLocked = val;
  48369. this.mesh.getBoundingInfo().isLocked = val;
  48370. },
  48371. enumerable: true,
  48372. configurable: true
  48373. });
  48374. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48375. // getters
  48376. get: function () {
  48377. return this._computeParticleRotation;
  48378. },
  48379. // Optimizer setters
  48380. /**
  48381. * Tells to `setParticles()` to compute the particle rotations or not.
  48382. * Default value : true. The SPS is faster when it's set to false.
  48383. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48384. */
  48385. set: function (val) {
  48386. this._computeParticleRotation = val;
  48387. },
  48388. enumerable: true,
  48389. configurable: true
  48390. });
  48391. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48392. get: function () {
  48393. return this._computeParticleColor;
  48394. },
  48395. /**
  48396. * Tells to `setParticles()` to compute the particle colors or not.
  48397. * Default value : true. The SPS is faster when it's set to false.
  48398. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48399. */
  48400. set: function (val) {
  48401. this._computeParticleColor = val;
  48402. },
  48403. enumerable: true,
  48404. configurable: true
  48405. });
  48406. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48407. get: function () {
  48408. return this._computeParticleTexture;
  48409. },
  48410. /**
  48411. * Tells to `setParticles()` to compute the particle textures or not.
  48412. * Default value : true. The SPS is faster when it's set to false.
  48413. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48414. */
  48415. set: function (val) {
  48416. this._computeParticleTexture = val;
  48417. },
  48418. enumerable: true,
  48419. configurable: true
  48420. });
  48421. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48422. get: function () {
  48423. return this._computeParticleVertex;
  48424. },
  48425. /**
  48426. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48427. * Default value : false. The SPS is faster when it's set to false.
  48428. * Note : the particle custom vertex positions aren't stored values.
  48429. */
  48430. set: function (val) {
  48431. this._computeParticleVertex = val;
  48432. },
  48433. enumerable: true,
  48434. configurable: true
  48435. });
  48436. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48437. get: function () {
  48438. return this._computeBoundingBox;
  48439. },
  48440. /**
  48441. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48442. */
  48443. set: function (val) {
  48444. this._computeBoundingBox = val;
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. // =======================================================================
  48450. // Particle behavior logic
  48451. // these following methods may be overwritten by the user to fit his needs
  48452. /**
  48453. * This function does nothing. It may be overwritten to set all the particle first values.
  48454. * The SPS doesn't call this function, you may have to call it by your own.
  48455. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48456. */
  48457. SolidParticleSystem.prototype.initParticles = function () {
  48458. };
  48459. /**
  48460. * This function does nothing. It may be overwritten to recycle a particle.
  48461. * The SPS doesn't call this function, you may have to call it by your own.
  48462. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48463. */
  48464. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48465. return particle;
  48466. };
  48467. /**
  48468. * Updates a particle : this function should be overwritten by the user.
  48469. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48470. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48471. * ex : just set a particle position or velocity and recycle conditions
  48472. */
  48473. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48474. return particle;
  48475. };
  48476. /**
  48477. * Updates a vertex of a particle : it can be overwritten by the user.
  48478. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48479. * @param particle the current particle
  48480. * @param vertex the current index of the current particle
  48481. * @param pt the index of the current vertex in the particle shape
  48482. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48483. * ex : just set a vertex particle position
  48484. */
  48485. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48486. return vertex;
  48487. };
  48488. /**
  48489. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48490. * This does nothing and may be overwritten by the user.
  48491. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48492. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48493. * @param update the boolean update value actually passed to setParticles()
  48494. */
  48495. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48496. };
  48497. /**
  48498. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48499. * This will be passed three parameters.
  48500. * This does nothing and may be overwritten by the user.
  48501. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48502. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48503. * @param update the boolean update value actually passed to setParticles()
  48504. */
  48505. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48506. };
  48507. return SolidParticleSystem;
  48508. }());
  48509. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48510. })(BABYLON || (BABYLON = {}));
  48511. var BABYLON;
  48512. (function (BABYLON) {
  48513. var Internals;
  48514. (function (Internals) {
  48515. var FileFaceOrientation = (function () {
  48516. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48517. this.name = name;
  48518. this.worldAxisForNormal = worldAxisForNormal;
  48519. this.worldAxisForFileX = worldAxisForFileX;
  48520. this.worldAxisForFileY = worldAxisForFileY;
  48521. }
  48522. return FileFaceOrientation;
  48523. }());
  48524. ;
  48525. /**
  48526. * Helper class dealing with the extraction of spherical polynomial dataArray
  48527. * from a cube map.
  48528. */
  48529. var CubeMapToSphericalPolynomialTools = (function () {
  48530. function CubeMapToSphericalPolynomialTools() {
  48531. }
  48532. /**
  48533. * Converts a cubemap to the according Spherical Polynomial data.
  48534. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48535. *
  48536. * @param cubeInfo The Cube map to extract the information from.
  48537. * @return The Spherical Polynomial data.
  48538. */
  48539. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48540. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48541. var totalSolidAngle = 0.0;
  48542. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48543. var du = 2.0 / cubeInfo.size;
  48544. var dv = du;
  48545. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48546. var minUV = du * 0.5 - 1.0;
  48547. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48548. var fileFace = this.FileFaces[faceIndex];
  48549. var dataArray = cubeInfo[fileFace.name];
  48550. var v = minUV;
  48551. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48552. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48553. // Because SP is still linear, so summation is fine in that basis.
  48554. for (var y = 0; y < cubeInfo.size; y++) {
  48555. var u = minUV;
  48556. for (var x = 0; x < cubeInfo.size; x++) {
  48557. // World direction (not normalised)
  48558. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48559. worldDirection.normalize();
  48560. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48561. if (1) {
  48562. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  48563. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  48564. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  48565. var color = new BABYLON.Color3(r, g, b);
  48566. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48567. }
  48568. else {
  48569. if (faceIndex == 0) {
  48570. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48571. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48572. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48573. }
  48574. else if (faceIndex == 1) {
  48575. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48576. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48577. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48578. }
  48579. else if (faceIndex == 2) {
  48580. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48581. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48582. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48583. }
  48584. else if (faceIndex == 3) {
  48585. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48586. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48587. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48588. }
  48589. else if (faceIndex == 4) {
  48590. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48591. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48592. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48593. }
  48594. else if (faceIndex == 5) {
  48595. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48596. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48597. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48598. }
  48599. 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]);
  48600. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48601. }
  48602. totalSolidAngle += deltaSolidAngle;
  48603. u += du;
  48604. }
  48605. v += dv;
  48606. }
  48607. }
  48608. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  48609. var correction = correctSolidAngle / totalSolidAngle;
  48610. sphericalHarmonics.scale(correction);
  48611. // Additionally scale by pi -- audit needed
  48612. sphericalHarmonics.scale(1.0 / Math.PI);
  48613. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48614. };
  48615. CubeMapToSphericalPolynomialTools.FileFaces = [
  48616. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48617. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48618. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48619. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48620. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48621. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48622. ];
  48623. return CubeMapToSphericalPolynomialTools;
  48624. }());
  48625. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48626. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48627. })(BABYLON || (BABYLON = {}));
  48628. var BABYLON;
  48629. (function (BABYLON) {
  48630. var Internals;
  48631. (function (Internals) {
  48632. /**
  48633. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48634. */
  48635. var PanoramaToCubeMapTools = (function () {
  48636. function PanoramaToCubeMapTools() {
  48637. }
  48638. /**
  48639. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48640. *
  48641. * @param float32Array The source data.
  48642. * @param inputWidth The width of the input panorama.
  48643. * @param inputhHeight The height of the input panorama.
  48644. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48645. * @return The cubemap data
  48646. */
  48647. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48648. if (!float32Array) {
  48649. throw "ConvertPanoramaToCubemap: input cannot be null";
  48650. }
  48651. if (float32Array.length != inputWidth * inputHeight * 3) {
  48652. throw "ConvertPanoramaToCubemap: input size is wrong";
  48653. }
  48654. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48655. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48656. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48657. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48658. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48659. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48660. return {
  48661. front: textureFront,
  48662. back: textureBack,
  48663. left: textureLeft,
  48664. right: textureRight,
  48665. up: textureUp,
  48666. down: textureDown,
  48667. size: size
  48668. };
  48669. };
  48670. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48671. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48672. var textureArray = new Float32Array(buffer);
  48673. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48674. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48675. var dy = 1 / texSize;
  48676. var fy = 0;
  48677. for (var y = 0; y < texSize; y++) {
  48678. var xv1 = faceData[0];
  48679. var xv2 = faceData[2];
  48680. for (var x = 0; x < texSize; x++) {
  48681. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48682. v.normalize();
  48683. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48684. // 3 channels per pixels
  48685. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48686. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48687. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48688. xv1 = xv1.add(rotDX1);
  48689. xv2 = xv2.add(rotDX2);
  48690. }
  48691. fy += dy;
  48692. }
  48693. return textureArray;
  48694. };
  48695. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48696. var theta = Math.atan2(vDir.z, vDir.x);
  48697. var phi = Math.acos(vDir.y);
  48698. while (theta < -Math.PI)
  48699. theta += 2 * Math.PI;
  48700. while (theta > Math.PI)
  48701. theta -= 2 * Math.PI;
  48702. var dx = theta / Math.PI;
  48703. var dy = phi / Math.PI;
  48704. // recenter.
  48705. dx = dx * 0.5 + 0.5;
  48706. var px = Math.round(dx * inputWidth);
  48707. if (px < 0)
  48708. px = 0;
  48709. else if (px >= inputWidth)
  48710. px = inputWidth - 1;
  48711. var py = Math.round(dy * inputHeight);
  48712. if (py < 0)
  48713. py = 0;
  48714. else if (py >= inputHeight)
  48715. py = inputHeight - 1;
  48716. var inputY = (inputHeight - py - 1);
  48717. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48718. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48719. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48720. return {
  48721. r: r,
  48722. g: g,
  48723. b: b
  48724. };
  48725. };
  48726. PanoramaToCubeMapTools.FACE_FRONT = [
  48727. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48728. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48729. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48730. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48731. ];
  48732. PanoramaToCubeMapTools.FACE_BACK = [
  48733. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48734. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48735. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48736. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48737. ];
  48738. PanoramaToCubeMapTools.FACE_RIGHT = [
  48739. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48740. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48741. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48742. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48743. ];
  48744. PanoramaToCubeMapTools.FACE_LEFT = [
  48745. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48746. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48747. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48748. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48749. ];
  48750. PanoramaToCubeMapTools.FACE_DOWN = [
  48751. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48752. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48753. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48754. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48755. ];
  48756. PanoramaToCubeMapTools.FACE_UP = [
  48757. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48758. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48759. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48760. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48761. ];
  48762. return PanoramaToCubeMapTools;
  48763. }());
  48764. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48765. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48766. })(BABYLON || (BABYLON = {}));
  48767. var BABYLON;
  48768. (function (BABYLON) {
  48769. var Internals;
  48770. (function (Internals) {
  48771. ;
  48772. /**
  48773. * This groups tools to convert HDR texture to native colors array.
  48774. */
  48775. var HDRTools = (function () {
  48776. function HDRTools() {
  48777. }
  48778. HDRTools.Ldexp = function (mantissa, exponent) {
  48779. if (exponent > 1023) {
  48780. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48781. }
  48782. if (exponent < -1074) {
  48783. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48784. }
  48785. return mantissa * Math.pow(2, exponent);
  48786. };
  48787. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48788. if (exponent > 0) {
  48789. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48790. float32array[index + 0] = red * exponent;
  48791. float32array[index + 1] = green * exponent;
  48792. float32array[index + 2] = blue * exponent;
  48793. }
  48794. else {
  48795. float32array[index + 0] = 0;
  48796. float32array[index + 1] = 0;
  48797. float32array[index + 2] = 0;
  48798. }
  48799. };
  48800. HDRTools.readStringLine = function (uint8array, startIndex) {
  48801. var line = "";
  48802. var character = "";
  48803. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48804. character = String.fromCharCode(uint8array[i]);
  48805. if (character == "\n") {
  48806. break;
  48807. }
  48808. line += character;
  48809. }
  48810. return line;
  48811. };
  48812. /**
  48813. * Reads header information from an RGBE texture stored in a native array.
  48814. * More information on this format are available here:
  48815. * https://en.wikipedia.org/wiki/RGBE_image_format
  48816. *
  48817. * @param uint8array The binary file stored in native array.
  48818. * @return The header information.
  48819. */
  48820. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48821. var height = 0;
  48822. var width = 0;
  48823. var line = this.readStringLine(uint8array, 0);
  48824. if (line[0] != '#' || line[1] != '?') {
  48825. throw "Bad HDR Format.";
  48826. }
  48827. var endOfHeader = false;
  48828. var findFormat = false;
  48829. var lineIndex = 0;
  48830. do {
  48831. lineIndex += (line.length + 1);
  48832. line = this.readStringLine(uint8array, lineIndex);
  48833. if (line == "FORMAT=32-bit_rle_rgbe") {
  48834. findFormat = true;
  48835. }
  48836. else if (line.length == 0) {
  48837. endOfHeader = true;
  48838. }
  48839. } while (!endOfHeader);
  48840. if (!findFormat) {
  48841. throw "HDR Bad header format, unsupported FORMAT";
  48842. }
  48843. lineIndex += (line.length + 1);
  48844. line = this.readStringLine(uint8array, lineIndex);
  48845. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48846. var match = sizeRegexp.exec(line);
  48847. // TODO. Support +Y and -X if needed.
  48848. if (match.length < 3) {
  48849. throw "HDR Bad header format, no size";
  48850. }
  48851. width = parseInt(match[2]);
  48852. height = parseInt(match[1]);
  48853. if (width < 8 || width > 0x7fff) {
  48854. throw "HDR Bad header format, unsupported size";
  48855. }
  48856. lineIndex += (line.length + 1);
  48857. return {
  48858. height: height,
  48859. width: width,
  48860. dataPosition: lineIndex
  48861. };
  48862. };
  48863. /**
  48864. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48865. * This RGBE texture needs to store the information as a panorama.
  48866. *
  48867. * More information on this format are available here:
  48868. * https://en.wikipedia.org/wiki/RGBE_image_format
  48869. *
  48870. * @param buffer The binary file stored in an array buffer.
  48871. * @param size The expected size of the extracted cubemap.
  48872. * @return The Cube Map information.
  48873. */
  48874. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48875. var uint8array = new Uint8Array(buffer);
  48876. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48877. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48878. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48879. return cubeMapData;
  48880. };
  48881. /**
  48882. * Returns the pixels data extracted from an RGBE texture.
  48883. * This pixels will be stored left to right up to down in the R G B order in one array.
  48884. *
  48885. * More information on this format are available here:
  48886. * https://en.wikipedia.org/wiki/RGBE_image_format
  48887. *
  48888. * @param uint8array The binary file stored in an array buffer.
  48889. * @param hdrInfo The header information of the file.
  48890. * @return The pixels data in RGB right to left up to down order.
  48891. */
  48892. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48893. // Keep for multi format supports.
  48894. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48895. };
  48896. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48897. var num_scanlines = hdrInfo.height;
  48898. var scanline_width = hdrInfo.width;
  48899. var a, b, c, d, count;
  48900. var dataIndex = hdrInfo.dataPosition;
  48901. var index = 0, endIndex = 0, i = 0;
  48902. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48903. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48904. // 3 channels of 4 bytes per pixel in float.
  48905. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48906. var resultArray = new Float32Array(resultBuffer);
  48907. // read in each successive scanline
  48908. while (num_scanlines > 0) {
  48909. a = uint8array[dataIndex++];
  48910. b = uint8array[dataIndex++];
  48911. c = uint8array[dataIndex++];
  48912. d = uint8array[dataIndex++];
  48913. if (a != 2 || b != 2 || (c & 0x80)) {
  48914. // this file is not run length encoded
  48915. throw "HDR Bad header format, not RLE";
  48916. }
  48917. if (((c << 8) | d) != scanline_width) {
  48918. throw "HDR Bad header format, wrong scan line width";
  48919. }
  48920. index = 0;
  48921. // read each of the four channels for the scanline into the buffer
  48922. for (i = 0; i < 4; i++) {
  48923. endIndex = (i + 1) * scanline_width;
  48924. while (index < endIndex) {
  48925. a = uint8array[dataIndex++];
  48926. b = uint8array[dataIndex++];
  48927. if (a > 128) {
  48928. // a run of the same value
  48929. count = a - 128;
  48930. if ((count == 0) || (count > endIndex - index)) {
  48931. throw "HDR Bad Format, bad scanline data (run)";
  48932. }
  48933. while (count-- > 0) {
  48934. scanLineArray[index++] = b;
  48935. }
  48936. }
  48937. else {
  48938. // a non-run
  48939. count = a;
  48940. if ((count == 0) || (count > endIndex - index)) {
  48941. throw "HDR Bad Format, bad scanline data (non-run)";
  48942. }
  48943. scanLineArray[index++] = b;
  48944. if (--count > 0) {
  48945. for (var j = 0; j < count; j++) {
  48946. scanLineArray[index++] = uint8array[dataIndex++];
  48947. }
  48948. }
  48949. }
  48950. }
  48951. }
  48952. // now convert data from buffer into floats
  48953. for (i = 0; i < scanline_width; i++) {
  48954. a = scanLineArray[i];
  48955. b = scanLineArray[i + scanline_width];
  48956. c = scanLineArray[i + 2 * scanline_width];
  48957. d = scanLineArray[i + 3 * scanline_width];
  48958. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48959. }
  48960. num_scanlines--;
  48961. }
  48962. return resultArray;
  48963. };
  48964. return HDRTools;
  48965. }());
  48966. Internals.HDRTools = HDRTools;
  48967. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48968. })(BABYLON || (BABYLON = {}));
  48969. //_______________________________________________________________
  48970. // Extracted from CubeMapGen:
  48971. // https://code.google.com/archive/p/cubemapgen/
  48972. //
  48973. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48974. //_______________________________________________________________
  48975. var BABYLON;
  48976. (function (BABYLON) {
  48977. var Internals;
  48978. (function (Internals) {
  48979. /**
  48980. * The bounding box information used during the conversion process.
  48981. */
  48982. var CMGBoundinBox = (function () {
  48983. function CMGBoundinBox() {
  48984. this.min = new BABYLON.Vector3(0, 0, 0);
  48985. this.max = new BABYLON.Vector3(0, 0, 0);
  48986. this.clear();
  48987. }
  48988. CMGBoundinBox.prototype.clear = function () {
  48989. this.min.x = CMGBoundinBox.MAX;
  48990. this.min.y = CMGBoundinBox.MAX;
  48991. this.min.z = CMGBoundinBox.MAX;
  48992. this.max.x = CMGBoundinBox.MIN;
  48993. this.max.y = CMGBoundinBox.MIN;
  48994. this.max.z = CMGBoundinBox.MIN;
  48995. };
  48996. CMGBoundinBox.prototype.augment = function (x, y, z) {
  48997. this.min.x = Math.min(this.min.x, x);
  48998. this.min.y = Math.min(this.min.y, y);
  48999. this.min.z = Math.min(this.min.z, z);
  49000. this.max.x = Math.max(this.max.x, x);
  49001. this.max.y = Math.max(this.max.y, y);
  49002. this.max.z = Math.max(this.max.z, z);
  49003. };
  49004. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  49005. this.min.x = Math.max(this.min.x, x);
  49006. this.min.y = Math.max(this.min.y, y);
  49007. this.min.z = Math.max(this.min.z, z);
  49008. };
  49009. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  49010. this.max.x = Math.min(this.max.x, x);
  49011. this.max.y = Math.min(this.max.y, y);
  49012. this.max.z = Math.min(this.max.z, z);
  49013. };
  49014. CMGBoundinBox.prototype.empty = function () {
  49015. if ((this.min.x > this.max.y) ||
  49016. (this.min.y > this.max.y) ||
  49017. (this.min.z > this.max.y)) {
  49018. return true;
  49019. }
  49020. else {
  49021. return false;
  49022. }
  49023. };
  49024. CMGBoundinBox.MAX = Number.MAX_VALUE;
  49025. CMGBoundinBox.MIN = Number.MIN_VALUE;
  49026. return CMGBoundinBox;
  49027. }());
  49028. /**
  49029. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  49030. * required by the glossinees of a material.
  49031. *
  49032. * This only supports the cosine drop power as well as Warp fixup generation method.
  49033. *
  49034. * This is using the process from CubeMapGen described here:
  49035. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49036. */
  49037. var PMREMGenerator = (function () {
  49038. /**
  49039. * Constructor of the generator.
  49040. *
  49041. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  49042. * @param inputSize The size of the cubemap faces
  49043. * @param outputSize The size of the output cubemap faces
  49044. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  49045. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  49046. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  49047. * @param specularPower The max specular level of the desired cubemap
  49048. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  49049. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  49050. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  49051. */
  49052. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  49053. this.input = input;
  49054. this.inputSize = inputSize;
  49055. this.outputSize = outputSize;
  49056. this.maxNumMipLevels = maxNumMipLevels;
  49057. this.numChannels = numChannels;
  49058. this.isFloat = isFloat;
  49059. this.specularPower = specularPower;
  49060. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  49061. this.excludeBase = excludeBase;
  49062. this.fixup = fixup;
  49063. this._outputSurface = [];
  49064. this._numMipLevels = 0;
  49065. }
  49066. /**
  49067. * Launches the filter process and return the result.
  49068. *
  49069. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  49070. */
  49071. PMREMGenerator.prototype.filterCubeMap = function () {
  49072. // Init cubemap processor
  49073. this.init();
  49074. // Filters the cubemap
  49075. this.filterCubeMapMipChain();
  49076. // Returns the filtered mips.
  49077. return this._outputSurface;
  49078. };
  49079. PMREMGenerator.prototype.init = function () {
  49080. var i;
  49081. var j;
  49082. var mipLevelSize;
  49083. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  49084. if (this.maxNumMipLevels == 0) {
  49085. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  49086. }
  49087. //first miplevel size
  49088. mipLevelSize = this.outputSize;
  49089. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  49090. for (j = 0; j < this.maxNumMipLevels; j++) {
  49091. this._outputSurface.length++;
  49092. this._outputSurface[j] = [];
  49093. //Iterate over faces for output images
  49094. for (i = 0; i < 6; i++) {
  49095. this._outputSurface[j].length++;
  49096. // Initializes a new array for the output.
  49097. if (this.isFloat) {
  49098. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49099. }
  49100. else {
  49101. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49102. }
  49103. }
  49104. //next mip level is half size
  49105. mipLevelSize >>= 1;
  49106. this._numMipLevels++;
  49107. //terminate if mip chain becomes too small
  49108. if (mipLevelSize == 0) {
  49109. this.maxNumMipLevels = j;
  49110. return;
  49111. }
  49112. }
  49113. };
  49114. //--------------------------------------------------------------------------------------
  49115. //Cube map filtering and mip chain generation.
  49116. // the cube map filtereing is specified using a number of parameters:
  49117. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  49118. // indicates the region of the hemisphere to filter over for each tap.
  49119. //
  49120. // Note that the top mip level is also a filtered version of the original input images
  49121. // as well in order to create mip chains for diffuse environment illumination.
  49122. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  49123. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  49124. //
  49125. // Then the mip angle used to genreate the next level of the mip chain from the first level
  49126. // is a_InitialMipAngle
  49127. //
  49128. // The angle for the subsequent levels of the mip chain are specified by their parents
  49129. // filtering angle and a per-level scale and bias
  49130. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  49131. //
  49132. //--------------------------------------------------------------------------------------
  49133. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  49134. // First, take count of the lighting model to modify SpecularPower
  49135. // 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;
  49136. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  49137. //Cone angle start (for generating subsequent mip levels)
  49138. var currentSpecularPower = this.specularPower;
  49139. //Build filter lookup tables based on the source miplevel size
  49140. this.precomputeFilterLookupTables(this.inputSize);
  49141. // Note that we need to filter the first level before generating mipmap
  49142. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  49143. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  49144. // TODO : Write a function to copy and scale the base mipmap in output
  49145. // I am just lazy here and just put a high specular power value, and do some if.
  49146. if (this.excludeBase && (levelIndex == 0)) {
  49147. // 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).
  49148. currentSpecularPower = 100000.0;
  49149. }
  49150. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  49151. var srcCubeImage = this.input;
  49152. var dstCubeImage = this._outputSurface[levelIndex];
  49153. var dstSize = this.outputSize >> levelIndex;
  49154. // Compute required angle.
  49155. var angle = this.getBaseFilterAngle(currentSpecularPower);
  49156. // filter cube surfaces
  49157. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  49158. // fix seams
  49159. if (this.fixup) {
  49160. this.fixupCubeEdges(dstCubeImage, dstSize);
  49161. }
  49162. // Decrease the specular power to generate the mipmap chain
  49163. // TODO : Use another method for Exclude (see first comment at start of the function
  49164. if (this.excludeBase && (levelIndex == 0)) {
  49165. currentSpecularPower = this.specularPower;
  49166. }
  49167. currentSpecularPower *= this.cosinePowerDropPerMip;
  49168. }
  49169. };
  49170. //--------------------------------------------------------------------------------------
  49171. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  49172. // It allow to optimize the texel to access base on the specular power.
  49173. //--------------------------------------------------------------------------------------
  49174. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  49175. // We want to find the alpha such that:
  49176. // cos(alpha)^cosinePower = epsilon
  49177. // That's: acos(epsilon^(1/cosinePower))
  49178. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  49179. var angle = 180.0;
  49180. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  49181. angle *= 180.0 / Math.PI; // Convert to degree
  49182. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  49183. return angle;
  49184. };
  49185. //--------------------------------------------------------------------------------------
  49186. //Builds the following lookup tables prior to filtering:
  49187. // -normalizer cube map
  49188. // -tap weight lookup table
  49189. //
  49190. //--------------------------------------------------------------------------------------
  49191. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  49192. var srcTexelAngle;
  49193. var iCubeFace;
  49194. //clear pre-existing normalizer cube map
  49195. this._normCubeMap = [];
  49196. //Normalized vectors per cubeface and per-texel solid angle
  49197. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  49198. };
  49199. //--------------------------------------------------------------------------------------
  49200. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  49201. //
  49202. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  49203. //
  49204. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  49205. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  49206. // below
  49207. //--------------------------------------------------------------------------------------
  49208. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  49209. var iCubeFace;
  49210. var u;
  49211. var v;
  49212. //iterate over cube faces
  49213. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49214. //First three channels for norm cube, and last channel for solid angle
  49215. this._normCubeMap.push(new Float32Array(size * size * 4));
  49216. //fast texture walk, build normalizer cube map
  49217. var facesData = this.input[iCubeFace];
  49218. for (v = 0; v < size; v++) {
  49219. for (u = 0; u < size; u++) {
  49220. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  49221. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  49222. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  49223. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  49224. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  49225. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  49226. }
  49227. }
  49228. }
  49229. };
  49230. //--------------------------------------------------------------------------------------
  49231. // Convert cubemap face texel coordinates and face idx to 3D vector
  49232. // note the U and V coords are integer coords and range from 0 to size-1
  49233. // this routine can be used to generate a normalizer cube map
  49234. //--------------------------------------------------------------------------------------
  49235. // SL BEGIN
  49236. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  49237. var nvcU;
  49238. var nvcV;
  49239. var tempVec;
  49240. // Change from original AMD code
  49241. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49242. // + 0.5f is for texel center addressing
  49243. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  49244. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  49245. // warp fixup
  49246. if (fixup && size > 1) {
  49247. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  49248. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  49249. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  49250. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  49251. }
  49252. // Get current vector
  49253. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  49254. // U contribution
  49255. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49256. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  49257. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  49258. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  49259. // V contribution and Sum
  49260. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49261. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  49262. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  49263. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  49264. //add face axis
  49265. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  49266. PMREMGenerator._vectorTemp.x += faceAxis[0];
  49267. PMREMGenerator._vectorTemp.y += faceAxis[1];
  49268. PMREMGenerator._vectorTemp.z += faceAxis[2];
  49269. //normalize vector
  49270. PMREMGenerator._vectorTemp.normalize();
  49271. return PMREMGenerator._vectorTemp;
  49272. };
  49273. //--------------------------------------------------------------------------------------
  49274. // Convert 3D vector to cubemap face texel coordinates and face idx
  49275. // note the U and V coords are integer coords and range from 0 to size-1
  49276. // this routine can be used to generate a normalizer cube map
  49277. //
  49278. // returns face IDX and texel coords
  49279. //--------------------------------------------------------------------------------------
  49280. // SL BEGIN
  49281. /*
  49282. Mapping Texture Coordinates to Cube Map Faces
  49283. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  49284. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  49285. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  49286. map arrangement in Pixar's RenderMan package.
  49287. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  49288. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  49289. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  49290. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  49291. the major axis direction). The target column in the table below explains how the major axis direction
  49292. maps to the 2D image of a particular cube map target.
  49293. major axis
  49294. direction target sc tc ma
  49295. ---------- --------------------------------- --- --- ---
  49296. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  49297. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  49298. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  49299. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  49300. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  49301. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  49302. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  49303. an updated (s,t) is calculated as follows
  49304. s = ( sc/|ma| + 1 ) / 2
  49305. t = ( tc/|ma| + 1 ) / 2
  49306. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  49307. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  49308. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  49309. */
  49310. // Note this method return U and V in range from 0 to size-1
  49311. // SL END
  49312. // Store the information in vector3 for convenience (faceindex, u, v)
  49313. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  49314. var maxCoord;
  49315. var faceIdx;
  49316. //absolute value 3
  49317. var absX = Math.abs(x);
  49318. var absY = Math.abs(y);
  49319. var absZ = Math.abs(z);
  49320. if (absX >= absY && absX >= absZ) {
  49321. maxCoord = absX;
  49322. if (x >= 0) {
  49323. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  49324. }
  49325. else {
  49326. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49327. }
  49328. }
  49329. else if (absY >= absX && absY >= absZ) {
  49330. maxCoord = absY;
  49331. if (y >= 0) {
  49332. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49333. }
  49334. else {
  49335. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49336. }
  49337. }
  49338. else {
  49339. maxCoord = absZ;
  49340. if (z >= 0) {
  49341. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49342. }
  49343. else {
  49344. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49345. }
  49346. }
  49347. //divide through by max coord so face vector lies on cube face
  49348. var scale = 1 / maxCoord;
  49349. x *= scale;
  49350. y *= scale;
  49351. z *= scale;
  49352. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49353. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  49354. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49355. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  49356. // Modify original AMD code to return value from 0 to Size - 1
  49357. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  49358. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  49359. PMREMGenerator._vectorTemp.x = faceIdx;
  49360. PMREMGenerator._vectorTemp.y = u;
  49361. PMREMGenerator._vectorTemp.z = v;
  49362. return PMREMGenerator._vectorTemp;
  49363. };
  49364. //--------------------------------------------------------------------------------------
  49365. //Original code from Ignacio CastaÒo
  49366. // This formula is from Manne ÷hrstrˆm's thesis.
  49367. // Take two coordiantes in the range [-1, 1] that define a portion of a
  49368. // cube face and return the area of the projection of that portion on the
  49369. // surface of the sphere.
  49370. //--------------------------------------------------------------------------------------
  49371. PMREMGenerator.prototype.areaElement = function (x, y) {
  49372. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  49373. };
  49374. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  49375. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49376. // (+ 0.5f is for texel center addressing)
  49377. u = (2.0 * (u + 0.5) / size) - 1.0;
  49378. v = (2.0 * (v + 0.5) / size) - 1.0;
  49379. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  49380. var invResolution = 1.0 / size;
  49381. // U and V are the -1..1 texture coordinate on the current face.
  49382. // Get projected area for this texel
  49383. var x0 = u - invResolution;
  49384. var y0 = v - invResolution;
  49385. var x1 = u + invResolution;
  49386. var y1 = v + invResolution;
  49387. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  49388. return solidAngle;
  49389. };
  49390. //--------------------------------------------------------------------------------------
  49391. //The key to the speed of these filtering routines is to quickly define a per-face
  49392. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  49393. // Later these pixels are selectively processed based on their dot products to see if
  49394. // they reside within the filtering cone.
  49395. //
  49396. //This is done by computing the smallest per-texel angle to get a conservative estimate
  49397. // of the number of texels needed to be covered in width and height order to filter the
  49398. // region. the bounding box for the center taps face is defined first, and if the
  49399. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  49400. // defined next
  49401. //--------------------------------------------------------------------------------------
  49402. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  49403. // note that pixels within these regions may be rejected
  49404. // based on the anlge
  49405. var iCubeFace;
  49406. var u;
  49407. var v;
  49408. // bounding box per face to specify region to process
  49409. var filterExtents = [];
  49410. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49411. filterExtents.push(new CMGBoundinBox());
  49412. }
  49413. // min angle a src texel can cover (in degrees)
  49414. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  49415. // angle about center tap to define filter cone
  49416. // filter angle is 1/2 the cone angle
  49417. var filterAngle = filterConeAngle / 2.0;
  49418. //ensure filter angle is larger than a texel
  49419. if (filterAngle < srcTexelAngle) {
  49420. filterAngle = srcTexelAngle;
  49421. }
  49422. //ensure filter cone is always smaller than the hemisphere
  49423. if (filterAngle > 90.0) {
  49424. filterAngle = 90.0;
  49425. }
  49426. // the maximum number of texels in 1D the filter cone angle will cover
  49427. // used to determine bounding box size for filter extents
  49428. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  49429. // ensure conservative region always covers at least one texel
  49430. if (filterSize < 1) {
  49431. filterSize = 1;
  49432. }
  49433. // dotProdThresh threshold based on cone angle to determine whether or not taps
  49434. // reside within the cone angle
  49435. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  49436. // process required faces
  49437. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49438. //iterate over dst cube map face texel
  49439. for (v = 0; v < dstSize; v++) {
  49440. for (u = 0; u < dstSize; u++) {
  49441. //get center tap direction
  49442. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  49443. //clear old per-face filter extents
  49444. this.clearFilterExtents(filterExtents);
  49445. //define per-face filter extents
  49446. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  49447. //perform filtering of src faces using filter extents
  49448. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  49449. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  49450. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  49451. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  49452. }
  49453. }
  49454. }
  49455. };
  49456. //--------------------------------------------------------------------------------------
  49457. //Clear filter extents for the 6 cube map faces
  49458. //--------------------------------------------------------------------------------------
  49459. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  49460. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  49461. filterExtents[iCubeFaces].clear();
  49462. }
  49463. };
  49464. //--------------------------------------------------------------------------------------
  49465. //Define per-face bounding box filter extents
  49466. //
  49467. // These define conservative texel regions in each of the faces the filter can possibly
  49468. // process. When the pixels in the regions are actually processed, the dot product
  49469. // between the tap vector and the center tap vector is used to determine the weight of
  49470. // the tap and whether or not the tap is within the cone.
  49471. //
  49472. //--------------------------------------------------------------------------------------
  49473. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  49474. //neighboring face and bleed over amount, and width of BBOX for
  49475. // left, right, top, and bottom edges of this face
  49476. var bleedOverAmount = [0, 0, 0, 0];
  49477. var bleedOverBBoxMin = [0, 0, 0, 0];
  49478. var bleedOverBBoxMax = [0, 0, 0, 0];
  49479. var neighborFace;
  49480. var neighborEdge;
  49481. var oppositeFaceIdx;
  49482. //get face idx, and u, v info from center tap dir
  49483. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  49484. var faceIdx = result.x;
  49485. var u = result.y;
  49486. var v = result.z;
  49487. //define bbox size within face
  49488. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  49489. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  49490. filterExtents[faceIdx].clampMin(0, 0, 0);
  49491. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  49492. //u and v extent in face corresponding to center tap
  49493. var minU = filterExtents[faceIdx].min.x;
  49494. var minV = filterExtents[faceIdx].min.y;
  49495. var maxU = filterExtents[faceIdx].max.x;
  49496. var maxV = filterExtents[faceIdx].max.y;
  49497. //bleed over amounts for face across u=0 edge (left)
  49498. bleedOverAmount[0] = (bboxSize - u);
  49499. bleedOverBBoxMin[0] = minV;
  49500. bleedOverBBoxMax[0] = maxV;
  49501. //bleed over amounts for face across u=1 edge (right)
  49502. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  49503. bleedOverBBoxMin[1] = minV;
  49504. bleedOverBBoxMax[1] = maxV;
  49505. //bleed over to face across v=0 edge (up)
  49506. bleedOverAmount[2] = (bboxSize - v);
  49507. bleedOverBBoxMin[2] = minU;
  49508. bleedOverBBoxMax[2] = maxU;
  49509. //bleed over to face across v=1 edge (down)
  49510. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  49511. bleedOverBBoxMin[3] = minU;
  49512. bleedOverBBoxMax[3] = maxU;
  49513. //compute bleed over regions in neighboring faces
  49514. for (var i = 0; i < 4; i++) {
  49515. if (bleedOverAmount[i] > 0) {
  49516. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  49517. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  49518. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  49519. // be flipped: the cases are
  49520. // if a left edge mates with a left or bottom edge on the neighbor
  49521. // if a top edge mates with a top or right edge on the neighbor
  49522. // if a right edge mates with a right or top edge on the neighbor
  49523. // if a bottom edge mates with a bottom or left edge on the neighbor
  49524. //Seeing as the edges are enumerated as follows
  49525. // left =0
  49526. // right =1
  49527. // top =2
  49528. // bottom =3
  49529. //
  49530. // so if the edge enums are the same, or the sum of the enums == 3,
  49531. // the bbox needs to be flipped
  49532. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  49533. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  49534. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  49535. }
  49536. //The way the bounding box is extended onto the neighboring face
  49537. // depends on which edge of neighboring face abuts with this one
  49538. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  49539. case PMREMGenerator.CP_EDGE_LEFT:
  49540. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  49541. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49542. break;
  49543. case PMREMGenerator.CP_EDGE_RIGHT:
  49544. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  49545. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49546. break;
  49547. case PMREMGenerator.CP_EDGE_TOP:
  49548. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  49549. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  49550. break;
  49551. case PMREMGenerator.CP_EDGE_BOTTOM:
  49552. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  49553. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  49554. break;
  49555. }
  49556. //clamp filter extents in non-center tap faces to remain within surface
  49557. filterExtents[neighborFace].clampMin(0, 0, 0);
  49558. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  49559. }
  49560. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  49561. // from the center tap face, then process the opposite face entirely for now.
  49562. //Note that the cases in which this happens, what usually happens is that
  49563. // more than one edge bleeds onto the opposite face, and the bounding box
  49564. // encompasses the entire cube map face.
  49565. if (bleedOverAmount[i] > srcSize) {
  49566. //determine opposite face
  49567. switch (faceIdx) {
  49568. case PMREMGenerator.CP_FACE_X_POS:
  49569. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49570. break;
  49571. case PMREMGenerator.CP_FACE_X_NEG:
  49572. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  49573. break;
  49574. case PMREMGenerator.CP_FACE_Y_POS:
  49575. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49576. break;
  49577. case PMREMGenerator.CP_FACE_Y_NEG:
  49578. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49579. break;
  49580. case PMREMGenerator.CP_FACE_Z_POS:
  49581. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49582. break;
  49583. case PMREMGenerator.CP_FACE_Z_NEG:
  49584. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49585. break;
  49586. default:
  49587. break;
  49588. }
  49589. //just encompass entire face for now
  49590. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  49591. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  49592. }
  49593. }
  49594. };
  49595. //--------------------------------------------------------------------------------------
  49596. //ProcessFilterExtents
  49597. // Process bounding box in each cube face
  49598. //
  49599. //--------------------------------------------------------------------------------------
  49600. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  49601. //accumulators are 64-bit floats in order to have the precision needed
  49602. // over a summation of a large number of pixels
  49603. var dstAccum = [0, 0, 0, 0];
  49604. var weightAccum = 0;
  49605. var k = 0;
  49606. var nSrcChannels = this.numChannels;
  49607. // norm cube map and srcCubeMap have same face width
  49608. var faceWidth = srcSize;
  49609. //amount to add to pointer to move to next scanline in images
  49610. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  49611. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  49612. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  49613. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  49614. // iterate over cubefaces
  49615. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  49616. //if bbox is non empty
  49617. if (!filterExtents[iFaceIdx].empty()) {
  49618. var uStart = filterExtents[iFaceIdx].min.x;
  49619. var vStart = filterExtents[iFaceIdx].min.y;
  49620. var uEnd = filterExtents[iFaceIdx].max.x;
  49621. var vEnd = filterExtents[iFaceIdx].max.y;
  49622. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  49623. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  49624. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  49625. for (var v = vStart; v <= vEnd; v++) {
  49626. var normCubeRowWalk = 0;
  49627. var srcCubeRowWalk = 0;
  49628. for (var u = uStart; u <= uEnd; u++) {
  49629. //pointer to direction in cube map associated with texel
  49630. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  49631. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  49632. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  49633. //check dot product to see if texel is within cone
  49634. var tapDotProd = texelVectX * centerTapDir.x +
  49635. texelVectY * centerTapDir.y +
  49636. texelVectZ * centerTapDir.z;
  49637. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  49638. //solid angle stored in 4th channel of normalizer/solid angle cube map
  49639. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  49640. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  49641. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  49642. // so just adding one to specularpower do the trick.
  49643. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  49644. //iterate over channels
  49645. for (k = 0; k < nSrcChannels; k++) {
  49646. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  49647. srcCubeRowWalk++;
  49648. }
  49649. weightAccum += weight; //accumulate weight
  49650. }
  49651. else {
  49652. //step across source pixel
  49653. srcCubeRowWalk += nSrcChannels;
  49654. }
  49655. normCubeRowWalk += 4; // 4 channels per norm cube map.
  49656. }
  49657. startIndexNormCubeMap += normCubePitch;
  49658. startIndexSrcCubeMap += srcCubePitch;
  49659. }
  49660. }
  49661. }
  49662. //divide through by weights if weight is non zero
  49663. if (weightAccum != 0.0) {
  49664. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  49665. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  49666. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  49667. if (this.numChannels > 3) {
  49668. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  49669. }
  49670. }
  49671. else {
  49672. // otherwise sample nearest
  49673. // get face idx and u, v texel coordinate in face
  49674. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  49675. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  49676. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  49677. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  49678. if (this.numChannels > 3) {
  49679. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  49680. }
  49681. }
  49682. return PMREMGenerator._vectorTemp;
  49683. };
  49684. //--------------------------------------------------------------------------------------
  49685. // Fixup cube edges
  49686. //
  49687. // average texels on cube map faces across the edges
  49688. // WARP/BENT Method Only.
  49689. //--------------------------------------------------------------------------------------
  49690. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  49691. var k;
  49692. var j;
  49693. var i;
  49694. var iFace;
  49695. var iCorner = 0;
  49696. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  49697. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  49698. // note that if functionality to filter across the three texels for each corner, then
  49699. //indexed by corner and face idx. the array contains the face the start points belongs to.
  49700. var cornerPtr = [
  49701. [[], [], []],
  49702. [[], [], []],
  49703. [[], [], []],
  49704. [[], [], []],
  49705. [[], [], []],
  49706. [[], [], []],
  49707. [[], [], []],
  49708. [[], [], []]
  49709. ];
  49710. //if there is no fixup, or fixup width = 0, do nothing
  49711. if (cubeMapSize < 1) {
  49712. return;
  49713. }
  49714. //special case 1x1 cubemap, average face colors
  49715. if (cubeMapSize == 1) {
  49716. //iterate over channels
  49717. for (k = 0; k < this.numChannels; k++) {
  49718. var accum = 0.0;
  49719. //iterate over faces to accumulate face colors
  49720. for (iFace = 0; iFace < 6; iFace++) {
  49721. accum += cubeMap[iFace][k];
  49722. }
  49723. //compute average over 6 face colors
  49724. accum /= 6.0;
  49725. //iterate over faces to distribute face colors
  49726. for (iFace = 0; iFace < 6; iFace++) {
  49727. cubeMap[iFace][k] = accum;
  49728. }
  49729. }
  49730. return;
  49731. }
  49732. //iterate over faces to collect list of corner texel pointers
  49733. for (iFace = 0; iFace < 6; iFace++) {
  49734. //the 4 corner pointers for this face
  49735. faceCornerStartIndicies[0] = [iFace, 0];
  49736. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  49737. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  49738. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  49739. //iterate over face corners to collect cube corner pointers
  49740. for (iCorner = 0; iCorner < 4; iCorner++) {
  49741. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  49742. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  49743. cornerNumPtrs[corner]++;
  49744. }
  49745. }
  49746. //iterate over corners to average across corner tap values
  49747. for (iCorner = 0; iCorner < 8; iCorner++) {
  49748. for (k = 0; k < this.numChannels; k++) {
  49749. var cornerTapAccum = 0.0;
  49750. //iterate over corner texels and average results
  49751. for (i = 0; i < 3; i++) {
  49752. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  49753. }
  49754. //divide by 3 to compute average of corner tap values
  49755. cornerTapAccum *= (1.0 / 3.0);
  49756. //iterate over corner texels and average results
  49757. for (i = 0; i < 3; i++) {
  49758. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  49759. }
  49760. }
  49761. }
  49762. //iterate over the twelve edges of the cube to average across edges
  49763. for (i = 0; i < 12; i++) {
  49764. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  49765. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  49766. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  49767. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  49768. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  49769. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  49770. var edgeWalk = 0;
  49771. var neighborEdgeWalk = 0;
  49772. //Determine walking pointers based on edge type
  49773. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  49774. switch (edge) {
  49775. case PMREMGenerator.CP_EDGE_LEFT:
  49776. // no change to faceEdgeStartPtr
  49777. edgeWalk = this.numChannels * cubeMapSize;
  49778. break;
  49779. case PMREMGenerator.CP_EDGE_RIGHT:
  49780. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49781. edgeWalk = this.numChannels * cubeMapSize;
  49782. break;
  49783. case PMREMGenerator.CP_EDGE_TOP:
  49784. // no change to faceEdgeStartPtr
  49785. edgeWalk = this.numChannels;
  49786. break;
  49787. case PMREMGenerator.CP_EDGE_BOTTOM:
  49788. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49789. edgeWalk = this.numChannels;
  49790. break;
  49791. }
  49792. //For certain types of edge abutments, the neighbor edge walk needs to
  49793. // be flipped: the cases are
  49794. // if a left edge mates with a left or bottom edge on the neighbor
  49795. // if a top edge mates with a top or right edge on the neighbor
  49796. // if a right edge mates with a right or top edge on the neighbor
  49797. // if a bottom edge mates with a bottom or left edge on the neighbor
  49798. //Seeing as the edges are enumerated as follows
  49799. // left =0
  49800. // right =1
  49801. // top =2
  49802. // bottom =3
  49803. //
  49804. //If the edge enums are the same, or the sum of the enums == 3,
  49805. // the neighbor edge walk needs to be flipped
  49806. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  49807. switch (neighborEdge) {
  49808. case PMREMGenerator.CP_EDGE_LEFT:
  49809. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  49810. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49811. break;
  49812. case PMREMGenerator.CP_EDGE_RIGHT:
  49813. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49814. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49815. break;
  49816. case PMREMGenerator.CP_EDGE_TOP:
  49817. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49818. neighborEdgeWalk = -this.numChannels;
  49819. break;
  49820. case PMREMGenerator.CP_EDGE_BOTTOM:
  49821. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49822. neighborEdgeWalk = -this.numChannels;
  49823. break;
  49824. }
  49825. }
  49826. else {
  49827. //swapped direction neighbor edge walk
  49828. switch (neighborEdge) {
  49829. case PMREMGenerator.CP_EDGE_LEFT:
  49830. //no change to neighborEdgeStartPtr for this case since it points
  49831. // to the upper left corner already
  49832. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49833. break;
  49834. case PMREMGenerator.CP_EDGE_RIGHT:
  49835. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49836. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49837. break;
  49838. case PMREMGenerator.CP_EDGE_TOP:
  49839. //no change to neighborEdgeStartPtr for this case since it points
  49840. // to the upper left corner already
  49841. neighborEdgeWalk = this.numChannels;
  49842. break;
  49843. case PMREMGenerator.CP_EDGE_BOTTOM:
  49844. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49845. neighborEdgeWalk = this.numChannels;
  49846. break;
  49847. }
  49848. }
  49849. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  49850. //nearby neighborhood
  49851. //step ahead one texel on edge
  49852. edgeStartIndex += edgeWalk;
  49853. neighborEdgeStartIndex += neighborEdgeWalk;
  49854. // note that this loop does not process the corner texels, since they have already been
  49855. // averaged across faces across earlier
  49856. for (j = 1; j < (cubeMapSize - 1); j++) {
  49857. //for each set of taps along edge, average them
  49858. // and rewrite the results into the edges
  49859. for (k = 0; k < this.numChannels; k++) {
  49860. var edgeTap = cubeMap[face][edgeStartIndex + k];
  49861. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  49862. //compute average of tap intensity values
  49863. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  49864. //propagate average of taps to edge taps
  49865. cubeMap[face][edgeStartIndex + k] = avgTap;
  49866. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  49867. }
  49868. edgeStartIndex += edgeWalk;
  49869. neighborEdgeStartIndex += neighborEdgeWalk;
  49870. }
  49871. }
  49872. };
  49873. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  49874. PMREMGenerator.CP_UDIR = 0;
  49875. PMREMGenerator.CP_VDIR = 1;
  49876. PMREMGenerator.CP_FACEAXIS = 2;
  49877. //used to index cube faces
  49878. PMREMGenerator.CP_FACE_X_POS = 0;
  49879. PMREMGenerator.CP_FACE_X_NEG = 1;
  49880. PMREMGenerator.CP_FACE_Y_POS = 2;
  49881. PMREMGenerator.CP_FACE_Y_NEG = 3;
  49882. PMREMGenerator.CP_FACE_Z_POS = 4;
  49883. PMREMGenerator.CP_FACE_Z_NEG = 5;
  49884. //used to index image edges
  49885. // NOTE.. the actual number corresponding to the edge is important
  49886. // do not change these, or the code will break
  49887. //
  49888. // CP_EDGE_LEFT is u = 0
  49889. // CP_EDGE_RIGHT is u = width-1
  49890. // CP_EDGE_TOP is v = 0
  49891. // CP_EDGE_BOTTOM is v = height-1
  49892. PMREMGenerator.CP_EDGE_LEFT = 0;
  49893. PMREMGenerator.CP_EDGE_RIGHT = 1;
  49894. PMREMGenerator.CP_EDGE_TOP = 2;
  49895. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  49896. //corners of CUBE map (P or N specifys if it corresponds to the
  49897. // positive or negative direction each of X, Y, and Z
  49898. PMREMGenerator.CP_CORNER_NNN = 0;
  49899. PMREMGenerator.CP_CORNER_NNP = 1;
  49900. PMREMGenerator.CP_CORNER_NPN = 2;
  49901. PMREMGenerator.CP_CORNER_NPP = 3;
  49902. PMREMGenerator.CP_CORNER_PNN = 4;
  49903. PMREMGenerator.CP_CORNER_PNP = 5;
  49904. PMREMGenerator.CP_CORNER_PPN = 6;
  49905. PMREMGenerator.CP_CORNER_PPP = 7;
  49906. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  49907. //3x2 matrices that map cube map indexing vectors in 3d
  49908. // (after face selection and divide through by the
  49909. // _ABSOLUTE VALUE_ of the max coord)
  49910. // into NVC space
  49911. //Note this currently assumes the D3D cube face ordering and orientation
  49912. PMREMGenerator._sgFace2DMapping = [
  49913. //XPOS face
  49914. [[0, 0, -1],
  49915. [0, -1, 0],
  49916. [1, 0, 0]],
  49917. //XNEG face
  49918. [[0, 0, 1],
  49919. [0, -1, 0],
  49920. [-1, 0, 0]],
  49921. //YPOS face
  49922. [[1, 0, 0],
  49923. [0, 0, 1],
  49924. [0, 1, 0]],
  49925. //YNEG face
  49926. [[1, 0, 0],
  49927. [0, 0, -1],
  49928. [0, -1, 0]],
  49929. //ZPOS face
  49930. [[1, 0, 0],
  49931. [0, -1, 0],
  49932. [0, 0, 1]],
  49933. //ZNEG face
  49934. [[-1, 0, 0],
  49935. [0, -1, 0],
  49936. [0, 0, -1]],
  49937. ];
  49938. //------------------------------------------------------------------------------
  49939. // D3D cube map face specification
  49940. // mapping from 3D x,y,z cube map lookup coordinates
  49941. // to 2D within face u,v coordinates
  49942. //
  49943. // --------------------> U direction
  49944. // | (within-face texture space)
  49945. // | _____
  49946. // | | |
  49947. // | | +Y |
  49948. // | _____|_____|_____ _____
  49949. // | | | | | |
  49950. // | | -X | +Z | +X | -Z |
  49951. // | |_____|_____|_____|_____|
  49952. // | | |
  49953. // | | -Y |
  49954. // | |_____|
  49955. // |
  49956. // v V direction
  49957. // (within-face texture space)
  49958. //------------------------------------------------------------------------------
  49959. //Information about neighbors and how texture coorrdinates change across faces
  49960. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  49961. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  49962. //Note this currently assumes the D3D cube face ordering and orientation
  49963. PMREMGenerator._sgCubeNgh = [
  49964. //XPOS face
  49965. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49966. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49967. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49968. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  49969. //XNEG face
  49970. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49971. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  49972. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  49973. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  49974. //YPOS face
  49975. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49976. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49977. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49978. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  49979. //YNEG face
  49980. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49981. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49982. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49983. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  49984. //ZPOS face
  49985. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49986. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49987. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49988. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  49989. //ZNEG face
  49990. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49991. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49992. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  49993. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  49994. ];
  49995. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  49996. // this table is used to average over the edges.
  49997. PMREMGenerator._sgCubeEdgeList = [
  49998. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49999. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50000. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50001. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50002. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50003. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50004. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50005. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50006. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  50007. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50008. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50009. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  50010. ];
  50011. //Information about which of the 8 cube corners are correspond to the
  50012. // the 4 corners in each cube face
  50013. // the order is upper left, upper right, lower left, lower right
  50014. PMREMGenerator._sgCubeCornerList = [
  50015. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  50016. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  50017. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  50018. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  50019. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  50020. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  50021. ];
  50022. return PMREMGenerator;
  50023. }());
  50024. Internals.PMREMGenerator = PMREMGenerator;
  50025. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50026. })(BABYLON || (BABYLON = {}));
  50027. var BABYLON;
  50028. (function (BABYLON) {
  50029. /**
  50030. * This represents a texture coming from an HDR input.
  50031. *
  50032. * The only supported format is currently panorama picture stored in RGBE format.
  50033. * Example of such files can be found on HDRLib: http://hdrlib.com/
  50034. */
  50035. var HDRCubeTexture = (function (_super) {
  50036. __extends(HDRCubeTexture, _super);
  50037. /**
  50038. * Instantiates an HDRTexture from the following parameters.
  50039. *
  50040. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  50041. * @param scene The scene the texture will be used in
  50042. * @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.
  50043. * @param noMipmap Forces to not generate the mipmap if true
  50044. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  50045. * @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)
  50046. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  50047. */
  50048. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50049. if (noMipmap === void 0) { noMipmap = false; }
  50050. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50051. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50052. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50053. _super.call(this, scene);
  50054. this._useInGammaSpace = false;
  50055. this._generateHarmonics = true;
  50056. this._isBABYLONPreprocessed = false;
  50057. /**
  50058. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  50059. */
  50060. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50061. /**
  50062. * The spherical polynomial data extracted from the texture.
  50063. */
  50064. this.sphericalPolynomial = null;
  50065. /**
  50066. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  50067. * This is usefull at run time to apply the good shader.
  50068. */
  50069. this.isPMREM = false;
  50070. if (!url) {
  50071. return;
  50072. }
  50073. this.name = url;
  50074. this.url = url;
  50075. this.hasAlpha = false;
  50076. this.isCube = true;
  50077. this._textureMatrix = BABYLON.Matrix.Identity();
  50078. if (size) {
  50079. this._isBABYLONPreprocessed = false;
  50080. this._noMipmap = noMipmap;
  50081. this._size = size;
  50082. this._useInGammaSpace = useInGammaSpace;
  50083. this._usePMREMGenerator = usePMREMGenerator &&
  50084. scene.getEngine().getCaps().textureLOD &&
  50085. this.getScene().getEngine().getCaps().textureFloat &&
  50086. !this._useInGammaSpace;
  50087. }
  50088. else {
  50089. this._isBABYLONPreprocessed = true;
  50090. this._noMipmap = false;
  50091. this._useInGammaSpace = false;
  50092. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  50093. this.getScene().getEngine().getCaps().textureFloat &&
  50094. !this._useInGammaSpace;
  50095. }
  50096. this.isPMREM = this._usePMREMGenerator;
  50097. this._texture = this._getFromCache(url, this._noMipmap);
  50098. if (!this._texture) {
  50099. if (!scene.useDelayedTextureLoading) {
  50100. this.loadTexture();
  50101. }
  50102. else {
  50103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50104. }
  50105. }
  50106. }
  50107. /**
  50108. * Occurs when the file is a preprocessed .babylon.hdr file.
  50109. */
  50110. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  50111. var _this = this;
  50112. var mipLevels = 0;
  50113. var floatArrayView = null;
  50114. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  50115. var mips = [];
  50116. var startIndex = 30;
  50117. for (var level = 0; level < mipLevels; level++) {
  50118. mips.push([]);
  50119. // Fill each pixel of the mip level.
  50120. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  50121. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50122. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  50123. mips[level].push(faceData);
  50124. startIndex += faceSize;
  50125. }
  50126. }
  50127. return mips;
  50128. } : null;
  50129. var callback = function (buffer) {
  50130. // Create Native Array Views
  50131. var intArrayView = new Int32Array(buffer);
  50132. floatArrayView = new Float32Array(buffer);
  50133. // Fill header.
  50134. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  50135. _this._size = intArrayView[1]; // CubeMap max mip face size.
  50136. // Update Texture Information.
  50137. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  50138. // Fill polynomial information.
  50139. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  50140. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  50141. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  50142. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  50143. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  50144. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  50145. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  50146. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  50147. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  50148. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  50149. // Fill pixel data.
  50150. mipLevels = intArrayView[29]; // Number of mip levels.
  50151. var startIndex = 30;
  50152. var data = [];
  50153. var faceSize = Math.pow(_this._size, 2) * 3;
  50154. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50155. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  50156. startIndex += faceSize;
  50157. }
  50158. var results = [];
  50159. var byteArray = null;
  50160. // Push each faces.
  50161. for (var k = 0; k < 6; k++) {
  50162. var dataFace = null;
  50163. // If special cases.
  50164. if (!mipmapGenerator) {
  50165. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  50166. dataFace = data[j];
  50167. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50168. // 3 channels of 1 bytes per pixel in bytes.
  50169. var byteBuffer = new ArrayBuffer(faceSize);
  50170. byteArray = new Uint8Array(byteBuffer);
  50171. }
  50172. for (var i = 0; i < _this._size * _this._size; i++) {
  50173. // Put in gamma space if requested.
  50174. if (_this._useInGammaSpace) {
  50175. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50176. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50177. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50178. }
  50179. // Convert to int texture for fallback.
  50180. if (byteArray) {
  50181. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50182. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50183. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50184. // May use luminance instead if the result is not accurate.
  50185. var max = Math.max(Math.max(r, g), b);
  50186. if (max > 255) {
  50187. var scale = 255 / max;
  50188. r *= scale;
  50189. g *= scale;
  50190. b *= scale;
  50191. }
  50192. byteArray[(i * 3) + 0] = r;
  50193. byteArray[(i * 3) + 1] = g;
  50194. byteArray[(i * 3) + 2] = b;
  50195. }
  50196. }
  50197. }
  50198. else {
  50199. dataFace = data[k];
  50200. }
  50201. // Fill the array accordingly.
  50202. if (byteArray) {
  50203. results.push(byteArray);
  50204. }
  50205. else {
  50206. results.push(dataFace);
  50207. }
  50208. }
  50209. return results;
  50210. };
  50211. 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);
  50212. };
  50213. /**
  50214. * Occurs when the file is raw .hdr file.
  50215. */
  50216. HDRCubeTexture.prototype.loadHDRTexture = function () {
  50217. var _this = this;
  50218. var callback = function (buffer) {
  50219. // Extract the raw linear data.
  50220. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  50221. // Generate harmonics if needed.
  50222. if (_this._generateHarmonics) {
  50223. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  50224. }
  50225. var results = [];
  50226. var byteArray = null;
  50227. // Push each faces.
  50228. for (var j = 0; j < 6; j++) {
  50229. // Create uintarray fallback.
  50230. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50231. // 3 channels of 1 bytes per pixel in bytes.
  50232. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  50233. byteArray = new Uint8Array(byteBuffer);
  50234. }
  50235. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  50236. // If special cases.
  50237. if (_this._useInGammaSpace || byteArray) {
  50238. for (var i = 0; i < _this._size * _this._size; i++) {
  50239. // Put in gamma space if requested.
  50240. if (_this._useInGammaSpace) {
  50241. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50242. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50243. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50244. }
  50245. // Convert to int texture for fallback.
  50246. if (byteArray) {
  50247. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50248. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50249. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50250. // May use luminance instead if the result is not accurate.
  50251. var max = Math.max(Math.max(r, g), b);
  50252. if (max > 255) {
  50253. var scale = 255 / max;
  50254. r *= scale;
  50255. g *= scale;
  50256. b *= scale;
  50257. }
  50258. byteArray[(i * 3) + 0] = r;
  50259. byteArray[(i * 3) + 1] = g;
  50260. byteArray[(i * 3) + 2] = b;
  50261. }
  50262. }
  50263. }
  50264. if (byteArray) {
  50265. results.push(byteArray);
  50266. }
  50267. else {
  50268. results.push(dataFace);
  50269. }
  50270. }
  50271. return results;
  50272. };
  50273. var mipmapGenerator = null;
  50274. if (!this._noMipmap &&
  50275. this._usePMREMGenerator) {
  50276. mipmapGenerator = function (data) {
  50277. // Custom setup of the generator matching with the PBR shader values.
  50278. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  50279. return generator.filterCubeMap();
  50280. };
  50281. }
  50282. 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);
  50283. };
  50284. /**
  50285. * Starts the loading process of the texture.
  50286. */
  50287. HDRCubeTexture.prototype.loadTexture = function () {
  50288. if (this._isBABYLONPreprocessed) {
  50289. this.loadBabylonTexture();
  50290. }
  50291. else {
  50292. this.loadHDRTexture();
  50293. }
  50294. };
  50295. HDRCubeTexture.prototype.clone = function () {
  50296. var size = this._isBABYLONPreprocessed ? null : this._size;
  50297. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  50298. // Base texture
  50299. newTexture.level = this.level;
  50300. newTexture.wrapU = this.wrapU;
  50301. newTexture.wrapV = this.wrapV;
  50302. newTexture.coordinatesIndex = this.coordinatesIndex;
  50303. newTexture.coordinatesMode = this.coordinatesMode;
  50304. return newTexture;
  50305. };
  50306. // Methods
  50307. HDRCubeTexture.prototype.delayLoad = function () {
  50308. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50309. return;
  50310. }
  50311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50312. this._texture = this._getFromCache(this.url, this._noMipmap);
  50313. if (!this._texture) {
  50314. this.loadTexture();
  50315. }
  50316. };
  50317. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  50318. return this._textureMatrix;
  50319. };
  50320. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50321. var texture = null;
  50322. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50323. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  50324. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  50325. texture.name = parsedTexture.name;
  50326. texture.hasAlpha = parsedTexture.hasAlpha;
  50327. texture.level = parsedTexture.level;
  50328. texture.coordinatesMode = parsedTexture.coordinatesMode;
  50329. }
  50330. return texture;
  50331. };
  50332. HDRCubeTexture.prototype.serialize = function () {
  50333. if (!this.name) {
  50334. return null;
  50335. }
  50336. var serializationObject = {};
  50337. serializationObject.name = this.name;
  50338. serializationObject.hasAlpha = this.hasAlpha;
  50339. serializationObject.isCube = true;
  50340. serializationObject.level = this.level;
  50341. serializationObject.size = this._size;
  50342. serializationObject.coordinatesMode = this.coordinatesMode;
  50343. serializationObject.useInGammaSpace = this._useInGammaSpace;
  50344. serializationObject.generateHarmonics = this._generateHarmonics;
  50345. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  50346. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  50347. serializationObject.customType = "BABYLON.HDRCubeTexture";
  50348. return serializationObject;
  50349. };
  50350. /**
  50351. * Saves as a file the data contained in the texture in a binary format.
  50352. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50353. * as the spherical used in the lighting.
  50354. * @param url The HDR file url.
  50355. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50356. * @param onError Method called if any error happens during download.
  50357. * @return The packed binary data.
  50358. */
  50359. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  50360. if (onError === void 0) { onError = null; }
  50361. var callback = function (buffer) {
  50362. var data = new Blob([buffer], { type: 'application/octet-stream' });
  50363. // Returns a URL you can use as a href.
  50364. var objUrl = window.URL.createObjectURL(data);
  50365. // Simulates a link to it and click to dowload.
  50366. var a = document.createElement("a");
  50367. document.body.appendChild(a);
  50368. a.style.display = "none";
  50369. a.href = objUrl;
  50370. a.download = "envmap.babylon.hdr";
  50371. a.click();
  50372. };
  50373. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  50374. };
  50375. /**
  50376. * Serializes the data contained in the texture in a binary format.
  50377. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50378. * as the spherical used in the lighting.
  50379. * @param url The HDR file url.
  50380. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50381. * @param onError Method called if any error happens during download.
  50382. * @return The packed binary data.
  50383. */
  50384. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  50385. if (onError === void 0) { onError = null; }
  50386. // Needs the url tho create the texture.
  50387. if (!url) {
  50388. return null;
  50389. }
  50390. // Check Power of two size.
  50391. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  50392. return null;
  50393. }
  50394. var getDataCallback = function (dataBuffer) {
  50395. // Extract the raw linear data.
  50396. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  50397. // Generate harmonics if needed.
  50398. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  50399. // Generate seamless faces
  50400. var mipGeneratorArray = [];
  50401. // Data are known to be in +X +Y +Z -X -Y -Z
  50402. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  50403. mipGeneratorArray.push(cubeData.right); // +X
  50404. mipGeneratorArray.push(cubeData.left); // -X
  50405. mipGeneratorArray.push(cubeData.up); // +Y
  50406. mipGeneratorArray.push(cubeData.down); // -Y
  50407. mipGeneratorArray.push(cubeData.front); // +Z
  50408. mipGeneratorArray.push(cubeData.back); // -Z
  50409. // Custom setup of the generator matching with the PBR shader values.
  50410. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  50411. var mippedData = generator.filterCubeMap();
  50412. // Compute required byte length.
  50413. var byteLength = 1 * 4; // Raw Data Version int32.
  50414. byteLength += 4; // CubeMap max mip face size int32.
  50415. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  50416. // Add data size.
  50417. byteLength += 4; // Number of mip levels int32.
  50418. for (var level = 0; level < mippedData.length; level++) {
  50419. var mipSize = size >> level;
  50420. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  50421. }
  50422. // Prepare binary structure.
  50423. var buffer = new ArrayBuffer(byteLength);
  50424. var intArrayView = new Int32Array(buffer);
  50425. var floatArrayView = new Float32Array(buffer);
  50426. // Fill header.
  50427. intArrayView[0] = 1; // Version 1.
  50428. intArrayView[1] = size; // CubeMap max mip face size.
  50429. // Fill polynomial information.
  50430. sphericalPolynomial.x.toArray(floatArrayView, 2);
  50431. sphericalPolynomial.y.toArray(floatArrayView, 5);
  50432. sphericalPolynomial.z.toArray(floatArrayView, 8);
  50433. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  50434. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  50435. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  50436. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  50437. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  50438. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  50439. // Fill pixel data.
  50440. intArrayView[29] = mippedData.length; // Number of mip levels.
  50441. var startIndex = 30;
  50442. for (var level = 0; level < mippedData.length; level++) {
  50443. // Fill each pixel of the mip level.
  50444. var faceSize = Math.pow(size >> level, 2) * 3;
  50445. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50446. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  50447. startIndex += faceSize;
  50448. }
  50449. }
  50450. // Callback.
  50451. callback(buffer);
  50452. };
  50453. // Download and process.
  50454. BABYLON.Tools.LoadFile(url, function (data) {
  50455. getDataCallback(data);
  50456. }, null, null, true, onError);
  50457. };
  50458. HDRCubeTexture._facesMapping = [
  50459. "right",
  50460. "up",
  50461. "front",
  50462. "left",
  50463. "down",
  50464. "back"
  50465. ];
  50466. return HDRCubeTexture;
  50467. }(BABYLON.BaseTexture));
  50468. BABYLON.HDRCubeTexture = HDRCubeTexture;
  50469. })(BABYLON || (BABYLON = {}));
  50470. var BABYLON;
  50471. (function (BABYLON) {
  50472. var Debug;
  50473. (function (Debug) {
  50474. /**
  50475. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  50476. */
  50477. var SkeletonViewer = (function () {
  50478. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  50479. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  50480. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  50481. this.skeleton = skeleton;
  50482. this.mesh = mesh;
  50483. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  50484. this.renderingGroupId = renderingGroupId;
  50485. this.color = BABYLON.Color3.White();
  50486. this._debugLines = [];
  50487. this._isEnabled = false;
  50488. this._scene = scene;
  50489. this.update();
  50490. this._renderFunction = this.update.bind(this);
  50491. }
  50492. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  50493. get: function () {
  50494. return this._isEnabled;
  50495. },
  50496. set: function (value) {
  50497. if (this._isEnabled === value) {
  50498. return;
  50499. }
  50500. this._isEnabled = value;
  50501. if (value) {
  50502. this._scene.registerBeforeRender(this._renderFunction);
  50503. }
  50504. else {
  50505. this._scene.unregisterBeforeRender(this._renderFunction);
  50506. }
  50507. },
  50508. enumerable: true,
  50509. configurable: true
  50510. });
  50511. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  50512. if (x === void 0) { x = 0; }
  50513. if (y === void 0) { y = 0; }
  50514. if (z === void 0) { z = 0; }
  50515. var tmat = BABYLON.Tmp.Matrix[0];
  50516. var parentBone = bone.getParent();
  50517. tmat.copyFrom(bone.getLocalMatrix());
  50518. if (x !== 0 || y !== 0 || z !== 0) {
  50519. var tmat2 = BABYLON.Tmp.Matrix[1];
  50520. BABYLON.Matrix.IdentityToRef(tmat2);
  50521. tmat2.m[12] = x;
  50522. tmat2.m[13] = y;
  50523. tmat2.m[14] = z;
  50524. tmat2.multiplyToRef(tmat, tmat);
  50525. }
  50526. if (parentBone) {
  50527. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  50528. }
  50529. tmat.multiplyToRef(meshMat, tmat);
  50530. position.x = tmat.m[12];
  50531. position.y = tmat.m[13];
  50532. position.z = tmat.m[14];
  50533. };
  50534. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  50535. var len = bones.length;
  50536. for (var i = 0; i < len; i++) {
  50537. var bone = bones[i];
  50538. var points = this._debugLines[i];
  50539. if (!points) {
  50540. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50541. this._debugLines[i] = points;
  50542. }
  50543. this._getBonePosition(points[0], bone, meshMat);
  50544. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  50545. }
  50546. };
  50547. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  50548. var len = bones.length;
  50549. var boneNum = 0;
  50550. for (var i = len - 1; i >= 0; i--) {
  50551. var childBone = bones[i];
  50552. var parentBone = childBone.getParent();
  50553. if (!parentBone) {
  50554. continue;
  50555. }
  50556. var points = this._debugLines[boneNum];
  50557. if (!points) {
  50558. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50559. this._debugLines[boneNum] = points;
  50560. }
  50561. this._getBonePosition(points[0], childBone, meshMat);
  50562. this._getBonePosition(points[1], parentBone, meshMat);
  50563. boneNum++;
  50564. }
  50565. };
  50566. SkeletonViewer.prototype.update = function () {
  50567. if (this.autoUpdateBonesMatrices) {
  50568. this._updateBoneMatrix(this.skeleton.bones[0]);
  50569. }
  50570. if (this.skeleton.bones[0].length === undefined) {
  50571. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50572. }
  50573. else {
  50574. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50575. }
  50576. if (!this._debugMesh) {
  50577. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  50578. this._debugMesh.renderingGroupId = this.renderingGroupId;
  50579. }
  50580. else {
  50581. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  50582. }
  50583. this._debugMesh.color = this.color;
  50584. };
  50585. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  50586. if (bone.getParent()) {
  50587. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  50588. }
  50589. var children = bone.children;
  50590. var len = children.length;
  50591. for (var i = 0; i < len; i++) {
  50592. this._updateBoneMatrix(children[i]);
  50593. }
  50594. };
  50595. SkeletonViewer.prototype.dispose = function () {
  50596. if (this._debugMesh) {
  50597. this.isEnabled = false;
  50598. this._debugMesh.dispose();
  50599. this._debugMesh = null;
  50600. }
  50601. };
  50602. return SkeletonViewer;
  50603. }());
  50604. Debug.SkeletonViewer = SkeletonViewer;
  50605. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  50606. })(BABYLON || (BABYLON = {}));
  50607. var BABYLON;
  50608. (function (BABYLON) {
  50609. /**
  50610. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  50611. * It can help converting any input color in a desired output one. This can then be used to create effects
  50612. * from sepia, black and white to sixties or futuristic rendering...
  50613. *
  50614. * The only supported format is currently 3dl.
  50615. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  50616. */
  50617. var ColorGradingTexture = (function (_super) {
  50618. __extends(ColorGradingTexture, _super);
  50619. /**
  50620. * Instantiates a ColorGradingTexture from the following parameters.
  50621. *
  50622. * @param url The location of the color gradind data (currently only supporting 3dl)
  50623. * @param scene The scene the texture will be used in
  50624. */
  50625. function ColorGradingTexture(url, scene) {
  50626. _super.call(this, scene);
  50627. if (!url) {
  50628. return;
  50629. }
  50630. this._textureMatrix = BABYLON.Matrix.Identity();
  50631. this.name = url;
  50632. this.url = url;
  50633. this.hasAlpha = false;
  50634. this.isCube = false;
  50635. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50636. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50637. this.anisotropicFilteringLevel = 1;
  50638. this._texture = this._getFromCache(url, true);
  50639. if (!this._texture) {
  50640. if (!scene.useDelayedTextureLoading) {
  50641. this.loadTexture();
  50642. }
  50643. else {
  50644. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50645. }
  50646. }
  50647. }
  50648. /**
  50649. * Returns the texture matrix used in most of the material.
  50650. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  50651. */
  50652. ColorGradingTexture.prototype.getTextureMatrix = function () {
  50653. return this._textureMatrix;
  50654. };
  50655. /**
  50656. * Occurs when the file being loaded is a .3dl LUT file.
  50657. */
  50658. ColorGradingTexture.prototype.load3dlTexture = function () {
  50659. var _this = this;
  50660. var mipLevels = 0;
  50661. var floatArrayView = null;
  50662. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50663. this._texture = texture;
  50664. var callback = function (text) {
  50665. var data;
  50666. var tempData;
  50667. var line;
  50668. var lines = text.split('\n');
  50669. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  50670. var maxColor = 0;
  50671. for (var i = 0; i < lines.length; i++) {
  50672. line = lines[i];
  50673. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  50674. continue;
  50675. if (line.indexOf('#') === 0)
  50676. continue;
  50677. var words = line.split(" ");
  50678. if (size === 0) {
  50679. // Number of space + one
  50680. size = words.length;
  50681. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  50682. tempData = new Float32Array(size * size * size * 4);
  50683. continue;
  50684. }
  50685. if (size != 0) {
  50686. var r = Math.max(parseInt(words[0]), 0);
  50687. var g = Math.max(parseInt(words[1]), 0);
  50688. var b = Math.max(parseInt(words[2]), 0);
  50689. maxColor = Math.max(r, maxColor);
  50690. maxColor = Math.max(g, maxColor);
  50691. maxColor = Math.max(b, maxColor);
  50692. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  50693. tempData[pixelStorageIndex + 0] = r;
  50694. tempData[pixelStorageIndex + 1] = g;
  50695. tempData[pixelStorageIndex + 2] = b;
  50696. tempData[pixelStorageIndex + 3] = 0;
  50697. pixelIndexSlice++;
  50698. if (pixelIndexSlice % size == 0) {
  50699. pixelIndexH++;
  50700. pixelIndexSlice = 0;
  50701. if (pixelIndexH % size == 0) {
  50702. pixelIndexW++;
  50703. pixelIndexH = 0;
  50704. }
  50705. }
  50706. }
  50707. }
  50708. for (var i = 0; i < tempData.length; i++) {
  50709. var value = tempData[i];
  50710. data[i] = (value / maxColor * 255);
  50711. }
  50712. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  50713. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  50714. };
  50715. BABYLON.Tools.LoadFile(this.url, callback);
  50716. return this._texture;
  50717. };
  50718. /**
  50719. * Starts the loading process of the texture.
  50720. */
  50721. ColorGradingTexture.prototype.loadTexture = function () {
  50722. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  50723. this.load3dlTexture();
  50724. }
  50725. };
  50726. /**
  50727. * Clones the color gradind texture.
  50728. */
  50729. ColorGradingTexture.prototype.clone = function () {
  50730. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  50731. // Base texture
  50732. newTexture.level = this.level;
  50733. return newTexture;
  50734. };
  50735. /**
  50736. * Called during delayed load for textures.
  50737. */
  50738. ColorGradingTexture.prototype.delayLoad = function () {
  50739. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50740. return;
  50741. }
  50742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50743. this._texture = this._getFromCache(this.url, true);
  50744. if (!this._texture) {
  50745. this.loadTexture();
  50746. }
  50747. };
  50748. /**
  50749. * Binds the color grading to the shader.
  50750. * @param colorGrading The texture to bind
  50751. * @param effect The effect to bind to
  50752. */
  50753. ColorGradingTexture.Bind = function (colorGrading, effect) {
  50754. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  50755. var x = colorGrading.level; // Texture Level
  50756. var y = colorGrading.getSize().height; // Texture Size example with 8
  50757. var z = y - 1.0; // SizeMinusOne 8 - 1
  50758. var w = 1 / y; // Space of 1 slice 1 / 8
  50759. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  50760. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  50761. 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
  50762. 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
  50763. 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
  50764. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  50765. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  50766. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  50767. };
  50768. /**
  50769. * Prepare the list of uniforms associated with the ColorGrading effects.
  50770. * @param uniformsList The list of uniforms used in the effect
  50771. * @param samplersList The list of samplers used in the effect
  50772. */
  50773. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  50774. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  50775. samplersList.push("cameraColorGrading2DSampler");
  50776. };
  50777. /**
  50778. * Parses a color grading texture serialized by Babylon.
  50779. * @param parsedTexture The texture information being parsedTexture
  50780. * @param scene The scene to load the texture in
  50781. * @param rootUrl The root url of the data assets to load
  50782. * @return A color gradind texture
  50783. */
  50784. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50785. var texture = null;
  50786. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50787. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  50788. texture.name = parsedTexture.name;
  50789. texture.level = parsedTexture.level;
  50790. }
  50791. return texture;
  50792. };
  50793. /**
  50794. * Serializes the LUT texture to json format.
  50795. */
  50796. ColorGradingTexture.prototype.serialize = function () {
  50797. if (!this.name) {
  50798. return null;
  50799. }
  50800. var serializationObject = {};
  50801. serializationObject.name = this.name;
  50802. serializationObject.level = this.level;
  50803. serializationObject.customType = "BABYLON.ColorGradingTexture";
  50804. return serializationObject;
  50805. };
  50806. /**
  50807. * Empty line regex stored for GC.
  50808. */
  50809. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  50810. return ColorGradingTexture;
  50811. }(BABYLON.BaseTexture));
  50812. BABYLON.ColorGradingTexture = ColorGradingTexture;
  50813. })(BABYLON || (BABYLON = {}));
  50814. var BABYLON;
  50815. (function (BABYLON) {
  50816. /**
  50817. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  50818. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  50819. * 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;
  50820. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  50821. */
  50822. var ColorCurves = (function () {
  50823. function ColorCurves() {
  50824. this._dirty = true;
  50825. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  50826. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  50827. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50828. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  50829. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50830. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  50831. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  50832. this._globalHue = 30;
  50833. this._globalDensity = 0;
  50834. this._globalSaturation = 0;
  50835. this._globalExposure = 0;
  50836. this._highlightsHue = 30;
  50837. this._highlightsDensity = 0;
  50838. this._highlightsSaturation = 0;
  50839. this._highlightsExposure = 0;
  50840. this._midtonesHue = 30;
  50841. this._midtonesDensity = 0;
  50842. this._midtonesSaturation = 0;
  50843. this._midtonesExposure = 0;
  50844. this._shadowsHue = 30;
  50845. this._shadowsDensity = 0;
  50846. this._shadowsSaturation = 0;
  50847. this._shadowsExposure = 0;
  50848. }
  50849. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  50850. /**
  50851. * Gets the global Hue value.
  50852. * 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).
  50853. */
  50854. get: function () {
  50855. return this._globalHue;
  50856. },
  50857. /**
  50858. * Sets the global Hue value.
  50859. * 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).
  50860. */
  50861. set: function (value) {
  50862. this._globalHue = value;
  50863. this._dirty = true;
  50864. },
  50865. enumerable: true,
  50866. configurable: true
  50867. });
  50868. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  50869. /**
  50870. * Gets the global Density value.
  50871. * 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.
  50872. * Values less than zero provide a filter of opposite hue.
  50873. */
  50874. get: function () {
  50875. return this._globalDensity;
  50876. },
  50877. /**
  50878. * Sets the global Density value.
  50879. * 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.
  50880. * Values less than zero provide a filter of opposite hue.
  50881. */
  50882. set: function (value) {
  50883. this._globalDensity = value;
  50884. this._dirty = true;
  50885. },
  50886. enumerable: true,
  50887. configurable: true
  50888. });
  50889. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  50890. /**
  50891. * Gets the global Saturation value.
  50892. * 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.
  50893. */
  50894. get: function () {
  50895. return this._globalSaturation;
  50896. },
  50897. /**
  50898. * Sets the global Saturation value.
  50899. * 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.
  50900. */
  50901. set: function (value) {
  50902. this._globalSaturation = value;
  50903. this._dirty = true;
  50904. },
  50905. enumerable: true,
  50906. configurable: true
  50907. });
  50908. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  50909. /**
  50910. * Gets the highlights Hue value.
  50911. * 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).
  50912. */
  50913. get: function () {
  50914. return this._highlightsHue;
  50915. },
  50916. /**
  50917. * Sets the highlights Hue value.
  50918. * 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).
  50919. */
  50920. set: function (value) {
  50921. this._highlightsHue = value;
  50922. this._dirty = true;
  50923. },
  50924. enumerable: true,
  50925. configurable: true
  50926. });
  50927. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  50928. /**
  50929. * Gets the highlights Density value.
  50930. * 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.
  50931. * Values less than zero provide a filter of opposite hue.
  50932. */
  50933. get: function () {
  50934. return this._highlightsDensity;
  50935. },
  50936. /**
  50937. * Sets the highlights Density value.
  50938. * 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.
  50939. * Values less than zero provide a filter of opposite hue.
  50940. */
  50941. set: function (value) {
  50942. this._highlightsDensity = value;
  50943. this._dirty = true;
  50944. },
  50945. enumerable: true,
  50946. configurable: true
  50947. });
  50948. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  50949. /**
  50950. * Gets the highlights Saturation value.
  50951. * 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.
  50952. */
  50953. get: function () {
  50954. return this._highlightsSaturation;
  50955. },
  50956. /**
  50957. * Sets the highlights Saturation value.
  50958. * 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.
  50959. */
  50960. set: function (value) {
  50961. this._highlightsSaturation = value;
  50962. this._dirty = true;
  50963. },
  50964. enumerable: true,
  50965. configurable: true
  50966. });
  50967. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  50968. /**
  50969. * Gets the highlights Exposure value.
  50970. * 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.
  50971. */
  50972. get: function () {
  50973. return this._highlightsExposure;
  50974. },
  50975. /**
  50976. * Sets the highlights Exposure value.
  50977. * 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.
  50978. */
  50979. set: function (value) {
  50980. this._highlightsExposure = value;
  50981. this._dirty = true;
  50982. },
  50983. enumerable: true,
  50984. configurable: true
  50985. });
  50986. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  50987. /**
  50988. * Gets the midtones Hue value.
  50989. * 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).
  50990. */
  50991. get: function () {
  50992. return this._midtonesHue;
  50993. },
  50994. /**
  50995. * Sets the midtones Hue value.
  50996. * 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).
  50997. */
  50998. set: function (value) {
  50999. this._midtonesHue = value;
  51000. this._dirty = true;
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  51006. /**
  51007. * Gets the midtones Density value.
  51008. * 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.
  51009. * Values less than zero provide a filter of opposite hue.
  51010. */
  51011. get: function () {
  51012. return this._midtonesDensity;
  51013. },
  51014. /**
  51015. * Sets the midtones Density value.
  51016. * 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.
  51017. * Values less than zero provide a filter of opposite hue.
  51018. */
  51019. set: function (value) {
  51020. this._midtonesDensity = value;
  51021. this._dirty = true;
  51022. },
  51023. enumerable: true,
  51024. configurable: true
  51025. });
  51026. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  51027. /**
  51028. * Gets the midtones Saturation value.
  51029. * 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.
  51030. */
  51031. get: function () {
  51032. return this._midtonesSaturation;
  51033. },
  51034. /**
  51035. * Sets the midtones Saturation value.
  51036. * 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.
  51037. */
  51038. set: function (value) {
  51039. this._midtonesSaturation = value;
  51040. this._dirty = true;
  51041. },
  51042. enumerable: true,
  51043. configurable: true
  51044. });
  51045. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  51046. /**
  51047. * Gets the midtones Exposure value.
  51048. * 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.
  51049. */
  51050. get: function () {
  51051. return this._midtonesExposure;
  51052. },
  51053. /**
  51054. * Sets the midtones Exposure value.
  51055. * 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.
  51056. */
  51057. set: function (value) {
  51058. this._midtonesExposure = value;
  51059. this._dirty = true;
  51060. },
  51061. enumerable: true,
  51062. configurable: true
  51063. });
  51064. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  51065. /**
  51066. * Gets the shadows Hue value.
  51067. * 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).
  51068. */
  51069. get: function () {
  51070. return this._shadowsHue;
  51071. },
  51072. /**
  51073. * Sets the shadows Hue value.
  51074. * 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).
  51075. */
  51076. set: function (value) {
  51077. this._shadowsHue = value;
  51078. this._dirty = true;
  51079. },
  51080. enumerable: true,
  51081. configurable: true
  51082. });
  51083. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  51084. /**
  51085. * Gets the shadows Density value.
  51086. * 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.
  51087. * Values less than zero provide a filter of opposite hue.
  51088. */
  51089. get: function () {
  51090. return this._shadowsDensity;
  51091. },
  51092. /**
  51093. * Sets the shadows Density value.
  51094. * 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.
  51095. * Values less than zero provide a filter of opposite hue.
  51096. */
  51097. set: function (value) {
  51098. this._shadowsDensity = value;
  51099. this._dirty = true;
  51100. },
  51101. enumerable: true,
  51102. configurable: true
  51103. });
  51104. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  51105. /**
  51106. * Gets the shadows Saturation value.
  51107. * 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.
  51108. */
  51109. get: function () {
  51110. return this._shadowsSaturation;
  51111. },
  51112. /**
  51113. * Sets the shadows Saturation value.
  51114. * 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.
  51115. */
  51116. set: function (value) {
  51117. this._shadowsSaturation = value;
  51118. this._dirty = true;
  51119. },
  51120. enumerable: true,
  51121. configurable: true
  51122. });
  51123. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  51124. /**
  51125. * Gets the shadows Exposure value.
  51126. * 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.
  51127. */
  51128. get: function () {
  51129. return this._shadowsExposure;
  51130. },
  51131. /**
  51132. * Sets the shadows Exposure value.
  51133. * 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.
  51134. */
  51135. set: function (value) {
  51136. this._shadowsExposure = value;
  51137. this._dirty = true;
  51138. },
  51139. enumerable: true,
  51140. configurable: true
  51141. });
  51142. /**
  51143. * Binds the color curves to the shader.
  51144. * @param colorCurves The color curve to bind
  51145. * @param effect The effect to bind to
  51146. */
  51147. ColorCurves.Bind = function (colorCurves, effect) {
  51148. if (colorCurves._dirty) {
  51149. colorCurves._dirty = false;
  51150. // Fill in global info.
  51151. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  51152. // Compute highlights info.
  51153. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  51154. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  51155. // Compute midtones info.
  51156. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  51157. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  51158. // Compute shadows info.
  51159. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  51160. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  51161. // Compute deltas (neutral is midtones).
  51162. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  51163. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  51164. }
  51165. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  51166. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  51167. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  51168. };
  51169. /**
  51170. * Prepare the list of uniforms associated with the ColorCurves effects.
  51171. * @param uniformsList The list of uniforms used in the effect
  51172. */
  51173. ColorCurves.PrepareUniforms = function (uniformsList) {
  51174. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  51175. };
  51176. /**
  51177. * Returns color grading data based on a hue, density, saturation and exposure value.
  51178. * @param filterHue The hue of the color filter.
  51179. * @param filterDensity The density of the color filter.
  51180. * @param saturation The saturation.
  51181. * @param exposure The exposure.
  51182. * @param result The result data container.
  51183. */
  51184. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  51185. if (hue == null) {
  51186. return;
  51187. }
  51188. hue = ColorCurves.clamp(hue, 0, 360);
  51189. density = ColorCurves.clamp(density, -100, 100);
  51190. saturation = ColorCurves.clamp(saturation, -100, 100);
  51191. exposure = ColorCurves.clamp(exposure, -100, 100);
  51192. // Remap the slider/config filter density with non-linear mapping and also scale by half
  51193. // so that the maximum filter density is only 50% control. This provides fine control
  51194. // for small values and reasonable range.
  51195. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  51196. density *= 0.5;
  51197. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  51198. if (density < 0) {
  51199. density *= -1;
  51200. hue = (hue + 180) % 360;
  51201. }
  51202. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  51203. result.scaleToRef(2, result);
  51204. result.a = 1 + 0.01 * saturation;
  51205. };
  51206. /**
  51207. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  51208. * @param value The input slider value in range [-100,100].
  51209. * @returns Adjusted value.
  51210. */
  51211. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  51212. value /= 100;
  51213. var x = Math.abs(value);
  51214. x = Math.pow(x, 2);
  51215. if (value < 0) {
  51216. x *= -1;
  51217. }
  51218. x *= 100;
  51219. return x;
  51220. };
  51221. /**
  51222. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  51223. * @param hue The hue (H) input.
  51224. * @param saturation The saturation (S) input.
  51225. * @param brightness The brightness (B) input.
  51226. * @result An RGBA color represented as Vector4.
  51227. */
  51228. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  51229. var h = ColorCurves.clamp(hue, 0, 360);
  51230. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  51231. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  51232. if (s === 0) {
  51233. result.r = v;
  51234. result.g = v;
  51235. result.b = v;
  51236. }
  51237. else {
  51238. // sector 0 to 5
  51239. h /= 60;
  51240. var i = Math.floor(h);
  51241. // fractional part of h
  51242. var f = h - i;
  51243. var p = v * (1 - s);
  51244. var q = v * (1 - s * f);
  51245. var t = v * (1 - s * (1 - f));
  51246. switch (i) {
  51247. case 0:
  51248. result.r = v;
  51249. result.g = t;
  51250. result.b = p;
  51251. break;
  51252. case 1:
  51253. result.r = q;
  51254. result.g = v;
  51255. result.b = p;
  51256. break;
  51257. case 2:
  51258. result.r = p;
  51259. result.g = v;
  51260. result.b = t;
  51261. break;
  51262. case 3:
  51263. result.r = p;
  51264. result.g = q;
  51265. result.b = v;
  51266. break;
  51267. case 4:
  51268. result.r = t;
  51269. result.g = p;
  51270. result.b = v;
  51271. break;
  51272. default:
  51273. result.r = v;
  51274. result.g = p;
  51275. result.b = q;
  51276. break;
  51277. }
  51278. }
  51279. result.a = 1;
  51280. };
  51281. /**
  51282. * Returns a value clamped between min and max
  51283. * @param value The value to clamp
  51284. * @param min The minimum of value
  51285. * @param max The maximum of value
  51286. * @returns The clamped value.
  51287. */
  51288. ColorCurves.clamp = function (value, min, max) {
  51289. return Math.min(Math.max(value, min), max);
  51290. };
  51291. /**
  51292. * Clones the current color curve instance.
  51293. * @return The cloned curves
  51294. */
  51295. ColorCurves.prototype.clone = function () {
  51296. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  51297. };
  51298. /**
  51299. * Serializes the current color curve instance to a json representation.
  51300. * @return a JSON representation
  51301. */
  51302. ColorCurves.prototype.serialize = function () {
  51303. return BABYLON.SerializationHelper.Serialize(this);
  51304. };
  51305. /**
  51306. * Parses the color curve from a json representation.
  51307. * @param source the JSON source to parse
  51308. * @return The parsed curves
  51309. */
  51310. ColorCurves.Parse = function (source) {
  51311. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  51312. };
  51313. __decorate([
  51314. BABYLON.serialize()
  51315. ], ColorCurves.prototype, "_globalHue", void 0);
  51316. __decorate([
  51317. BABYLON.serialize()
  51318. ], ColorCurves.prototype, "_globalDensity", void 0);
  51319. __decorate([
  51320. BABYLON.serialize()
  51321. ], ColorCurves.prototype, "_globalSaturation", void 0);
  51322. __decorate([
  51323. BABYLON.serialize()
  51324. ], ColorCurves.prototype, "_globalExposure", void 0);
  51325. __decorate([
  51326. BABYLON.serialize()
  51327. ], ColorCurves.prototype, "_highlightsHue", void 0);
  51328. __decorate([
  51329. BABYLON.serialize()
  51330. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  51331. __decorate([
  51332. BABYLON.serialize()
  51333. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  51334. __decorate([
  51335. BABYLON.serialize()
  51336. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  51337. __decorate([
  51338. BABYLON.serialize()
  51339. ], ColorCurves.prototype, "_midtonesHue", void 0);
  51340. __decorate([
  51341. BABYLON.serialize()
  51342. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  51343. __decorate([
  51344. BABYLON.serialize()
  51345. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  51346. __decorate([
  51347. BABYLON.serialize()
  51348. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  51349. return ColorCurves;
  51350. }());
  51351. BABYLON.ColorCurves = ColorCurves;
  51352. })(BABYLON || (BABYLON = {}));
  51353. var BABYLON;
  51354. (function (BABYLON) {
  51355. var PBRMaterialDefines = (function (_super) {
  51356. __extends(PBRMaterialDefines, _super);
  51357. function PBRMaterialDefines() {
  51358. _super.call(this);
  51359. this.ALBEDO = false;
  51360. this.AMBIENT = false;
  51361. this.OPACITY = false;
  51362. this.OPACITYRGB = false;
  51363. this.REFLECTION = false;
  51364. this.EMISSIVE = false;
  51365. this.REFLECTIVITY = false;
  51366. this.BUMP = false;
  51367. this.PARALLAX = false;
  51368. this.PARALLAXOCCLUSION = false;
  51369. this.SPECULAROVERALPHA = false;
  51370. this.CLIPPLANE = false;
  51371. this.ALPHATEST = false;
  51372. this.ALPHAFROMALBEDO = false;
  51373. this.POINTSIZE = false;
  51374. this.FOG = false;
  51375. this.SPECULARTERM = false;
  51376. this.OPACITYFRESNEL = false;
  51377. this.EMISSIVEFRESNEL = false;
  51378. this.FRESNEL = false;
  51379. this.NORMAL = false;
  51380. this.UV1 = false;
  51381. this.UV2 = false;
  51382. this.VERTEXCOLOR = false;
  51383. this.VERTEXALPHA = false;
  51384. this.NUM_BONE_INFLUENCERS = 0;
  51385. this.BonesPerMesh = 0;
  51386. this.INSTANCES = false;
  51387. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  51388. this.MICROSURFACEAUTOMATIC = false;
  51389. this.EMISSIVEASILLUMINATION = false;
  51390. this.LINKEMISSIVEWITHALBEDO = false;
  51391. this.LIGHTMAP = false;
  51392. this.USELIGHTMAPASSHADOWMAP = false;
  51393. this.REFLECTIONMAP_3D = false;
  51394. this.REFLECTIONMAP_SPHERICAL = false;
  51395. this.REFLECTIONMAP_PLANAR = false;
  51396. this.REFLECTIONMAP_CUBIC = false;
  51397. this.REFLECTIONMAP_PROJECTION = false;
  51398. this.REFLECTIONMAP_SKYBOX = false;
  51399. this.REFLECTIONMAP_EXPLICIT = false;
  51400. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  51401. this.INVERTCUBICMAP = false;
  51402. this.LOGARITHMICDEPTH = false;
  51403. this.CAMERATONEMAP = false;
  51404. this.CAMERACONTRAST = false;
  51405. this.CAMERACOLORGRADING = false;
  51406. this.CAMERACOLORCURVES = false;
  51407. this.OVERLOADEDVALUES = false;
  51408. this.OVERLOADEDSHADOWVALUES = false;
  51409. this.USESPHERICALFROMREFLECTIONMAP = false;
  51410. this.REFRACTION = false;
  51411. this.REFRACTIONMAP_3D = false;
  51412. this.LINKREFRACTIONTOTRANSPARENCY = false;
  51413. this.REFRACTIONMAPINLINEARSPACE = false;
  51414. this.LODBASEDMICROSFURACE = false;
  51415. this.USEPHYSICALLIGHTFALLOFF = false;
  51416. this.RADIANCEOVERALPHA = false;
  51417. this.USEPMREMREFLECTION = false;
  51418. this.USEPMREMREFRACTION = false;
  51419. this.OPENGLNORMALMAP = false;
  51420. this.INVERTNORMALMAPX = false;
  51421. this.INVERTNORMALMAPY = false;
  51422. this.SHADOWFULLFLOAT = false;
  51423. this.rebuild();
  51424. }
  51425. return PBRMaterialDefines;
  51426. }(BABYLON.MaterialDefines));
  51427. /**
  51428. * The Physically based material of BJS.
  51429. *
  51430. * This offers the main features of a standard PBR material.
  51431. * For more information, please refer to the documentation :
  51432. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  51433. */
  51434. var PBRMaterial = (function (_super) {
  51435. __extends(PBRMaterial, _super);
  51436. /**
  51437. * Instantiates a new PBRMaterial instance.
  51438. *
  51439. * @param name The material name
  51440. * @param scene The scene the material will be use in.
  51441. */
  51442. function PBRMaterial(name, scene) {
  51443. var _this = this;
  51444. _super.call(this, name, scene);
  51445. /**
  51446. * Intensity of the direct lights e.g. the four lights available in your scene.
  51447. * This impacts both the direct diffuse and specular highlights.
  51448. */
  51449. this.directIntensity = 1.0;
  51450. /**
  51451. * Intensity of the emissive part of the material.
  51452. * This helps controlling the emissive effect without modifying the emissive color.
  51453. */
  51454. this.emissiveIntensity = 1.0;
  51455. /**
  51456. * Intensity of the environment e.g. how much the environment will light the object
  51457. * either through harmonics for rough material or through the refelction for shiny ones.
  51458. */
  51459. this.environmentIntensity = 1.0;
  51460. /**
  51461. * This is a special control allowing the reduction of the specular highlights coming from the
  51462. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  51463. */
  51464. this.specularIntensity = 1.0;
  51465. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  51466. /**
  51467. * Debug Control allowing disabling the bump map on this material.
  51468. */
  51469. this.disableBumpMap = false;
  51470. /**
  51471. * Debug Control helping enforcing or dropping the darkness of shadows.
  51472. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  51473. */
  51474. this.overloadedShadowIntensity = 1.0;
  51475. /**
  51476. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  51477. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  51478. */
  51479. this.overloadedShadeIntensity = 1.0;
  51480. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  51481. /**
  51482. * The camera exposure used on this material.
  51483. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  51484. * This corresponds to a photographic exposure.
  51485. */
  51486. this.cameraExposure = 1.0;
  51487. /**
  51488. * The camera contrast used on this material.
  51489. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  51490. */
  51491. this.cameraContrast = 1.0;
  51492. /**
  51493. * Color Grading 2D Lookup Texture.
  51494. * This allows special effects like sepia, black and white to sixties rendering style.
  51495. */
  51496. this.cameraColorGradingTexture = null;
  51497. /**
  51498. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  51499. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  51500. * 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;
  51501. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  51502. */
  51503. this.cameraColorCurves = null;
  51504. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  51505. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  51506. /**
  51507. * Debug Control allowing to overload the ambient color.
  51508. * This as to be use with the overloadedAmbientIntensity parameter.
  51509. */
  51510. this.overloadedAmbient = BABYLON.Color3.White();
  51511. /**
  51512. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  51513. */
  51514. this.overloadedAmbientIntensity = 0.0;
  51515. /**
  51516. * Debug Control allowing to overload the albedo color.
  51517. * This as to be use with the overloadedAlbedoIntensity parameter.
  51518. */
  51519. this.overloadedAlbedo = BABYLON.Color3.White();
  51520. /**
  51521. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  51522. */
  51523. this.overloadedAlbedoIntensity = 0.0;
  51524. /**
  51525. * Debug Control allowing to overload the reflectivity color.
  51526. * This as to be use with the overloadedReflectivityIntensity parameter.
  51527. */
  51528. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  51529. /**
  51530. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  51531. */
  51532. this.overloadedReflectivityIntensity = 0.0;
  51533. /**
  51534. * Debug Control allowing to overload the emissive color.
  51535. * This as to be use with the overloadedEmissiveIntensity parameter.
  51536. */
  51537. this.overloadedEmissive = BABYLON.Color3.White();
  51538. /**
  51539. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  51540. */
  51541. this.overloadedEmissiveIntensity = 0.0;
  51542. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  51543. /**
  51544. * Debug Control allowing to overload the reflection color.
  51545. * This as to be use with the overloadedReflectionIntensity parameter.
  51546. */
  51547. this.overloadedReflection = BABYLON.Color3.White();
  51548. /**
  51549. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  51550. */
  51551. this.overloadedReflectionIntensity = 0.0;
  51552. /**
  51553. * Debug Control allowing to overload the microsurface.
  51554. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  51555. */
  51556. this.overloadedMicroSurface = 0.0;
  51557. /**
  51558. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  51559. */
  51560. this.overloadedMicroSurfaceIntensity = 0.0;
  51561. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  51562. /**
  51563. * AKA Occlusion Texture Intensity in other nomenclature.
  51564. */
  51565. this.ambientTextureStrength = 1.0;
  51566. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  51567. /**
  51568. * AKA Diffuse Color in other nomenclature.
  51569. */
  51570. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  51571. /**
  51572. * AKA Specular Color in other nomenclature.
  51573. */
  51574. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  51575. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  51576. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  51577. /**
  51578. * AKA Glossiness in other nomenclature.
  51579. */
  51580. this.microSurface = 0.9;
  51581. /**
  51582. * source material index of refraction (IOR)' / 'destination material IOR.
  51583. */
  51584. this.indexOfRefraction = 0.66;
  51585. /**
  51586. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  51587. */
  51588. this.invertRefractionY = false;
  51589. /**
  51590. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  51591. * Materials half opaque for instance using refraction could benefit from this control.
  51592. */
  51593. this.linkRefractionWithTransparency = false;
  51594. /**
  51595. * The emissive and albedo are linked to never be more than one (Energy conservation).
  51596. */
  51597. this.linkEmissiveWithAlbedo = false;
  51598. this.useLightmapAsShadowmap = false;
  51599. /**
  51600. * In this mode, the emissive informtaion will always be added to the lighting once.
  51601. * A light for instance can be thought as emissive.
  51602. */
  51603. this.useEmissiveAsIllumination = false;
  51604. /**
  51605. * Secifies that the alpha is coming form the albedo channel alpha channel.
  51606. */
  51607. this.useAlphaFromAlbedoTexture = false;
  51608. /**
  51609. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  51610. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  51611. */
  51612. this.useSpecularOverAlpha = true;
  51613. /**
  51614. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  51615. */
  51616. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  51617. /**
  51618. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  51619. * The material will try to infer what glossiness each pixel should be.
  51620. */
  51621. this.useAutoMicroSurfaceFromReflectivityMap = false;
  51622. /**
  51623. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  51624. * the creation of the material.
  51625. */
  51626. this.useScalarInLinearSpace = false;
  51627. /**
  51628. * BJS is using an harcoded light falloff based on a manually sets up range.
  51629. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  51630. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  51631. */
  51632. this.usePhysicalLightFalloff = true;
  51633. /**
  51634. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  51635. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  51636. */
  51637. this.useRadianceOverAlpha = true;
  51638. /**
  51639. * Allows using the bump map in parallax mode.
  51640. */
  51641. this.useParallax = false;
  51642. /**
  51643. * Allows using the bump map in parallax occlusion mode.
  51644. */
  51645. this.useParallaxOcclusion = false;
  51646. /**
  51647. * Controls the scale bias of the parallax mode.
  51648. */
  51649. this.parallaxScaleBias = 0.05;
  51650. /**
  51651. * If sets to true, disables all the lights affecting the material.
  51652. */
  51653. this.disableLighting = false;
  51654. /**
  51655. * Number of Simultaneous lights allowed on the material.
  51656. */
  51657. this.maxSimultaneousLights = 4;
  51658. /**
  51659. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  51660. */
  51661. this.invertNormalMapX = false;
  51662. /**
  51663. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  51664. */
  51665. this.invertNormalMapY = false;
  51666. this._renderTargets = new BABYLON.SmartArray(16);
  51667. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  51668. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  51669. this._tempColor = new BABYLON.Color3();
  51670. this._defines = new PBRMaterialDefines();
  51671. this._cachedDefines = new PBRMaterialDefines();
  51672. this._myScene = null;
  51673. this._myShadowGenerator = null;
  51674. this._cachedDefines.BonesPerMesh = -1;
  51675. this.getRenderTargetTextures = function () {
  51676. _this._renderTargets.reset();
  51677. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  51678. _this._renderTargets.push(_this.reflectionTexture);
  51679. }
  51680. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  51681. _this._renderTargets.push(_this.refractionTexture);
  51682. }
  51683. return _this._renderTargets;
  51684. };
  51685. }
  51686. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  51687. get: function () {
  51688. return this._useLogarithmicDepth;
  51689. },
  51690. set: function (value) {
  51691. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  51692. },
  51693. enumerable: true,
  51694. configurable: true
  51695. });
  51696. PBRMaterial.prototype.needAlphaBlending = function () {
  51697. if (this.linkRefractionWithTransparency) {
  51698. return false;
  51699. }
  51700. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  51701. };
  51702. PBRMaterial.prototype.needAlphaTesting = function () {
  51703. if (this.linkRefractionWithTransparency) {
  51704. return false;
  51705. }
  51706. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  51707. };
  51708. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  51709. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  51710. };
  51711. PBRMaterial.prototype.getAlphaTestTexture = function () {
  51712. return this.albedoTexture;
  51713. };
  51714. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51715. if (!mesh) {
  51716. return true;
  51717. }
  51718. if (this._defines.INSTANCES !== useInstances) {
  51719. return false;
  51720. }
  51721. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  51722. return true;
  51723. }
  51724. return false;
  51725. };
  51726. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  51727. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  51728. };
  51729. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  51730. if (!useScalarInLinear) {
  51731. color.toLinearSpaceToRef(ref);
  51732. }
  51733. else {
  51734. ref.r = color.r;
  51735. ref.g = color.g;
  51736. ref.b = color.b;
  51737. }
  51738. };
  51739. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  51740. var lightIndex = 0;
  51741. var depthValuesAlreadySet = false;
  51742. for (var index = 0; index < scene.lights.length; index++) {
  51743. var light = scene.lights[index];
  51744. if (!light.isEnabled()) {
  51745. continue;
  51746. }
  51747. if (!light.canAffectMesh(mesh)) {
  51748. continue;
  51749. }
  51750. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  51751. // GAMMA CORRECTION.
  51752. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  51753. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  51754. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  51755. if (defines["SPECULARTERM"]) {
  51756. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  51757. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  51758. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  51759. }
  51760. // Shadows
  51761. if (scene.shadowsEnabled) {
  51762. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  51763. }
  51764. lightIndex++;
  51765. if (lightIndex === maxSimultaneousLights)
  51766. break;
  51767. }
  51768. };
  51769. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  51770. if (this.checkReadyOnlyOnce) {
  51771. if (this._wasPreviouslyReady) {
  51772. return true;
  51773. }
  51774. }
  51775. var scene = this.getScene();
  51776. if (!this.checkReadyOnEveryCall) {
  51777. if (this._renderId === scene.getRenderId()) {
  51778. if (this._checkCache(scene, mesh, useInstances)) {
  51779. return true;
  51780. }
  51781. }
  51782. }
  51783. var engine = scene.getEngine();
  51784. var needNormals = false;
  51785. var needUVs = false;
  51786. this._defines.reset();
  51787. if (scene.texturesEnabled) {
  51788. if (scene.getEngine().getCaps().textureLOD) {
  51789. this._defines.LODBASEDMICROSFURACE = true;
  51790. }
  51791. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51792. if (!this.albedoTexture.isReady()) {
  51793. return false;
  51794. }
  51795. else {
  51796. needUVs = true;
  51797. this._defines.ALBEDO = true;
  51798. }
  51799. }
  51800. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51801. if (!this.ambientTexture.isReady()) {
  51802. return false;
  51803. }
  51804. else {
  51805. needUVs = true;
  51806. this._defines.AMBIENT = true;
  51807. }
  51808. }
  51809. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51810. if (!this.opacityTexture.isReady()) {
  51811. return false;
  51812. }
  51813. else {
  51814. needUVs = true;
  51815. this._defines.OPACITY = true;
  51816. if (this.opacityTexture.getAlphaFromRGB) {
  51817. this._defines.OPACITYRGB = true;
  51818. }
  51819. }
  51820. }
  51821. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51822. if (!this.reflectionTexture.isReady()) {
  51823. return false;
  51824. }
  51825. else {
  51826. needNormals = true;
  51827. this._defines.REFLECTION = true;
  51828. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  51829. this._defines.INVERTCUBICMAP = true;
  51830. }
  51831. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  51832. switch (this.reflectionTexture.coordinatesMode) {
  51833. case BABYLON.Texture.CUBIC_MODE:
  51834. case BABYLON.Texture.INVCUBIC_MODE:
  51835. this._defines.REFLECTIONMAP_CUBIC = true;
  51836. break;
  51837. case BABYLON.Texture.EXPLICIT_MODE:
  51838. this._defines.REFLECTIONMAP_EXPLICIT = true;
  51839. break;
  51840. case BABYLON.Texture.PLANAR_MODE:
  51841. this._defines.REFLECTIONMAP_PLANAR = true;
  51842. break;
  51843. case BABYLON.Texture.PROJECTION_MODE:
  51844. this._defines.REFLECTIONMAP_PROJECTION = true;
  51845. break;
  51846. case BABYLON.Texture.SKYBOX_MODE:
  51847. this._defines.REFLECTIONMAP_SKYBOX = true;
  51848. break;
  51849. case BABYLON.Texture.SPHERICAL_MODE:
  51850. this._defines.REFLECTIONMAP_SPHERICAL = true;
  51851. break;
  51852. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  51853. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  51854. break;
  51855. }
  51856. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  51857. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  51858. needNormals = true;
  51859. if (this.reflectionTexture.isPMREM) {
  51860. this._defines.USEPMREMREFLECTION = true;
  51861. }
  51862. }
  51863. }
  51864. }
  51865. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51866. if (!this.lightmapTexture.isReady()) {
  51867. return false;
  51868. }
  51869. else {
  51870. needUVs = true;
  51871. this._defines.LIGHTMAP = true;
  51872. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  51873. }
  51874. }
  51875. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51876. if (!this.emissiveTexture.isReady()) {
  51877. return false;
  51878. }
  51879. else {
  51880. needUVs = true;
  51881. this._defines.EMISSIVE = true;
  51882. }
  51883. }
  51884. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51885. if (!this.reflectivityTexture.isReady()) {
  51886. return false;
  51887. }
  51888. else {
  51889. needUVs = true;
  51890. this._defines.REFLECTIVITY = true;
  51891. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  51892. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  51893. }
  51894. }
  51895. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51896. if (!this.bumpTexture.isReady()) {
  51897. return false;
  51898. }
  51899. else {
  51900. needUVs = true;
  51901. this._defines.BUMP = true;
  51902. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51903. this._defines.PARALLAX = true;
  51904. if (this.useParallaxOcclusion) {
  51905. this._defines.PARALLAXOCCLUSION = true;
  51906. }
  51907. }
  51908. if (this.invertNormalMapX) {
  51909. this._defines.INVERTNORMALMAPX = true;
  51910. }
  51911. if (this.invertNormalMapY) {
  51912. this._defines.INVERTNORMALMAPY = true;
  51913. }
  51914. }
  51915. }
  51916. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51917. if (!this.refractionTexture.isReady()) {
  51918. return false;
  51919. }
  51920. else {
  51921. needUVs = true;
  51922. this._defines.REFRACTION = true;
  51923. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  51924. if (this.linkRefractionWithTransparency) {
  51925. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  51926. }
  51927. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  51928. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  51929. if (this.refractionTexture.isPMREM) {
  51930. this._defines.USEPMREMREFRACTION = true;
  51931. }
  51932. }
  51933. }
  51934. }
  51935. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  51936. if (!this.cameraColorGradingTexture.isReady()) {
  51937. return false;
  51938. }
  51939. else {
  51940. this._defines.CAMERACOLORGRADING = true;
  51941. }
  51942. }
  51943. }
  51944. // Effect
  51945. if (scene.clipPlane) {
  51946. this._defines.CLIPPLANE = true;
  51947. }
  51948. if (engine.getAlphaTesting()) {
  51949. this._defines.ALPHATEST = true;
  51950. }
  51951. if (this._shouldUseAlphaFromAlbedoTexture()) {
  51952. this._defines.ALPHAFROMALBEDO = true;
  51953. }
  51954. if (this.useEmissiveAsIllumination) {
  51955. this._defines.EMISSIVEASILLUMINATION = true;
  51956. }
  51957. if (this.linkEmissiveWithAlbedo) {
  51958. this._defines.LINKEMISSIVEWITHALBEDO = true;
  51959. }
  51960. if (this.useLogarithmicDepth) {
  51961. this._defines.LOGARITHMICDEPTH = true;
  51962. }
  51963. if (this.cameraContrast != 1) {
  51964. this._defines.CAMERACONTRAST = true;
  51965. }
  51966. if (this.cameraExposure != 1) {
  51967. this._defines.CAMERATONEMAP = true;
  51968. }
  51969. if (this.cameraColorCurves) {
  51970. this._defines.CAMERACOLORCURVES = true;
  51971. }
  51972. if (this.overloadedShadeIntensity != 1 ||
  51973. this.overloadedShadowIntensity != 1) {
  51974. this._defines.OVERLOADEDSHADOWVALUES = true;
  51975. }
  51976. if (this.overloadedMicroSurfaceIntensity > 0 ||
  51977. this.overloadedEmissiveIntensity > 0 ||
  51978. this.overloadedReflectivityIntensity > 0 ||
  51979. this.overloadedAlbedoIntensity > 0 ||
  51980. this.overloadedAmbientIntensity > 0 ||
  51981. this.overloadedReflectionIntensity > 0) {
  51982. this._defines.OVERLOADEDVALUES = true;
  51983. }
  51984. // Point size
  51985. if (this.pointsCloud || scene.forcePointsCloud) {
  51986. this._defines.POINTSIZE = true;
  51987. }
  51988. // Fog
  51989. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51990. this._defines.FOG = true;
  51991. }
  51992. if (scene.lightsEnabled && !this.disableLighting) {
  51993. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  51994. }
  51995. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51996. // Fresnel
  51997. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  51998. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51999. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52000. this._defines.OPACITYFRESNEL = true;
  52001. }
  52002. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52003. this._defines.EMISSIVEFRESNEL = true;
  52004. }
  52005. needNormals = true;
  52006. this._defines.FRESNEL = true;
  52007. }
  52008. }
  52009. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  52010. this._defines.SPECULAROVERALPHA = true;
  52011. }
  52012. if (this.usePhysicalLightFalloff) {
  52013. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  52014. }
  52015. if (this.useRadianceOverAlpha) {
  52016. this._defines.RADIANCEOVERALPHA = true;
  52017. }
  52018. // Attribs
  52019. if (mesh) {
  52020. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  52021. this._defines.NORMAL = true;
  52022. }
  52023. if (needUVs) {
  52024. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52025. this._defines.UV1 = true;
  52026. }
  52027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52028. this._defines.UV2 = true;
  52029. }
  52030. }
  52031. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52032. this._defines.VERTEXCOLOR = true;
  52033. if (mesh.hasVertexAlpha) {
  52034. this._defines.VERTEXALPHA = true;
  52035. }
  52036. }
  52037. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52038. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  52039. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  52040. }
  52041. // Instances
  52042. if (useInstances) {
  52043. this._defines.INSTANCES = true;
  52044. }
  52045. }
  52046. // Get correct effect
  52047. if (!this._defines.isEqual(this._cachedDefines)) {
  52048. this._defines.cloneTo(this._cachedDefines);
  52049. scene.resetCachedMaterial();
  52050. // Fallbacks
  52051. var fallbacks = new BABYLON.EffectFallbacks();
  52052. if (this._defines.REFLECTION) {
  52053. fallbacks.addFallback(0, "REFLECTION");
  52054. }
  52055. if (this._defines.REFRACTION) {
  52056. fallbacks.addFallback(0, "REFRACTION");
  52057. }
  52058. if (this._defines.REFLECTIVITY) {
  52059. fallbacks.addFallback(0, "REFLECTIVITY");
  52060. }
  52061. if (this._defines.BUMP) {
  52062. fallbacks.addFallback(0, "BUMP");
  52063. }
  52064. if (this._defines.PARALLAX) {
  52065. fallbacks.addFallback(1, "PARALLAX");
  52066. }
  52067. if (this._defines.PARALLAXOCCLUSION) {
  52068. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  52069. }
  52070. if (this._defines.SPECULAROVERALPHA) {
  52071. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  52072. }
  52073. if (this._defines.FOG) {
  52074. fallbacks.addFallback(1, "FOG");
  52075. }
  52076. if (this._defines.POINTSIZE) {
  52077. fallbacks.addFallback(0, "POINTSIZE");
  52078. }
  52079. if (this._defines.LOGARITHMICDEPTH) {
  52080. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  52081. }
  52082. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  52083. if (this._defines.SPECULARTERM) {
  52084. fallbacks.addFallback(0, "SPECULARTERM");
  52085. }
  52086. if (this._defines.OPACITYFRESNEL) {
  52087. fallbacks.addFallback(1, "OPACITYFRESNEL");
  52088. }
  52089. if (this._defines.EMISSIVEFRESNEL) {
  52090. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  52091. }
  52092. if (this._defines.FRESNEL) {
  52093. fallbacks.addFallback(3, "FRESNEL");
  52094. }
  52095. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  52096. fallbacks.addCPUSkinningFallback(0, mesh);
  52097. }
  52098. //Attributes
  52099. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52100. if (this._defines.NORMAL) {
  52101. attribs.push(BABYLON.VertexBuffer.NormalKind);
  52102. }
  52103. if (this._defines.UV1) {
  52104. attribs.push(BABYLON.VertexBuffer.UVKind);
  52105. }
  52106. if (this._defines.UV2) {
  52107. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52108. }
  52109. if (this._defines.VERTEXCOLOR) {
  52110. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52111. }
  52112. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  52113. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  52114. // Legacy browser patch
  52115. var join = this._defines.toString();
  52116. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  52117. "vFogInfos", "vFogColor", "pointSize",
  52118. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  52119. "mBones",
  52120. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  52121. "depthValues",
  52122. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  52123. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  52124. "logarithmicDepthConstant",
  52125. "vSphericalX", "vSphericalY", "vSphericalZ",
  52126. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  52127. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  52128. "vMicrosurfaceTextureLods",
  52129. "vCameraInfos"
  52130. ];
  52131. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  52132. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  52133. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  52134. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  52135. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  52136. }
  52137. if (!this._effect.isReady()) {
  52138. return false;
  52139. }
  52140. this._renderId = scene.getRenderId();
  52141. this._wasPreviouslyReady = true;
  52142. if (mesh) {
  52143. if (!mesh._materialDefines) {
  52144. mesh._materialDefines = new PBRMaterialDefines();
  52145. }
  52146. this._defines.cloneTo(mesh._materialDefines);
  52147. }
  52148. return true;
  52149. };
  52150. PBRMaterial.prototype.unbind = function () {
  52151. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  52152. this._effect.setTexture("reflection2DSampler", null);
  52153. }
  52154. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  52155. this._effect.setTexture("refraction2DSampler", null);
  52156. }
  52157. _super.prototype.unbind.call(this);
  52158. };
  52159. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52160. this._effect.setMatrix("world", world);
  52161. };
  52162. PBRMaterial.prototype.bind = function (world, mesh) {
  52163. this._myScene = this.getScene();
  52164. // Matrices
  52165. this.bindOnlyWorldMatrix(world);
  52166. // Bones
  52167. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52168. if (this._myScene.getCachedMaterial() !== this) {
  52169. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  52170. if (BABYLON.StandardMaterial.FresnelEnabled) {
  52171. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52172. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  52173. }
  52174. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52175. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  52176. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  52177. }
  52178. }
  52179. // Textures
  52180. if (this._myScene.texturesEnabled) {
  52181. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52182. this._effect.setTexture("albedoSampler", this.albedoTexture);
  52183. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  52184. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  52185. }
  52186. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  52187. this._effect.setTexture("ambientSampler", this.ambientTexture);
  52188. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  52189. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  52190. }
  52191. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  52192. this._effect.setTexture("opacitySampler", this.opacityTexture);
  52193. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  52194. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  52195. }
  52196. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  52197. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  52198. if (this.reflectionTexture.isCube) {
  52199. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  52200. }
  52201. else {
  52202. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  52203. }
  52204. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  52205. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  52206. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  52207. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  52208. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  52209. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  52210. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  52211. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  52212. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  52213. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  52214. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  52215. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  52216. }
  52217. }
  52218. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  52219. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  52220. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  52221. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  52222. }
  52223. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  52224. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  52225. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  52226. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  52227. }
  52228. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  52229. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  52230. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  52231. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  52232. }
  52233. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  52234. this._effect.setTexture("bumpSampler", this.bumpTexture);
  52235. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  52236. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  52237. }
  52238. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  52239. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  52240. var depth = 1.0;
  52241. if (this.refractionTexture.isCube) {
  52242. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  52243. }
  52244. else {
  52245. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  52246. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  52247. if (this.refractionTexture.depth) {
  52248. depth = this.refractionTexture.depth;
  52249. }
  52250. }
  52251. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  52252. }
  52253. if ((this.reflectionTexture || this.refractionTexture)) {
  52254. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  52255. }
  52256. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52257. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  52258. }
  52259. }
  52260. // Clip plane
  52261. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  52262. // Point size
  52263. if (this.pointsCloud) {
  52264. this._effect.setFloat("pointSize", this.pointSize);
  52265. }
  52266. // Colors
  52267. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  52268. // GAMMA CORRECTION.
  52269. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  52270. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  52271. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  52272. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  52273. // GAMMA CORRECTION.
  52274. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  52275. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  52276. // GAMMA CORRECTION.
  52277. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  52278. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  52279. }
  52280. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  52281. // GAMMA CORRECTION.
  52282. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  52283. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  52284. // Lights
  52285. if (this._myScene.lightsEnabled && !this.disableLighting) {
  52286. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  52287. }
  52288. // View
  52289. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  52290. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  52291. }
  52292. // Fog
  52293. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  52294. this._lightingInfos.x = this.directIntensity;
  52295. this._lightingInfos.y = this.emissiveIntensity;
  52296. this._lightingInfos.z = this.environmentIntensity;
  52297. this._lightingInfos.w = this.specularIntensity;
  52298. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  52299. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  52300. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  52301. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  52302. this._cameraInfos.x = this.cameraExposure;
  52303. this._cameraInfos.y = this.cameraContrast;
  52304. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  52305. if (this.cameraColorCurves) {
  52306. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  52307. }
  52308. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  52309. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  52310. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  52311. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  52312. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  52313. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  52314. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  52315. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  52316. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  52317. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  52318. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  52319. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  52320. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  52321. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  52322. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  52323. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  52324. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  52325. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  52326. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  52327. // Log. depth
  52328. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  52329. }
  52330. _super.prototype.bind.call(this, world, mesh);
  52331. this._myScene = null;
  52332. };
  52333. PBRMaterial.prototype.getAnimatables = function () {
  52334. var results = [];
  52335. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  52336. results.push(this.albedoTexture);
  52337. }
  52338. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  52339. results.push(this.ambientTexture);
  52340. }
  52341. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  52342. results.push(this.opacityTexture);
  52343. }
  52344. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  52345. results.push(this.reflectionTexture);
  52346. }
  52347. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  52348. results.push(this.emissiveTexture);
  52349. }
  52350. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  52351. results.push(this.reflectivityTexture);
  52352. }
  52353. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  52354. results.push(this.bumpTexture);
  52355. }
  52356. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  52357. results.push(this.lightmapTexture);
  52358. }
  52359. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  52360. results.push(this.refractionTexture);
  52361. }
  52362. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  52363. results.push(this.cameraColorGradingTexture);
  52364. }
  52365. return results;
  52366. };
  52367. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52368. if (forceDisposeTextures) {
  52369. if (this.albedoTexture) {
  52370. this.albedoTexture.dispose();
  52371. }
  52372. if (this.ambientTexture) {
  52373. this.ambientTexture.dispose();
  52374. }
  52375. if (this.opacityTexture) {
  52376. this.opacityTexture.dispose();
  52377. }
  52378. if (this.reflectionTexture) {
  52379. this.reflectionTexture.dispose();
  52380. }
  52381. if (this.emissiveTexture) {
  52382. this.emissiveTexture.dispose();
  52383. }
  52384. if (this.reflectivityTexture) {
  52385. this.reflectivityTexture.dispose();
  52386. }
  52387. if (this.bumpTexture) {
  52388. this.bumpTexture.dispose();
  52389. }
  52390. if (this.lightmapTexture) {
  52391. this.lightmapTexture.dispose();
  52392. }
  52393. if (this.refractionTexture) {
  52394. this.refractionTexture.dispose();
  52395. }
  52396. if (this.cameraColorGradingTexture) {
  52397. this.cameraColorGradingTexture.dispose();
  52398. }
  52399. }
  52400. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52401. };
  52402. PBRMaterial.prototype.clone = function (name) {
  52403. var _this = this;
  52404. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  52405. };
  52406. PBRMaterial.prototype.serialize = function () {
  52407. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52408. serializationObject.customType = "BABYLON.PBRMaterial";
  52409. return serializationObject;
  52410. };
  52411. // Statics
  52412. PBRMaterial.Parse = function (source, scene, rootUrl) {
  52413. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  52414. };
  52415. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  52416. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  52417. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  52418. PBRMaterial._scaledReflection = new BABYLON.Color3();
  52419. __decorate([
  52420. BABYLON.serialize()
  52421. ], PBRMaterial.prototype, "directIntensity", void 0);
  52422. __decorate([
  52423. BABYLON.serialize()
  52424. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  52425. __decorate([
  52426. BABYLON.serialize()
  52427. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  52428. __decorate([
  52429. BABYLON.serialize()
  52430. ], PBRMaterial.prototype, "specularIntensity", void 0);
  52431. __decorate([
  52432. BABYLON.serialize()
  52433. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  52434. __decorate([
  52435. BABYLON.serialize()
  52436. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  52437. __decorate([
  52438. BABYLON.serialize()
  52439. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  52440. __decorate([
  52441. BABYLON.serialize()
  52442. ], PBRMaterial.prototype, "cameraExposure", void 0);
  52443. __decorate([
  52444. BABYLON.serialize()
  52445. ], PBRMaterial.prototype, "cameraContrast", void 0);
  52446. __decorate([
  52447. BABYLON.serializeAsTexture()
  52448. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  52449. __decorate([
  52450. BABYLON.serializeAsColorCurves()
  52451. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  52452. __decorate([
  52453. BABYLON.serializeAsColor3()
  52454. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  52455. __decorate([
  52456. BABYLON.serialize()
  52457. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  52458. __decorate([
  52459. BABYLON.serializeAsColor3()
  52460. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  52461. __decorate([
  52462. BABYLON.serialize()
  52463. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  52464. __decorate([
  52465. BABYLON.serializeAsColor3()
  52466. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  52467. __decorate([
  52468. BABYLON.serialize()
  52469. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  52470. __decorate([
  52471. BABYLON.serializeAsColor3()
  52472. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  52473. __decorate([
  52474. BABYLON.serialize()
  52475. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  52476. __decorate([
  52477. BABYLON.serializeAsColor3()
  52478. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  52479. __decorate([
  52480. BABYLON.serialize()
  52481. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  52482. __decorate([
  52483. BABYLON.serialize()
  52484. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  52485. __decorate([
  52486. BABYLON.serialize()
  52487. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  52488. __decorate([
  52489. BABYLON.serializeAsTexture()
  52490. ], PBRMaterial.prototype, "albedoTexture", void 0);
  52491. __decorate([
  52492. BABYLON.serializeAsTexture()
  52493. ], PBRMaterial.prototype, "ambientTexture", void 0);
  52494. __decorate([
  52495. BABYLON.serialize()
  52496. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  52497. __decorate([
  52498. BABYLON.serializeAsTexture()
  52499. ], PBRMaterial.prototype, "opacityTexture", void 0);
  52500. __decorate([
  52501. BABYLON.serializeAsTexture()
  52502. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  52503. __decorate([
  52504. BABYLON.serializeAsTexture()
  52505. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  52506. __decorate([
  52507. BABYLON.serializeAsTexture()
  52508. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  52509. __decorate([
  52510. BABYLON.serializeAsTexture()
  52511. ], PBRMaterial.prototype, "bumpTexture", void 0);
  52512. __decorate([
  52513. BABYLON.serializeAsTexture()
  52514. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  52515. __decorate([
  52516. BABYLON.serializeAsTexture()
  52517. ], PBRMaterial.prototype, "refractionTexture", void 0);
  52518. __decorate([
  52519. BABYLON.serializeAsColor3("ambient")
  52520. ], PBRMaterial.prototype, "ambientColor", void 0);
  52521. __decorate([
  52522. BABYLON.serializeAsColor3("albedo")
  52523. ], PBRMaterial.prototype, "albedoColor", void 0);
  52524. __decorate([
  52525. BABYLON.serializeAsColor3("reflectivity")
  52526. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  52527. __decorate([
  52528. BABYLON.serializeAsColor3("reflection")
  52529. ], PBRMaterial.prototype, "reflectionColor", void 0);
  52530. __decorate([
  52531. BABYLON.serializeAsColor3("emissive")
  52532. ], PBRMaterial.prototype, "emissiveColor", void 0);
  52533. __decorate([
  52534. BABYLON.serialize()
  52535. ], PBRMaterial.prototype, "microSurface", void 0);
  52536. __decorate([
  52537. BABYLON.serialize()
  52538. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  52539. __decorate([
  52540. BABYLON.serialize()
  52541. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  52542. __decorate([
  52543. BABYLON.serializeAsFresnelParameters()
  52544. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  52545. __decorate([
  52546. BABYLON.serializeAsFresnelParameters()
  52547. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  52548. __decorate([
  52549. BABYLON.serialize()
  52550. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  52551. __decorate([
  52552. BABYLON.serialize()
  52553. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  52554. __decorate([
  52555. BABYLON.serialize()
  52556. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  52557. __decorate([
  52558. BABYLON.serialize()
  52559. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  52560. __decorate([
  52561. BABYLON.serialize()
  52562. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  52563. __decorate([
  52564. BABYLON.serialize()
  52565. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  52566. __decorate([
  52567. BABYLON.serialize()
  52568. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  52569. __decorate([
  52570. BABYLON.serialize()
  52571. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  52572. __decorate([
  52573. BABYLON.serialize()
  52574. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  52575. __decorate([
  52576. BABYLON.serialize()
  52577. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  52578. __decorate([
  52579. BABYLON.serialize()
  52580. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  52581. __decorate([
  52582. BABYLON.serialize()
  52583. ], PBRMaterial.prototype, "useParallax", void 0);
  52584. __decorate([
  52585. BABYLON.serialize()
  52586. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  52587. __decorate([
  52588. BABYLON.serialize()
  52589. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  52590. __decorate([
  52591. BABYLON.serialize()
  52592. ], PBRMaterial.prototype, "disableLighting", void 0);
  52593. __decorate([
  52594. BABYLON.serialize()
  52595. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  52596. __decorate([
  52597. BABYLON.serialize()
  52598. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  52599. __decorate([
  52600. BABYLON.serialize()
  52601. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  52602. __decorate([
  52603. BABYLON.serialize()
  52604. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  52605. return PBRMaterial;
  52606. }(BABYLON.Material));
  52607. BABYLON.PBRMaterial = PBRMaterial;
  52608. })(BABYLON || (BABYLON = {}));
  52609. var BABYLON;
  52610. (function (BABYLON) {
  52611. var DebugLayer = (function () {
  52612. function DebugLayer(scene) {
  52613. var _this = this;
  52614. this._transformationMatrix = BABYLON.Matrix.Identity();
  52615. this._enabled = false;
  52616. this._labelsEnabled = false;
  52617. this._displayStatistics = true;
  52618. this._displayTree = false;
  52619. this._displayLogs = false;
  52620. this._skeletonViewers = new Array();
  52621. this._identityMatrix = BABYLON.Matrix.Identity();
  52622. this.axisRatio = 0.02;
  52623. this.accentColor = "orange";
  52624. this._scene = scene;
  52625. this._syncPositions = function () {
  52626. var engine = _this._scene.getEngine();
  52627. var canvasRect = engine.getRenderingCanvasClientRect();
  52628. if (_this._showUI) {
  52629. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  52630. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  52631. _this._statsDiv.style.width = "400px";
  52632. _this._statsDiv.style.height = "auto";
  52633. _this._statsSubsetDiv.style.maxHeight = "240px";
  52634. _this._optionsDiv.style.left = "0px";
  52635. _this._optionsDiv.style.top = "10px";
  52636. _this._optionsDiv.style.width = "200px";
  52637. _this._optionsDiv.style.height = "auto";
  52638. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  52639. _this._logDiv.style.left = "0px";
  52640. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  52641. _this._logDiv.style.width = "600px";
  52642. _this._logDiv.style.height = "160px";
  52643. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  52644. _this._treeDiv.style.top = "10px";
  52645. _this._treeDiv.style.width = "300px";
  52646. _this._treeDiv.style.height = "auto";
  52647. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  52648. }
  52649. _this._globalDiv.style.left = canvasRect.left + "px";
  52650. _this._globalDiv.style.top = canvasRect.top + "px";
  52651. _this._drawingCanvas.style.left = "0px";
  52652. _this._drawingCanvas.style.top = "0px";
  52653. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  52654. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  52655. var devicePixelRatio = window.devicePixelRatio || 1;
  52656. var context = _this._drawingContext;
  52657. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  52658. context.mozBackingStorePixelRatio ||
  52659. context.msBackingStorePixelRatio ||
  52660. context.oBackingStorePixelRatio ||
  52661. context.backingStorePixelRatio || 1;
  52662. _this._ratio = devicePixelRatio / backingStoreRatio;
  52663. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  52664. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  52665. };
  52666. this._onCanvasClick = function (evt) {
  52667. _this._clickPosition = {
  52668. x: evt.clientX * _this._ratio,
  52669. y: evt.clientY * _this._ratio
  52670. };
  52671. };
  52672. this._syncUI = function () {
  52673. if (_this._showUI) {
  52674. if (_this._displayStatistics) {
  52675. _this._displayStats();
  52676. _this._statsDiv.style.display = "";
  52677. }
  52678. else {
  52679. _this._statsDiv.style.display = "none";
  52680. }
  52681. if (_this._displayLogs) {
  52682. _this._logDiv.style.display = "";
  52683. }
  52684. else {
  52685. _this._logDiv.style.display = "none";
  52686. }
  52687. if (_this._displayTree) {
  52688. _this._treeDiv.style.display = "";
  52689. if (_this._needToRefreshMeshesTree) {
  52690. _this._needToRefreshMeshesTree = false;
  52691. _this._refreshMeshesTreeContent();
  52692. }
  52693. }
  52694. else {
  52695. _this._treeDiv.style.display = "none";
  52696. }
  52697. }
  52698. };
  52699. this._syncData = function () {
  52700. if (_this._labelsEnabled || !_this._showUI) {
  52701. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  52702. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  52703. var engine = _this._scene.getEngine();
  52704. var viewport = _this._camera.viewport;
  52705. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52706. // Meshes
  52707. var meshes = _this._camera.getActiveMeshes();
  52708. var index;
  52709. var projectedPosition;
  52710. for (index = 0; index < meshes.length; index++) {
  52711. var mesh = meshes.data[index];
  52712. var position = mesh.getBoundingInfo().boundingSphere.center;
  52713. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52714. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  52715. _this._renderAxis(projectedPosition, mesh, globalViewport);
  52716. }
  52717. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  52718. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  52719. }
  52720. }
  52721. // Cameras
  52722. var cameras = _this._scene.cameras;
  52723. for (index = 0; index < cameras.length; index++) {
  52724. var camera = cameras[index];
  52725. if (camera === _this._camera) {
  52726. continue;
  52727. }
  52728. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52729. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  52730. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  52731. _this._camera.detachControl(engine.getRenderingCanvas());
  52732. _this._camera = camera;
  52733. _this._camera.attachControl(engine.getRenderingCanvas());
  52734. }, function () { return "purple"; });
  52735. }
  52736. }
  52737. // Lights
  52738. var lights = _this._scene.lights;
  52739. for (index = 0; index < lights.length; index++) {
  52740. var light = lights[index];
  52741. if (light.position) {
  52742. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  52743. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  52744. _this._renderLabel(light.name, projectedPosition, -20, function () {
  52745. light.setEnabled(!light.isEnabled());
  52746. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  52747. }
  52748. }
  52749. }
  52750. }
  52751. _this._clickPosition = undefined;
  52752. };
  52753. }
  52754. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  52755. while (this._treeSubsetDiv.hasChildNodes()) {
  52756. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  52757. }
  52758. // Add meshes
  52759. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  52760. sortedArray.sort(function (a, b) {
  52761. if (a.name === b.name) {
  52762. return 0;
  52763. }
  52764. return (a.name > b.name) ? 1 : -1;
  52765. });
  52766. for (var index = 0; index < sortedArray.length; index++) {
  52767. var mesh = sortedArray[index];
  52768. if (!mesh.isEnabled()) {
  52769. continue;
  52770. }
  52771. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  52772. m.isVisible = element.checked;
  52773. }, mesh);
  52774. }
  52775. };
  52776. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  52777. this._drawingContext.beginPath();
  52778. this._drawingContext.moveTo(zero.x, zero.y);
  52779. this._drawingContext.lineTo(unit.x, unit.y);
  52780. this._drawingContext.strokeStyle = color;
  52781. this._drawingContext.lineWidth = 4;
  52782. this._drawingContext.stroke();
  52783. this._drawingContext.font = "normal 14px Segoe UI";
  52784. this._drawingContext.fillStyle = color;
  52785. this._drawingContext.fillText(label, unitText.x, unitText.y);
  52786. };
  52787. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  52788. var position = mesh.getBoundingInfo().boundingSphere.center;
  52789. var worldMatrix = mesh.getWorldMatrix();
  52790. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  52791. var unit = (unprojectedVector.subtract(position)).length();
  52792. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52793. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52794. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  52795. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52796. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52797. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  52798. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  52799. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  52800. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  52801. };
  52802. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  52803. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  52804. this._drawingContext.font = "normal 12px Segoe UI";
  52805. var textMetrics = this._drawingContext.measureText(text);
  52806. var centerX = projectedPosition.x - textMetrics.width / 2;
  52807. var centerY = projectedPosition.y;
  52808. var clientRect = this._drawingCanvas.getBoundingClientRect();
  52809. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  52810. onClick();
  52811. }
  52812. this._drawingContext.beginPath();
  52813. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  52814. this._drawingContext.fillStyle = getFillStyle();
  52815. this._drawingContext.globalAlpha = 0.5;
  52816. this._drawingContext.fill();
  52817. this._drawingContext.globalAlpha = 1.0;
  52818. this._drawingContext.strokeStyle = '#FFFFFF';
  52819. this._drawingContext.lineWidth = 1;
  52820. this._drawingContext.stroke();
  52821. this._drawingContext.fillStyle = "#FFFFFF";
  52822. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  52823. this._drawingContext.beginPath();
  52824. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  52825. this._drawingContext.fill();
  52826. }
  52827. };
  52828. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  52829. if (!this._clickPosition) {
  52830. return false;
  52831. }
  52832. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  52833. return false;
  52834. }
  52835. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  52836. return false;
  52837. }
  52838. return true;
  52839. };
  52840. DebugLayer.prototype.isVisible = function () {
  52841. return this._enabled;
  52842. };
  52843. DebugLayer.prototype.hide = function () {
  52844. if (!this._enabled) {
  52845. return;
  52846. }
  52847. this._enabled = false;
  52848. var engine = this._scene.getEngine();
  52849. this._scene.unregisterBeforeRender(this._syncData);
  52850. this._scene.unregisterAfterRender(this._syncUI);
  52851. this._rootElement.removeChild(this._globalDiv);
  52852. this._scene.forceShowBoundingBoxes = false;
  52853. this._scene.forceWireframe = false;
  52854. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  52855. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  52856. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  52857. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  52858. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  52859. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  52860. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  52861. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  52862. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  52863. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  52864. this._scene.shadowsEnabled = true;
  52865. this._scene.particlesEnabled = true;
  52866. this._scene.postProcessesEnabled = true;
  52867. this._scene.collisionsEnabled = true;
  52868. this._scene.lightsEnabled = true;
  52869. this._scene.texturesEnabled = true;
  52870. this._scene.lensFlaresEnabled = true;
  52871. this._scene.proceduralTexturesEnabled = true;
  52872. this._scene.renderTargetsEnabled = true;
  52873. this._scene.probesEnabled = true;
  52874. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  52875. this._clearSkeletonViewers();
  52876. };
  52877. DebugLayer.prototype._clearSkeletonViewers = function () {
  52878. for (var index = 0; index < this._skeletonViewers.length; index++) {
  52879. this._skeletonViewers[index].dispose();
  52880. }
  52881. this._skeletonViewers = [];
  52882. };
  52883. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  52884. if (showUI === void 0) { showUI = true; }
  52885. if (camera === void 0) { camera = null; }
  52886. if (rootElement === void 0) { rootElement = null; }
  52887. if (this._enabled) {
  52888. return;
  52889. }
  52890. this._enabled = true;
  52891. if (camera) {
  52892. this._camera = camera;
  52893. }
  52894. else {
  52895. this._camera = this._scene.activeCamera;
  52896. }
  52897. this._showUI = showUI;
  52898. var engine = this._scene.getEngine();
  52899. this._globalDiv = document.createElement("div");
  52900. this._rootElement = rootElement || document.body;
  52901. this._rootElement.appendChild(this._globalDiv);
  52902. this._generateDOMelements();
  52903. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  52904. this._syncPositions();
  52905. this._scene.registerBeforeRender(this._syncData);
  52906. this._scene.registerAfterRender(this._syncUI);
  52907. };
  52908. DebugLayer.prototype._clearLabels = function () {
  52909. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  52910. for (var index = 0; index < this._scene.meshes.length; index++) {
  52911. var mesh = this._scene.meshes[index];
  52912. mesh.renderOverlay = false;
  52913. }
  52914. };
  52915. DebugLayer.prototype._generateheader = function (root, text) {
  52916. var header = document.createElement("div");
  52917. header.innerHTML = text + "&nbsp;";
  52918. header.style.textAlign = "right";
  52919. header.style.width = "100%";
  52920. header.style.color = "white";
  52921. header.style.backgroundColor = "Black";
  52922. header.style.padding = "5px 5px 4px 0px";
  52923. header.style.marginLeft = "-5px";
  52924. header.style.fontWeight = "bold";
  52925. root.appendChild(header);
  52926. };
  52927. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  52928. var label = document.createElement("label");
  52929. label.style.display = "inline";
  52930. label.innerHTML = title;
  52931. label.style.color = color;
  52932. root.appendChild(label);
  52933. root.appendChild(document.createElement("br"));
  52934. };
  52935. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  52936. if (tag === void 0) { tag = null; }
  52937. var label = document.createElement("label");
  52938. label.style.display = "inline";
  52939. var boundingBoxesCheckbox = document.createElement("input");
  52940. boundingBoxesCheckbox.type = "checkbox";
  52941. boundingBoxesCheckbox.checked = initialState;
  52942. boundingBoxesCheckbox.style.display = "inline";
  52943. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  52944. boundingBoxesCheckbox.style.verticalAlign = "sub";
  52945. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  52946. task(evt.target, tag);
  52947. });
  52948. label.appendChild(boundingBoxesCheckbox);
  52949. var container = document.createElement("span");
  52950. var leftPart = document.createElement("span");
  52951. var rightPart = document.createElement("span");
  52952. rightPart.style.cssFloat = "right";
  52953. leftPart.innerHTML = leftTitle;
  52954. rightPart.innerHTML = rightTitle;
  52955. rightPart.style.fontSize = "12px";
  52956. rightPart.style.maxWidth = "200px";
  52957. container.appendChild(leftPart);
  52958. container.appendChild(rightPart);
  52959. label.appendChild(container);
  52960. root.appendChild(label);
  52961. root.appendChild(document.createElement("br"));
  52962. };
  52963. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  52964. if (tag === void 0) { tag = null; }
  52965. var label = document.createElement("label");
  52966. label.style.display = "inline";
  52967. var checkBox = document.createElement("input");
  52968. checkBox.type = "checkbox";
  52969. checkBox.checked = initialState;
  52970. checkBox.style.display = "inline";
  52971. checkBox.style.margin = "0px 5px 0px 0px";
  52972. checkBox.style.verticalAlign = "sub";
  52973. checkBox.addEventListener("change", function (evt) {
  52974. task(evt.target, tag);
  52975. });
  52976. label.appendChild(checkBox);
  52977. label.appendChild(document.createTextNode(title));
  52978. root.appendChild(label);
  52979. root.appendChild(document.createElement("br"));
  52980. };
  52981. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  52982. if (tag === void 0) { tag = null; }
  52983. var button = document.createElement("button");
  52984. button.innerHTML = title;
  52985. button.style.height = "24px";
  52986. button.style.width = "150px";
  52987. button.style.marginBottom = "5px";
  52988. button.style.color = "#444444";
  52989. button.style.border = "1px solid white";
  52990. button.className = "debugLayerButton";
  52991. button.addEventListener("click", function (evt) {
  52992. task(evt.target, tag);
  52993. });
  52994. root.appendChild(button);
  52995. root.appendChild(document.createElement("br"));
  52996. };
  52997. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  52998. if (tag === void 0) { tag = null; }
  52999. var label = document.createElement("label");
  53000. label.style.display = "inline";
  53001. var boundingBoxesRadio = document.createElement("input");
  53002. boundingBoxesRadio.type = "radio";
  53003. boundingBoxesRadio.name = name;
  53004. boundingBoxesRadio.checked = initialState;
  53005. boundingBoxesRadio.style.display = "inline";
  53006. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  53007. boundingBoxesRadio.style.verticalAlign = "sub";
  53008. boundingBoxesRadio.addEventListener("change", function (evt) {
  53009. task(evt.target, tag);
  53010. });
  53011. label.appendChild(boundingBoxesRadio);
  53012. label.appendChild(document.createTextNode(title));
  53013. root.appendChild(label);
  53014. root.appendChild(document.createElement("br"));
  53015. };
  53016. DebugLayer.prototype._generateDOMelements = function () {
  53017. var _this = this;
  53018. this._globalDiv.id = "DebugLayer";
  53019. this._globalDiv.style.position = "absolute";
  53020. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  53021. this._globalDiv.style.fontSize = "14px";
  53022. this._globalDiv.style.color = "white";
  53023. // Drawing canvas
  53024. this._drawingCanvas = document.createElement("canvas");
  53025. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  53026. this._drawingCanvas.style.position = "absolute";
  53027. this._drawingCanvas.style.pointerEvents = "none";
  53028. this._drawingCanvas.style.backgroundColor = "transparent";
  53029. this._drawingContext = this._drawingCanvas.getContext("2d");
  53030. this._globalDiv.appendChild(this._drawingCanvas);
  53031. if (this._showUI) {
  53032. var background = "rgba(128, 128, 128, 0.4)";
  53033. var border = "rgb(180, 180, 180) solid 1px";
  53034. // Stats
  53035. this._statsDiv = document.createElement("div");
  53036. this._statsDiv.id = "DebugLayerStats";
  53037. this._statsDiv.style.border = border;
  53038. this._statsDiv.style.position = "absolute";
  53039. this._statsDiv.style.background = background;
  53040. this._statsDiv.style.padding = "0px 0px 0px 5px";
  53041. this._generateheader(this._statsDiv, "STATISTICS");
  53042. this._statsSubsetDiv = document.createElement("div");
  53043. this._statsSubsetDiv.style.paddingTop = "5px";
  53044. this._statsSubsetDiv.style.paddingBottom = "5px";
  53045. this._statsSubsetDiv.style.overflowY = "auto";
  53046. this._statsDiv.appendChild(this._statsSubsetDiv);
  53047. // Tree
  53048. this._treeDiv = document.createElement("div");
  53049. this._treeDiv.id = "DebugLayerTree";
  53050. this._treeDiv.style.border = border;
  53051. this._treeDiv.style.position = "absolute";
  53052. this._treeDiv.style.background = background;
  53053. this._treeDiv.style.padding = "0px 0px 0px 5px";
  53054. this._treeDiv.style.display = "none";
  53055. this._generateheader(this._treeDiv, "MESHES TREE");
  53056. this._treeSubsetDiv = document.createElement("div");
  53057. this._treeSubsetDiv.style.paddingTop = "5px";
  53058. this._treeSubsetDiv.style.paddingRight = "5px";
  53059. this._treeSubsetDiv.style.overflowY = "auto";
  53060. this._treeSubsetDiv.style.maxHeight = "300px";
  53061. this._treeDiv.appendChild(this._treeSubsetDiv);
  53062. this._needToRefreshMeshesTree = true;
  53063. // Logs
  53064. this._logDiv = document.createElement("div");
  53065. this._logDiv.style.border = border;
  53066. this._logDiv.id = "DebugLayerLogs";
  53067. this._logDiv.style.position = "absolute";
  53068. this._logDiv.style.background = background;
  53069. this._logDiv.style.padding = "0px 0px 0px 5px";
  53070. this._logDiv.style.display = "none";
  53071. this._generateheader(this._logDiv, "LOGS");
  53072. this._logSubsetDiv = document.createElement("div");
  53073. this._logSubsetDiv.style.height = "127px";
  53074. this._logSubsetDiv.style.paddingTop = "5px";
  53075. this._logSubsetDiv.style.overflowY = "auto";
  53076. this._logSubsetDiv.style.fontSize = "12px";
  53077. this._logSubsetDiv.style.fontFamily = "consolas";
  53078. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  53079. this._logDiv.appendChild(this._logSubsetDiv);
  53080. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  53081. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  53082. };
  53083. // Options
  53084. this._optionsDiv = document.createElement("div");
  53085. this._optionsDiv.id = "DebugLayerOptions";
  53086. this._optionsDiv.style.border = border;
  53087. this._optionsDiv.style.position = "absolute";
  53088. this._optionsDiv.style.background = background;
  53089. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  53090. this._optionsDiv.style.overflowY = "auto";
  53091. this._generateheader(this._optionsDiv, "OPTIONS");
  53092. this._optionsSubsetDiv = document.createElement("div");
  53093. this._optionsSubsetDiv.style.paddingTop = "5px";
  53094. this._optionsSubsetDiv.style.paddingBottom = "5px";
  53095. this._optionsSubsetDiv.style.overflowY = "auto";
  53096. this._optionsSubsetDiv.style.maxHeight = "200px";
  53097. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  53098. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  53099. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  53100. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  53101. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  53102. _this._displayTree = element.checked;
  53103. _this._needToRefreshMeshesTree = true;
  53104. });
  53105. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53106. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  53107. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  53108. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  53109. _this._labelsEnabled = element.checked;
  53110. if (!_this._labelsEnabled) {
  53111. _this._clearLabels();
  53112. }
  53113. });
  53114. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  53115. if (element.checked) {
  53116. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  53117. }
  53118. else {
  53119. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  53120. }
  53121. });
  53122. ;
  53123. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53124. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  53125. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  53126. if (element.checked) {
  53127. _this._scene.forceWireframe = false;
  53128. _this._scene.forcePointsCloud = false;
  53129. }
  53130. });
  53131. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  53132. if (element.checked) {
  53133. _this._scene.forceWireframe = true;
  53134. _this._scene.forcePointsCloud = false;
  53135. }
  53136. });
  53137. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  53138. if (element.checked) {
  53139. _this._scene.forceWireframe = false;
  53140. _this._scene.forcePointsCloud = true;
  53141. }
  53142. });
  53143. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53144. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  53145. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  53146. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  53147. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  53148. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  53149. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  53150. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  53151. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  53152. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  53153. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  53154. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  53155. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  53156. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53157. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  53158. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  53159. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  53160. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  53161. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  53162. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  53163. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  53164. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  53165. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  53166. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  53167. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  53168. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  53169. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  53170. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  53171. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  53172. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  53173. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53174. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  53175. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  53176. if (element.checked) {
  53177. _this._scene.headphone = true;
  53178. }
  53179. });
  53180. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  53181. if (element.checked) {
  53182. _this._scene.headphone = false;
  53183. }
  53184. });
  53185. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  53186. _this._scene.audioEnabled = !element.checked;
  53187. });
  53188. }
  53189. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53190. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  53191. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  53192. if (!element.checked) {
  53193. _this._clearSkeletonViewers();
  53194. return;
  53195. }
  53196. for (var index = 0; index < _this._scene.meshes.length; index++) {
  53197. var mesh = _this._scene.meshes[index];
  53198. if (mesh.skeleton) {
  53199. var found = false;
  53200. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  53201. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  53202. found = true;
  53203. break;
  53204. }
  53205. }
  53206. if (found) {
  53207. continue;
  53208. }
  53209. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  53210. viewer.isEnabled = true;
  53211. _this._skeletonViewers.push(viewer);
  53212. }
  53213. }
  53214. });
  53215. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53216. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  53217. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  53218. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  53219. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  53220. if (_this._camera) {
  53221. console.log(_this._camera);
  53222. }
  53223. else {
  53224. console.warn("No camera defined, or debug layer created before camera creation!");
  53225. }
  53226. });
  53227. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53228. this._globalDiv.appendChild(this._statsDiv);
  53229. this._globalDiv.appendChild(this._logDiv);
  53230. this._globalDiv.appendChild(this._optionsDiv);
  53231. this._globalDiv.appendChild(this._treeDiv);
  53232. }
  53233. };
  53234. DebugLayer.prototype._displayStats = function () {
  53235. var scene = this._scene;
  53236. var engine = scene.getEngine();
  53237. var glInfo = engine.getGlInfo();
  53238. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  53239. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53240. + "<b>Count</b><br>"
  53241. + "Total meshes: " + scene.meshes.length + "<br>"
  53242. + "Total lights: " + scene.lights.length + "<br>"
  53243. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  53244. + "Total materials: " + scene.materials.length + "<br>"
  53245. + "Total textures: " + scene.textures.length + "<br>"
  53246. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  53247. + "Active indices: " + scene.getActiveIndices() + "<br>"
  53248. + "Active bones: " + scene.getActiveBones() + "<br>"
  53249. + "Active particles: " + scene.getActiveParticles() + "<br>"
  53250. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  53251. + "<b>Duration</b><br>"
  53252. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  53253. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  53254. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  53255. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  53256. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  53257. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  53258. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  53259. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  53260. + "</div>"
  53261. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53262. + "<b>Extensions</b><br>"
  53263. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  53264. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  53265. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  53266. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  53267. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  53268. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  53269. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  53270. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  53271. + "</div><br>"
  53272. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53273. + "<b>Caps.</b><br>"
  53274. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  53275. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  53276. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  53277. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  53278. + "<b>Info</b><br>"
  53279. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  53280. + glInfo.version + "<br>"
  53281. + "</div><br>"
  53282. + glInfo.renderer + "<br>";
  53283. if (this.customStatsFunction) {
  53284. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  53285. }
  53286. };
  53287. return DebugLayer;
  53288. }());
  53289. BABYLON.DebugLayer = DebugLayer;
  53290. })(BABYLON || (BABYLON = {}));
  53291. var BABYLON;
  53292. (function (BABYLON) {
  53293. var StandardRenderingPipeline = (function (_super) {
  53294. __extends(StandardRenderingPipeline, _super);
  53295. /**
  53296. * @constructor
  53297. * @param {string} name - The rendering pipeline name
  53298. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53299. * @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)
  53300. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53301. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53302. */
  53303. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53304. var _this = this;
  53305. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53306. _super.call(this, scene.getEngine(), name);
  53307. this.downSampleX4PostProcess = null;
  53308. this.brightPassPostProcess = null;
  53309. this.gaussianBlurHPostProcesses = [];
  53310. this.gaussianBlurVPostProcesses = [];
  53311. this.textureAdderPostProcess = null;
  53312. this.textureAdderFinalPostProcess = null;
  53313. this.lensFlarePostProcess = null;
  53314. this.lensFlareShiftPostProcess = null;
  53315. this.lensFlareComposePostProcess = null;
  53316. this.depthOfFieldPostProcess = null;
  53317. this.motionBlurPostProcess = null;
  53318. // Values
  53319. this.brightThreshold = 1.0;
  53320. this.gaussianCoefficient = 0.25;
  53321. this.gaussianMean = 1.0;
  53322. this.gaussianStandardDeviation = 1.0;
  53323. this.exposure = 1.0;
  53324. this.lensTexture = null;
  53325. this.lensColorTexture = null;
  53326. this.lensFlareStrength = 1.0;
  53327. this.lensFlareGhostDispersal = 1.0;
  53328. this.lensFlareHaloWidth = 0.4;
  53329. this.lensFlareDistortionStrength = 4.0;
  53330. this.lensStarTexture = null;
  53331. this.lensFlareDirtTexture = null;
  53332. this.depthOfFieldDistance = 10.0;
  53333. this._depthRenderer = null;
  53334. // Getters and setters
  53335. this._depthOfFieldEnabled = true;
  53336. this._lensFlareEnabled = true;
  53337. // Initialize
  53338. this._scene = scene;
  53339. // Create pass post-processe
  53340. if (!originalPostProcess) {
  53341. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  53342. }
  53343. else {
  53344. this.originalPostProcess = originalPostProcess;
  53345. }
  53346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53347. // Create down sample X4 post-process
  53348. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53349. // Create bright pass post-process
  53350. this._createBrightPassPostProcess(scene, ratio / 2);
  53351. // Create gaussian blur post-processes (down sampling blurs)
  53352. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  53353. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  53354. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  53355. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  53356. // Create texture adder post-process
  53357. this._createTextureAdderPostProcess(scene, ratio);
  53358. // Create depth-of-field source post-process
  53359. 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);
  53360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53361. // Create lens flare post-process
  53362. this._createLensFlarePostProcess(scene, ratio);
  53363. // Create gaussian blur used by depth-of-field
  53364. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  53365. // Create depth-of-field post-process
  53366. this._createDepthOfFieldPostProcess(scene, ratio);
  53367. // Finish
  53368. scene.postProcessRenderPipelineManager.addPipeline(this);
  53369. if (cameras !== null) {
  53370. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53371. }
  53372. // Deactivate
  53373. this.LensFlareEnabled = false;
  53374. this.DepthOfFieldEnabled = false;
  53375. }
  53376. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53377. get: function () {
  53378. return this._depthOfFieldEnabled;
  53379. },
  53380. set: function (enabled) {
  53381. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  53382. if (enabled && !this._depthOfFieldEnabled) {
  53383. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53384. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53385. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53386. this._depthRenderer = this._scene.enableDepthRenderer();
  53387. }
  53388. else if (!enabled && this._depthOfFieldEnabled) {
  53389. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53390. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53391. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53392. }
  53393. this._depthOfFieldEnabled = enabled;
  53394. },
  53395. enumerable: true,
  53396. configurable: true
  53397. });
  53398. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53399. get: function () {
  53400. return this._lensFlareEnabled;
  53401. },
  53402. set: function (enabled) {
  53403. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  53404. if (enabled && !this._lensFlareEnabled) {
  53405. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53406. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53407. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53408. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53409. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53410. this._depthRenderer = this._scene.enableDepthRenderer();
  53411. }
  53412. else if (!enabled && this._lensFlareEnabled) {
  53413. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53414. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53415. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53416. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53417. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53418. }
  53419. this._lensFlareEnabled = enabled;
  53420. },
  53421. enumerable: true,
  53422. configurable: true
  53423. });
  53424. // Down Sample X4 Post-Processs
  53425. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53426. var _this = this;
  53427. var downSampleX4Offsets = new Array(32);
  53428. 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);
  53429. this.downSampleX4PostProcess.onApply = function (effect) {
  53430. var id = 0;
  53431. for (var i = -2; i < 2; i++) {
  53432. for (var j = -2; j < 2; j++) {
  53433. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53434. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53435. id += 2;
  53436. }
  53437. }
  53438. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53439. };
  53440. // Add to pipeline
  53441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53442. };
  53443. // Brightpass Post-Process
  53444. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53445. var _this = this;
  53446. var brightOffsets = new Array(8);
  53447. 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);
  53448. this.brightPassPostProcess.onApply = function (effect) {
  53449. var sU = (1.0 / _this.brightPassPostProcess.width);
  53450. var sV = (1.0 / _this.brightPassPostProcess.height);
  53451. brightOffsets[0] = -0.5 * sU;
  53452. brightOffsets[1] = 0.5 * sV;
  53453. brightOffsets[2] = 0.5 * sU;
  53454. brightOffsets[3] = 0.5 * sV;
  53455. brightOffsets[4] = -0.5 * sU;
  53456. brightOffsets[5] = -0.5 * sV;
  53457. brightOffsets[6] = 0.5 * sU;
  53458. brightOffsets[7] = -0.5 * sV;
  53459. effect.setArray2("dsOffsets", brightOffsets);
  53460. effect.setFloat("brightThreshold", _this.brightThreshold);
  53461. };
  53462. // Add to pipeline
  53463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53464. };
  53465. // Create gaussian blur H&V post-processes
  53466. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  53467. var _this = this;
  53468. var blurOffsets = new Array(9);
  53469. var blurWeights = new Array(9);
  53470. var uniforms = ["blurOffsets", "blurWeights"];
  53471. var callback = function (height) {
  53472. return function (effect) {
  53473. // Weights
  53474. var x = 0.0;
  53475. for (var i = 0; i < 9; i++) {
  53476. x = (i - 4.0) / 4.0;
  53477. blurWeights[i] =
  53478. _this.gaussianCoefficient
  53479. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  53480. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  53481. }
  53482. var lastOutputDimensions = {
  53483. width: scene.getEngine().getRenderWidth(),
  53484. height: scene.getEngine().getRenderHeight()
  53485. };
  53486. for (var i = 0; i < 9; i++) {
  53487. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53488. blurOffsets[i] = value;
  53489. }
  53490. effect.setArray("blurOffsets", blurOffsets);
  53491. effect.setArray("blurWeights", blurWeights);
  53492. };
  53493. };
  53494. // Create horizontal gaussian blur post-processes
  53495. 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);
  53496. gaussianBlurHPostProcess.onApply = callback(false);
  53497. // Create vertical gaussian blur post-process
  53498. 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);
  53499. gaussianBlurVPostProcess.onApply = callback(true);
  53500. // Add to pipeline
  53501. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  53502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  53503. // Finish
  53504. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  53505. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  53506. };
  53507. // Create texture adder post-process
  53508. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53509. var _this = this;
  53510. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  53511. 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);
  53512. this.textureAdderPostProcess.onApply = function (effect) {
  53513. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  53514. effect.setTexture("lensSampler", _this.lensTexture);
  53515. effect.setFloat("exposure", _this.exposure);
  53516. };
  53517. // Add to pipeline
  53518. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53519. };
  53520. // Create lens flare post-process
  53521. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53522. var _this = this;
  53523. 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);
  53524. 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);
  53525. this._createGaussianBlurPostProcesses(scene, ratio / 8, 4);
  53526. 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);
  53527. var resolution = new BABYLON.Vector2(0, 0);
  53528. // Lens flare
  53529. this.lensFlarePostProcess.onApply = function (effect) {
  53530. effect.setTextureFromPostProcess("textureSampler", _this.textureAdderPostProcess);
  53531. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53532. effect.setFloat("strength", _this.lensFlareStrength);
  53533. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53534. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53535. };
  53536. // Shift
  53537. this.lensFlareShiftPostProcess.onApply = function (effect) {
  53538. resolution.x = _this.lensFlareShiftPostProcess.width;
  53539. resolution.y = _this.lensFlareShiftPostProcess.height;
  53540. effect.setVector2("resolution", resolution);
  53541. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53542. };
  53543. // Compose
  53544. 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));
  53545. 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));
  53546. this.lensFlareComposePostProcess.onApply = function (effect) {
  53547. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53548. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53549. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53550. effect.setMatrix("viewMatrix", _this._scene.activeCamera.getViewMatrix());
  53551. effect.setMatrix3x3("scaleBias1", scaleBias1);
  53552. effect.setMatrix3x3("scaleBias2", scaleBias2);
  53553. };
  53554. // Add to pipeline
  53555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  53556. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareShift", function () { return _this.lensFlareShiftPostProcess; }, false));
  53557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  53558. };
  53559. // Create depth-of-field post-process
  53560. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53561. var _this = this;
  53562. 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);
  53563. this.depthOfFieldPostProcess.onApply = function (effect) {
  53564. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53565. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  53566. effect.setFloat("distance", _this.depthOfFieldDistance);
  53567. };
  53568. // Add to pipeline
  53569. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53570. };
  53571. return StandardRenderingPipeline;
  53572. }(BABYLON.PostProcessRenderPipeline));
  53573. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53574. })(BABYLON || (BABYLON = {}));
  53575. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nfloat hash(vec2 p) {\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p) {\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p) {\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec4 result=vec4(0.0);\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*float(i));\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=texture2D(textureSampler,offset)*weight;\n}\nfloat patternWeight=0.4*length(vec2(0.5)-uv);\nresult=mix(result,result*vec4(pattern(uv),1.0),0.6);\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-vUV)/length(vec2(0.5))));\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,5.0);\nvec4 halo=texture2D(textureSampler,uv+haloVec)*weight;\ngl_FragColor=(result+halo)*strength;\n}\n#endif\n#if defined(LENS_FLARE_SHIFT)\nuniform vec2 resolution;\nuniform float distortionStrength;\nvoid main(void)\n{\nconst float dispersion=0.15;\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-vUV);\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec2 direction=vec2(normalize(ghostDir));\nvec4 rgbShift=vec4(\ntexture2D(textureSampler,vUV+direction*distortion.r).r,\ntexture2D(textureSampler,vUV+direction*distortion.g).g,\ntexture2D(textureSampler,vUV+direction*distortion.b).b,\n1.0\n);\ngl_FragColor=rgbShift;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 viewMatrix;\nuniform mat3 scaleBias1;\nuniform mat3 scaleBias2;\nvoid main(void)\n{\nvec3 camerax=viewMatrix[0].xyz;\nvec3 cameraz=viewMatrix[1].xyz;\nfloat camRot=dot(camerax,vec3(0.0,0.0,1.0))+dot(cameraz,vec3(0.0,1.0,0.0));\nmat3 rotation=mat3(\ncos(camRot),-sin(camRot),0.0,\nsin(camRot),cos(camRot),0.0,\n0.0,0.0,1.0\n);\nmat3 lensMatrix=scaleBias2*rotation*scaleBias1;\nvec2 lensFlareCoords=(lensMatrix*vec3(vUV,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,lensFlareCoords);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  53576. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  53577. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n=this.x,r=this.y,o=this.z,e=this.w,s=n*n,h=-2*(s+r*r)+1,a=2*(o*n+e*r),u=-2*(o*r-e*n),m=2*(n*r+e*o),y=-2*(o*o+s)+1;return u=u>1?1:u,u=u<-1?-1:u,t.x=Math.asin(u),t.z=Math.atan2(m,y),t.y=Math.atan2(a,h),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),b=1/(i*T+n*_+r*M+o*A),F=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*D)*b,t.m[7]=(i*I-r*q+o*V)*b,t.m[11]=-(i*H-n*q+o*N)*b,t.m[15]=(i*D-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),\nthis},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],b=t.m[8],F=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return n<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  53578. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  53579. module.exports = BABYLON;
  53580. };