babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315
  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. Color4.prototype.toString = function () {
  267. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  268. };
  269. Color4.prototype.getClassName = function () {
  270. return "Color4";
  271. };
  272. Color4.prototype.getHashCode = function () {
  273. var hash = this.r || 0;
  274. hash = (hash * 397) ^ (this.g || 0);
  275. hash = (hash * 397) ^ (this.b || 0);
  276. hash = (hash * 397) ^ (this.a || 0);
  277. return hash;
  278. };
  279. Color4.prototype.clone = function () {
  280. return new Color4(this.r, this.g, this.b, this.a);
  281. };
  282. Color4.prototype.copyFrom = function (source) {
  283. this.r = source.r;
  284. this.g = source.g;
  285. this.b = source.b;
  286. this.a = source.a;
  287. return this;
  288. };
  289. Color4.prototype.toHexString = function () {
  290. var intR = (this.r * 255) | 0;
  291. var intG = (this.g * 255) | 0;
  292. var intB = (this.b * 255) | 0;
  293. var intA = (this.a * 255) | 0;
  294. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  295. };
  296. // Statics
  297. Color4.FromHexString = function (hex) {
  298. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  299. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  300. return new Color4(0, 0, 0, 0);
  301. }
  302. var r = parseInt(hex.substring(1, 3), 16);
  303. var g = parseInt(hex.substring(3, 5), 16);
  304. var b = parseInt(hex.substring(5, 7), 16);
  305. var a = parseInt(hex.substring(7, 9), 16);
  306. return Color4.FromInts(r, g, b, a);
  307. };
  308. Color4.Lerp = function (left, right, amount) {
  309. var result = new Color4(0, 0, 0, 0);
  310. Color4.LerpToRef(left, right, amount, result);
  311. return result;
  312. };
  313. Color4.LerpToRef = function (left, right, amount, result) {
  314. result.r = left.r + (right.r - left.r) * amount;
  315. result.g = left.g + (right.g - left.g) * amount;
  316. result.b = left.b + (right.b - left.b) * amount;
  317. result.a = left.a + (right.a - left.a) * amount;
  318. };
  319. Color4.FromArray = function (array, offset) {
  320. if (offset === void 0) { offset = 0; }
  321. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  322. };
  323. Color4.FromInts = function (r, g, b, a) {
  324. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  325. };
  326. Color4.CheckColors4 = function (colors, count) {
  327. // Check if color3 was used
  328. if (colors.length === count * 3) {
  329. var colors4 = [];
  330. for (var index = 0; index < colors.length; index += 3) {
  331. var newIndex = (index / 3) * 4;
  332. colors4[newIndex] = colors[index];
  333. colors4[newIndex + 1] = colors[index + 1];
  334. colors4[newIndex + 2] = colors[index + 2];
  335. colors4[newIndex + 3] = 1.0;
  336. }
  337. return colors4;
  338. }
  339. return colors;
  340. };
  341. return Color4;
  342. })();
  343. BABYLON.Color4 = Color4;
  344. var Vector2 = (function () {
  345. function Vector2(x, y) {
  346. this.x = x;
  347. this.y = y;
  348. }
  349. Vector2.prototype.toString = function () {
  350. return "{X: " + this.x + " Y:" + this.y + "}";
  351. };
  352. Vector2.prototype.getClassName = function () {
  353. return "Vector2";
  354. };
  355. Vector2.prototype.getHashCode = function () {
  356. var hash = this.x || 0;
  357. hash = (hash * 397) ^ (this.y || 0);
  358. return hash;
  359. };
  360. // Operators
  361. Vector2.prototype.toArray = function (array, index) {
  362. if (index === void 0) { index = 0; }
  363. array[index] = this.x;
  364. array[index + 1] = this.y;
  365. return this;
  366. };
  367. Vector2.prototype.asArray = function () {
  368. var result = [];
  369. this.toArray(result, 0);
  370. return result;
  371. };
  372. Vector2.prototype.copyFrom = function (source) {
  373. this.x = source.x;
  374. this.y = source.y;
  375. return this;
  376. };
  377. Vector2.prototype.copyFromFloats = function (x, y) {
  378. this.x = x;
  379. this.y = y;
  380. return this;
  381. };
  382. Vector2.prototype.add = function (otherVector) {
  383. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  384. };
  385. Vector2.prototype.addVector3 = function (otherVector) {
  386. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  387. };
  388. Vector2.prototype.subtract = function (otherVector) {
  389. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  390. };
  391. Vector2.prototype.subtractInPlace = function (otherVector) {
  392. this.x -= otherVector.x;
  393. this.y -= otherVector.y;
  394. return this;
  395. };
  396. Vector2.prototype.multiplyInPlace = function (otherVector) {
  397. this.x *= otherVector.x;
  398. this.y *= otherVector.y;
  399. return this;
  400. };
  401. Vector2.prototype.multiply = function (otherVector) {
  402. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  403. };
  404. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  405. result.x = this.x * otherVector.x;
  406. result.y = this.y * otherVector.y;
  407. return this;
  408. };
  409. Vector2.prototype.multiplyByFloats = function (x, y) {
  410. return new Vector2(this.x * x, this.y * y);
  411. };
  412. Vector2.prototype.divide = function (otherVector) {
  413. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  414. };
  415. Vector2.prototype.divideToRef = function (otherVector, result) {
  416. result.x = this.x / otherVector.x;
  417. result.y = this.y / otherVector.y;
  418. return this;
  419. };
  420. Vector2.prototype.negate = function () {
  421. return new Vector2(-this.x, -this.y);
  422. };
  423. Vector2.prototype.scaleInPlace = function (scale) {
  424. this.x *= scale;
  425. this.y *= scale;
  426. return this;
  427. };
  428. Vector2.prototype.scale = function (scale) {
  429. return new Vector2(this.x * scale, this.y * scale);
  430. };
  431. Vector2.prototype.equals = function (otherVector) {
  432. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  433. };
  434. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  435. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  436. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  437. };
  438. // Properties
  439. Vector2.prototype.length = function () {
  440. return Math.sqrt(this.x * this.x + this.y * this.y);
  441. };
  442. Vector2.prototype.lengthSquared = function () {
  443. return (this.x * this.x + this.y * this.y);
  444. };
  445. // Methods
  446. Vector2.prototype.normalize = function () {
  447. var len = this.length();
  448. if (len === 0)
  449. return this;
  450. var num = 1.0 / len;
  451. this.x *= num;
  452. this.y *= num;
  453. return this;
  454. };
  455. Vector2.prototype.clone = function () {
  456. return new Vector2(this.x, this.y);
  457. };
  458. // Statics
  459. Vector2.Zero = function () {
  460. return new Vector2(0, 0);
  461. };
  462. Vector2.FromArray = function (array, offset) {
  463. if (offset === void 0) { offset = 0; }
  464. return new Vector2(array[offset], array[offset + 1]);
  465. };
  466. Vector2.FromArrayToRef = function (array, offset, result) {
  467. result.x = array[offset];
  468. result.y = array[offset + 1];
  469. };
  470. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  471. var squared = amount * amount;
  472. var cubed = amount * squared;
  473. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  474. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  475. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  476. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  477. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  478. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  479. return new Vector2(x, y);
  480. };
  481. Vector2.Clamp = function (value, min, max) {
  482. var x = value.x;
  483. x = (x > max.x) ? max.x : x;
  484. x = (x < min.x) ? min.x : x;
  485. var y = value.y;
  486. y = (y > max.y) ? max.y : y;
  487. y = (y < min.y) ? min.y : y;
  488. return new Vector2(x, y);
  489. };
  490. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  491. var squared = amount * amount;
  492. var cubed = amount * squared;
  493. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  494. var part2 = (-2.0 * cubed) + (3.0 * squared);
  495. var part3 = (cubed - (2.0 * squared)) + amount;
  496. var part4 = cubed - squared;
  497. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  498. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  499. return new Vector2(x, y);
  500. };
  501. Vector2.Lerp = function (start, end, amount) {
  502. var x = start.x + ((end.x - start.x) * amount);
  503. var y = start.y + ((end.y - start.y) * amount);
  504. return new Vector2(x, y);
  505. };
  506. Vector2.Dot = function (left, right) {
  507. return left.x * right.x + left.y * right.y;
  508. };
  509. Vector2.Normalize = function (vector) {
  510. var newVector = vector.clone();
  511. newVector.normalize();
  512. return newVector;
  513. };
  514. Vector2.Minimize = function (left, right) {
  515. var x = (left.x < right.x) ? left.x : right.x;
  516. var y = (left.y < right.y) ? left.y : right.y;
  517. return new Vector2(x, y);
  518. };
  519. Vector2.Maximize = function (left, right) {
  520. var x = (left.x > right.x) ? left.x : right.x;
  521. var y = (left.y > right.y) ? left.y : right.y;
  522. return new Vector2(x, y);
  523. };
  524. Vector2.Transform = function (vector, transformation) {
  525. var r = Vector2.Zero();
  526. Vector2.TransformToRef(vector, transformation, r);
  527. return r;
  528. };
  529. Vector2.TransformToRef = function (vector, transformation, result) {
  530. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  531. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  532. result.x = x;
  533. result.y = y;
  534. };
  535. Vector2.Distance = function (value1, value2) {
  536. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  537. };
  538. Vector2.DistanceSquared = function (value1, value2) {
  539. var x = value1.x - value2.x;
  540. var y = value1.y - value2.y;
  541. return (x * x) + (y * y);
  542. };
  543. return Vector2;
  544. })();
  545. BABYLON.Vector2 = Vector2;
  546. var Vector3 = (function () {
  547. function Vector3(x, y, z) {
  548. this.x = x;
  549. this.y = y;
  550. this.z = z;
  551. }
  552. Vector3.prototype.toString = function () {
  553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  554. };
  555. Vector3.prototype.getClassName = function () {
  556. return "Vector3";
  557. };
  558. Vector3.prototype.getHashCode = function () {
  559. var hash = this.x || 0;
  560. hash = (hash * 397) ^ (this.y || 0);
  561. hash = (hash * 397) ^ (this.z || 0);
  562. return hash;
  563. };
  564. // Operators
  565. Vector3.prototype.asArray = function () {
  566. var result = [];
  567. this.toArray(result, 0);
  568. return result;
  569. };
  570. Vector3.prototype.toArray = function (array, index) {
  571. if (index === void 0) { index = 0; }
  572. array[index] = this.x;
  573. array[index + 1] = this.y;
  574. array[index + 2] = this.z;
  575. return this;
  576. };
  577. Vector3.prototype.toQuaternion = function () {
  578. var result = new Quaternion(0, 0, 0, 1);
  579. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  580. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  581. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  582. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  583. var cosy = Math.cos(this.y * 0.5);
  584. var siny = Math.sin(this.y * 0.5);
  585. result.x = coszMinusx * siny;
  586. result.y = -sinzMinusx * siny;
  587. result.z = sinxPlusz * cosy;
  588. result.w = cosxPlusz * cosy;
  589. return result;
  590. };
  591. Vector3.prototype.addInPlace = function (otherVector) {
  592. this.x += otherVector.x;
  593. this.y += otherVector.y;
  594. this.z += otherVector.z;
  595. return this;
  596. };
  597. Vector3.prototype.add = function (otherVector) {
  598. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  599. };
  600. Vector3.prototype.addToRef = function (otherVector, result) {
  601. result.x = this.x + otherVector.x;
  602. result.y = this.y + otherVector.y;
  603. result.z = this.z + otherVector.z;
  604. return this;
  605. };
  606. Vector3.prototype.subtractInPlace = function (otherVector) {
  607. this.x -= otherVector.x;
  608. this.y -= otherVector.y;
  609. this.z -= otherVector.z;
  610. return this;
  611. };
  612. Vector3.prototype.subtract = function (otherVector) {
  613. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  614. };
  615. Vector3.prototype.subtractToRef = function (otherVector, result) {
  616. result.x = this.x - otherVector.x;
  617. result.y = this.y - otherVector.y;
  618. result.z = this.z - otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  622. return new Vector3(this.x - x, this.y - y, this.z - z);
  623. };
  624. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  625. result.x = this.x - x;
  626. result.y = this.y - y;
  627. result.z = this.z - z;
  628. return this;
  629. };
  630. Vector3.prototype.negate = function () {
  631. return new Vector3(-this.x, -this.y, -this.z);
  632. };
  633. Vector3.prototype.scaleInPlace = function (scale) {
  634. this.x *= scale;
  635. this.y *= scale;
  636. this.z *= scale;
  637. return this;
  638. };
  639. Vector3.prototype.scale = function (scale) {
  640. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  641. };
  642. Vector3.prototype.scaleToRef = function (scale, result) {
  643. result.x = this.x * scale;
  644. result.y = this.y * scale;
  645. result.z = this.z * scale;
  646. };
  647. Vector3.prototype.equals = function (otherVector) {
  648. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  649. };
  650. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  651. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  652. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  653. };
  654. Vector3.prototype.equalsToFloats = function (x, y, z) {
  655. return this.x === x && this.y === y && this.z === z;
  656. };
  657. Vector3.prototype.multiplyInPlace = function (otherVector) {
  658. this.x *= otherVector.x;
  659. this.y *= otherVector.y;
  660. this.z *= otherVector.z;
  661. return this;
  662. };
  663. Vector3.prototype.multiply = function (otherVector) {
  664. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  665. };
  666. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  667. result.x = this.x * otherVector.x;
  668. result.y = this.y * otherVector.y;
  669. result.z = this.z * otherVector.z;
  670. return this;
  671. };
  672. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  673. return new Vector3(this.x * x, this.y * y, this.z * z);
  674. };
  675. Vector3.prototype.divide = function (otherVector) {
  676. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  677. };
  678. Vector3.prototype.divideToRef = function (otherVector, result) {
  679. result.x = this.x / otherVector.x;
  680. result.y = this.y / otherVector.y;
  681. result.z = this.z / otherVector.z;
  682. return this;
  683. };
  684. Vector3.prototype.MinimizeInPlace = function (other) {
  685. if (other.x < this.x)
  686. this.x = other.x;
  687. if (other.y < this.y)
  688. this.y = other.y;
  689. if (other.z < this.z)
  690. this.z = other.z;
  691. return this;
  692. };
  693. Vector3.prototype.MaximizeInPlace = function (other) {
  694. if (other.x > this.x)
  695. this.x = other.x;
  696. if (other.y > this.y)
  697. this.y = other.y;
  698. if (other.z > this.z)
  699. this.z = other.z;
  700. return this;
  701. };
  702. // Properties
  703. Vector3.prototype.length = function () {
  704. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  705. };
  706. Vector3.prototype.lengthSquared = function () {
  707. return (this.x * this.x + this.y * this.y + this.z * this.z);
  708. };
  709. // Methods
  710. Vector3.prototype.normalize = function () {
  711. var len = this.length();
  712. if (len === 0 || len === 1.0)
  713. return this;
  714. var num = 1.0 / len;
  715. this.x *= num;
  716. this.y *= num;
  717. this.z *= num;
  718. return this;
  719. };
  720. Vector3.prototype.clone = function () {
  721. return new Vector3(this.x, this.y, this.z);
  722. };
  723. Vector3.prototype.copyFrom = function (source) {
  724. this.x = source.x;
  725. this.y = source.y;
  726. this.z = source.z;
  727. return this;
  728. };
  729. Vector3.prototype.copyFromFloats = function (x, y, z) {
  730. this.x = x;
  731. this.y = y;
  732. this.z = z;
  733. return this;
  734. };
  735. // Statics
  736. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  737. var d0 = Vector3.Dot(vector0, axis) - size;
  738. var d1 = Vector3.Dot(vector1, axis) - size;
  739. var s = d0 / (d0 - d1);
  740. return s;
  741. };
  742. Vector3.FromArray = function (array, offset) {
  743. if (!offset) {
  744. offset = 0;
  745. }
  746. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  747. };
  748. Vector3.FromFloatArray = function (array, offset) {
  749. if (!offset) {
  750. offset = 0;
  751. }
  752. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  753. };
  754. Vector3.FromArrayToRef = function (array, offset, result) {
  755. result.x = array[offset];
  756. result.y = array[offset + 1];
  757. result.z = array[offset + 2];
  758. };
  759. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  760. result.x = array[offset];
  761. result.y = array[offset + 1];
  762. result.z = array[offset + 2];
  763. };
  764. Vector3.FromFloatsToRef = function (x, y, z, result) {
  765. result.x = x;
  766. result.y = y;
  767. result.z = z;
  768. };
  769. Vector3.Zero = function () {
  770. return new Vector3(0, 0, 0);
  771. };
  772. Vector3.Up = function () {
  773. return new Vector3(0, 1.0, 0);
  774. };
  775. Vector3.TransformCoordinates = function (vector, transformation) {
  776. var result = Vector3.Zero();
  777. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  778. return result;
  779. };
  780. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  781. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  782. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  783. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  784. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  785. result.x = x / w;
  786. result.y = y / w;
  787. result.z = z / w;
  788. };
  789. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  790. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  791. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  792. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  793. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  794. result.x = rx / rw;
  795. result.y = ry / rw;
  796. result.z = rz / rw;
  797. };
  798. Vector3.TransformNormal = function (vector, transformation) {
  799. var result = Vector3.Zero();
  800. Vector3.TransformNormalToRef(vector, transformation, result);
  801. return result;
  802. };
  803. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  804. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  805. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  806. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  807. };
  808. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  809. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  810. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  811. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  812. };
  813. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  814. var squared = amount * amount;
  815. var cubed = amount * squared;
  816. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  817. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  818. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  819. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  820. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  821. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  822. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  823. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  824. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  825. return new Vector3(x, y, z);
  826. };
  827. Vector3.Clamp = function (value, min, max) {
  828. var x = value.x;
  829. x = (x > max.x) ? max.x : x;
  830. x = (x < min.x) ? min.x : x;
  831. var y = value.y;
  832. y = (y > max.y) ? max.y : y;
  833. y = (y < min.y) ? min.y : y;
  834. var z = value.z;
  835. z = (z > max.z) ? max.z : z;
  836. z = (z < min.z) ? min.z : z;
  837. return new Vector3(x, y, z);
  838. };
  839. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  840. var squared = amount * amount;
  841. var cubed = amount * squared;
  842. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  843. var part2 = (-2.0 * cubed) + (3.0 * squared);
  844. var part3 = (cubed - (2.0 * squared)) + amount;
  845. var part4 = cubed - squared;
  846. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  847. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  848. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  849. return new Vector3(x, y, z);
  850. };
  851. Vector3.Lerp = function (start, end, amount) {
  852. var x = start.x + ((end.x - start.x) * amount);
  853. var y = start.y + ((end.y - start.y) * amount);
  854. var z = start.z + ((end.z - start.z) * amount);
  855. return new Vector3(x, y, z);
  856. };
  857. Vector3.Dot = function (left, right) {
  858. return (left.x * right.x + left.y * right.y + left.z * right.z);
  859. };
  860. Vector3.Cross = function (left, right) {
  861. var result = Vector3.Zero();
  862. Vector3.CrossToRef(left, right, result);
  863. return result;
  864. };
  865. Vector3.CrossToRef = function (left, right, result) {
  866. result.x = left.y * right.z - left.z * right.y;
  867. result.y = left.z * right.x - left.x * right.z;
  868. result.z = left.x * right.y - left.y * right.x;
  869. };
  870. Vector3.Normalize = function (vector) {
  871. var result = Vector3.Zero();
  872. Vector3.NormalizeToRef(vector, result);
  873. return result;
  874. };
  875. Vector3.NormalizeToRef = function (vector, result) {
  876. result.copyFrom(vector);
  877. result.normalize();
  878. };
  879. Vector3.Project = function (vector, world, transform, viewport) {
  880. var cw = viewport.width;
  881. var ch = viewport.height;
  882. var cx = viewport.x;
  883. var cy = viewport.y;
  884. var viewportMatrix = Matrix.FromValues(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);
  885. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  886. return Vector3.TransformCoordinates(vector, finalMatrix);
  887. };
  888. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  889. var matrix = world.multiply(transform);
  890. matrix.invert();
  891. source.x = source.x / viewportWidth * 2 - 1;
  892. source.y = -(source.y / viewportHeight * 2 - 1);
  893. var vector = Vector3.TransformCoordinates(source, matrix);
  894. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  895. if (MathTools.WithinEpsilon(num, 1.0)) {
  896. vector = vector.scale(1.0 / num);
  897. }
  898. return vector;
  899. };
  900. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  901. var matrix = world.multiply(view).multiply(projection);
  902. matrix.invert();
  903. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  904. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  905. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  906. if (MathTools.WithinEpsilon(num, 1.0)) {
  907. vector = vector.scale(1.0 / num);
  908. }
  909. return vector;
  910. };
  911. Vector3.Minimize = function (left, right) {
  912. var min = left.clone();
  913. min.MinimizeInPlace(right);
  914. return min;
  915. };
  916. Vector3.Maximize = function (left, right) {
  917. var max = left.clone();
  918. max.MaximizeInPlace(right);
  919. return max;
  920. };
  921. Vector3.Distance = function (value1, value2) {
  922. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  923. };
  924. Vector3.DistanceSquared = function (value1, value2) {
  925. var x = value1.x - value2.x;
  926. var y = value1.y - value2.y;
  927. var z = value1.z - value2.z;
  928. return (x * x) + (y * y) + (z * z);
  929. };
  930. Vector3.Center = function (value1, value2) {
  931. var center = value1.add(value2);
  932. center.scaleInPlace(0.5);
  933. return center;
  934. };
  935. /**
  936. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  937. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  938. * to something in order to rotate it from its local system to the given target system.
  939. */
  940. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  941. var rotation = Vector3.Zero();
  942. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  943. return rotation;
  944. };
  945. /**
  946. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  947. */
  948. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  949. var u = axis1.normalize();
  950. var w = axis3.normalize();
  951. // world axis
  952. var X = Axis.X;
  953. var Y = Axis.Y;
  954. // equation unknowns and vars
  955. var yaw = 0.0;
  956. var pitch = 0.0;
  957. var roll = 0.0;
  958. var x = 0.0;
  959. var y = 0.0;
  960. var z = 0.0;
  961. var t = 0.0;
  962. var sign = -1.0;
  963. var nbRevert = 0;
  964. var cross = Tmp.Vector3[0];
  965. var dot = 0.0;
  966. // step 1 : rotation around w
  967. // Rv3(u) = u1, and u1 belongs to plane xOz
  968. // Rv3(w) = w1 = w invariant
  969. var u1 = Tmp.Vector3[1];
  970. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  971. z = 1.0;
  972. }
  973. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  974. x = 1.0;
  975. }
  976. else {
  977. t = w.z / w.x;
  978. x = -t * Math.sqrt(1 / (1 + t * t));
  979. z = Math.sqrt(1 / (1 + t * t));
  980. }
  981. u1.x = x;
  982. u1.y = y;
  983. u1.z = z;
  984. u1.normalize();
  985. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  986. cross.normalize();
  987. if (Vector3.Dot(w, cross) < 0) {
  988. sign = 1.0;
  989. }
  990. dot = Vector3.Dot(u, u1);
  991. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  992. roll = Math.acos(dot) * sign;
  993. if (Vector3.Dot(u1, X) < 0) {
  994. roll = Math.PI + roll;
  995. u1 = u1.scaleInPlace(-1);
  996. nbRevert++;
  997. }
  998. // step 2 : rotate around u1
  999. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1000. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1001. var w2 = Tmp.Vector3[2];
  1002. var v2 = Tmp.Vector3[3];
  1003. x = 0.0;
  1004. y = 0.0;
  1005. z = 0.0;
  1006. sign = -1.0;
  1007. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1008. x = 1.0;
  1009. }
  1010. else {
  1011. t = u1.z / u1.x;
  1012. x = -t * Math.sqrt(1 / (1 + t * t));
  1013. z = Math.sqrt(1 / (1 + t * t));
  1014. }
  1015. w2.x = x;
  1016. w2.y = y;
  1017. w2.z = z;
  1018. w2.normalize();
  1019. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1020. v2.normalize();
  1021. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1022. cross.normalize();
  1023. if (Vector3.Dot(u1, cross) < 0) {
  1024. sign = 1.0;
  1025. }
  1026. dot = Vector3.Dot(w, w2);
  1027. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1028. pitch = Math.acos(dot) * sign;
  1029. if (Vector3.Dot(v2, Y) < 0) {
  1030. pitch = Math.PI + pitch;
  1031. nbRevert++;
  1032. }
  1033. // step 3 : rotate around v2
  1034. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1035. sign = -1.0;
  1036. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1037. cross.normalize();
  1038. if (Vector3.Dot(cross, Y) < 0) {
  1039. sign = 1.0;
  1040. }
  1041. dot = Vector3.Dot(u1, X);
  1042. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1043. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1044. if (dot < 0 && nbRevert < 2) {
  1045. yaw = Math.PI + yaw;
  1046. }
  1047. ref.x = pitch;
  1048. ref.y = yaw;
  1049. ref.z = roll;
  1050. };
  1051. return Vector3;
  1052. })();
  1053. BABYLON.Vector3 = Vector3;
  1054. //Vector4 class created for EulerAngle class conversion to Quaternion
  1055. var Vector4 = (function () {
  1056. function Vector4(x, y, z, w) {
  1057. this.x = x;
  1058. this.y = y;
  1059. this.z = z;
  1060. this.w = w;
  1061. }
  1062. Vector4.prototype.toString = function () {
  1063. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1064. };
  1065. Vector4.prototype.getClassName = function () {
  1066. return "Vector4";
  1067. };
  1068. Vector4.prototype.getHashCode = function () {
  1069. var hash = this.x || 0;
  1070. hash = (hash * 397) ^ (this.y || 0);
  1071. hash = (hash * 397) ^ (this.z || 0);
  1072. hash = (hash * 397) ^ (this.w || 0);
  1073. return hash;
  1074. };
  1075. // Operators
  1076. Vector4.prototype.asArray = function () {
  1077. var result = [];
  1078. this.toArray(result, 0);
  1079. return result;
  1080. };
  1081. Vector4.prototype.toArray = function (array, index) {
  1082. if (index === undefined) {
  1083. index = 0;
  1084. }
  1085. array[index] = this.x;
  1086. array[index + 1] = this.y;
  1087. array[index + 2] = this.z;
  1088. array[index + 3] = this.w;
  1089. return this;
  1090. };
  1091. Vector4.prototype.addInPlace = function (otherVector) {
  1092. this.x += otherVector.x;
  1093. this.y += otherVector.y;
  1094. this.z += otherVector.z;
  1095. this.w += otherVector.w;
  1096. return this;
  1097. };
  1098. Vector4.prototype.add = function (otherVector) {
  1099. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1100. };
  1101. Vector4.prototype.addToRef = function (otherVector, result) {
  1102. result.x = this.x + otherVector.x;
  1103. result.y = this.y + otherVector.y;
  1104. result.z = this.z + otherVector.z;
  1105. result.w = this.w + otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.subtractInPlace = function (otherVector) {
  1109. this.x -= otherVector.x;
  1110. this.y -= otherVector.y;
  1111. this.z -= otherVector.z;
  1112. this.w -= otherVector.w;
  1113. return this;
  1114. };
  1115. Vector4.prototype.subtract = function (otherVector) {
  1116. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1117. };
  1118. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1119. result.x = this.x - otherVector.x;
  1120. result.y = this.y - otherVector.y;
  1121. result.z = this.z - otherVector.z;
  1122. result.w = this.w - otherVector.w;
  1123. return this;
  1124. };
  1125. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1126. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1127. };
  1128. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1129. result.x = this.x - x;
  1130. result.y = this.y - y;
  1131. result.z = this.z - z;
  1132. result.w = this.w - w;
  1133. return this;
  1134. };
  1135. Vector4.prototype.negate = function () {
  1136. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1137. };
  1138. Vector4.prototype.scaleInPlace = function (scale) {
  1139. this.x *= scale;
  1140. this.y *= scale;
  1141. this.z *= scale;
  1142. this.w *= scale;
  1143. return this;
  1144. };
  1145. Vector4.prototype.scale = function (scale) {
  1146. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1147. };
  1148. Vector4.prototype.scaleToRef = function (scale, result) {
  1149. result.x = this.x * scale;
  1150. result.y = this.y * scale;
  1151. result.z = this.z * scale;
  1152. result.w = this.w * scale;
  1153. };
  1154. Vector4.prototype.equals = function (otherVector) {
  1155. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1156. };
  1157. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1158. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1159. return otherVector
  1160. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1161. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1162. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1163. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1164. };
  1165. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1166. return this.x === x && this.y === y && this.z === z && this.w === w;
  1167. };
  1168. Vector4.prototype.multiplyInPlace = 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.multiply = 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.multiplyToRef = 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.multiplyByFloats = function (x, y, z, w) {
  1186. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1187. };
  1188. Vector4.prototype.divide = function (otherVector) {
  1189. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1190. };
  1191. Vector4.prototype.divideToRef = function (otherVector, result) {
  1192. result.x = this.x / otherVector.x;
  1193. result.y = this.y / otherVector.y;
  1194. result.z = this.z / otherVector.z;
  1195. result.w = this.w / otherVector.w;
  1196. return this;
  1197. };
  1198. Vector4.prototype.MinimizeInPlace = function (other) {
  1199. if (other.x < this.x)
  1200. this.x = other.x;
  1201. if (other.y < this.y)
  1202. this.y = other.y;
  1203. if (other.z < this.z)
  1204. this.z = other.z;
  1205. if (other.w < this.w)
  1206. this.w = other.w;
  1207. return this;
  1208. };
  1209. Vector4.prototype.MaximizeInPlace = function (other) {
  1210. if (other.x > this.x)
  1211. this.x = other.x;
  1212. if (other.y > this.y)
  1213. this.y = other.y;
  1214. if (other.z > this.z)
  1215. this.z = other.z;
  1216. if (other.w > this.w)
  1217. this.w = other.w;
  1218. return this;
  1219. };
  1220. // Properties
  1221. Vector4.prototype.length = function () {
  1222. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1223. };
  1224. Vector4.prototype.lengthSquared = function () {
  1225. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1226. };
  1227. // Methods
  1228. Vector4.prototype.normalize = function () {
  1229. var len = this.length();
  1230. if (len === 0)
  1231. return this;
  1232. var num = 1.0 / len;
  1233. this.x *= num;
  1234. this.y *= num;
  1235. this.z *= num;
  1236. this.w *= num;
  1237. return this;
  1238. };
  1239. Vector4.prototype.toVector3 = function () {
  1240. return new Vector3(this.x, this.y, this.z);
  1241. };
  1242. Vector4.prototype.clone = function () {
  1243. return new Vector4(this.x, this.y, this.z, this.w);
  1244. };
  1245. Vector4.prototype.copyFrom = function (source) {
  1246. this.x = source.x;
  1247. this.y = source.y;
  1248. this.z = source.z;
  1249. this.w = source.w;
  1250. return this;
  1251. };
  1252. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1253. this.x = x;
  1254. this.y = y;
  1255. this.z = z;
  1256. this.w = w;
  1257. return this;
  1258. };
  1259. // Statics
  1260. Vector4.FromArray = function (array, offset) {
  1261. if (!offset) {
  1262. offset = 0;
  1263. }
  1264. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1265. };
  1266. Vector4.FromArrayToRef = function (array, offset, result) {
  1267. result.x = array[offset];
  1268. result.y = array[offset + 1];
  1269. result.z = array[offset + 2];
  1270. result.w = array[offset + 3];
  1271. };
  1272. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1273. result.x = array[offset];
  1274. result.y = array[offset + 1];
  1275. result.z = array[offset + 2];
  1276. result.w = array[offset + 3];
  1277. };
  1278. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1279. result.x = x;
  1280. result.y = y;
  1281. result.z = z;
  1282. result.w = w;
  1283. };
  1284. Vector4.Zero = function () {
  1285. return new Vector4(0, 0, 0, 0);
  1286. };
  1287. Vector4.Normalize = function (vector) {
  1288. var result = Vector4.Zero();
  1289. Vector4.NormalizeToRef(vector, result);
  1290. return result;
  1291. };
  1292. Vector4.NormalizeToRef = function (vector, result) {
  1293. result.copyFrom(vector);
  1294. result.normalize();
  1295. };
  1296. Vector4.Minimize = function (left, right) {
  1297. var min = left.clone();
  1298. min.MinimizeInPlace(right);
  1299. return min;
  1300. };
  1301. Vector4.Maximize = function (left, right) {
  1302. var max = left.clone();
  1303. max.MaximizeInPlace(right);
  1304. return max;
  1305. };
  1306. Vector4.Distance = function (value1, value2) {
  1307. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1308. };
  1309. Vector4.DistanceSquared = function (value1, value2) {
  1310. var x = value1.x - value2.x;
  1311. var y = value1.y - value2.y;
  1312. var z = value1.z - value2.z;
  1313. var w = value1.w - value2.w;
  1314. return (x * x) + (y * y) + (z * z) + (w * w);
  1315. };
  1316. Vector4.Center = function (value1, value2) {
  1317. var center = value1.add(value2);
  1318. center.scaleInPlace(0.5);
  1319. return center;
  1320. };
  1321. return Vector4;
  1322. })();
  1323. BABYLON.Vector4 = Vector4;
  1324. var Size = (function () {
  1325. function Size(width, height) {
  1326. this.width = width;
  1327. this.height = height;
  1328. }
  1329. Size.prototype.toString = function () {
  1330. return "{W: " + this.width + ", H: " + this.height + "}";
  1331. };
  1332. Size.prototype.getClassName = function () {
  1333. return "Size";
  1334. };
  1335. Size.prototype.getHashCode = function () {
  1336. var hash = this.width || 0;
  1337. hash = (hash * 397) ^ (this.height || 0);
  1338. return hash;
  1339. };
  1340. Size.prototype.clone = function () {
  1341. return new Size(this.width, this.height);
  1342. };
  1343. Size.prototype.equals = function (other) {
  1344. if (!other) {
  1345. return false;
  1346. }
  1347. return (this.width === other.width) && (this.height === other.height);
  1348. };
  1349. Object.defineProperty(Size.prototype, "surface", {
  1350. get: function () {
  1351. return this.width * this.height;
  1352. },
  1353. enumerable: true,
  1354. configurable: true
  1355. });
  1356. Size.Zero = function () {
  1357. return new Size(0, 0);
  1358. };
  1359. Size.prototype.add = function (otherSize) {
  1360. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1361. return r;
  1362. };
  1363. Size.prototype.substract = function (otherSize) {
  1364. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1365. return r;
  1366. };
  1367. Size.Lerp = function (start, end, amount) {
  1368. var w = start.width + ((end.width - start.width) * amount);
  1369. var h = start.height + ((end.height - start.height) * amount);
  1370. return new Size(w, h);
  1371. };
  1372. return Size;
  1373. })();
  1374. BABYLON.Size = Size;
  1375. var Quaternion = (function () {
  1376. function Quaternion(x, y, z, w) {
  1377. if (x === void 0) { x = 0; }
  1378. if (y === void 0) { y = 0; }
  1379. if (z === void 0) { z = 0; }
  1380. if (w === void 0) { w = 1; }
  1381. this.x = x;
  1382. this.y = y;
  1383. this.z = z;
  1384. this.w = w;
  1385. }
  1386. Quaternion.prototype.toString = function () {
  1387. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1388. };
  1389. Quaternion.prototype.getClassName = function () {
  1390. return "Quaternion";
  1391. };
  1392. Quaternion.prototype.getHashCode = function () {
  1393. var hash = this.x || 0;
  1394. hash = (hash * 397) ^ (this.y || 0);
  1395. hash = (hash * 397) ^ (this.z || 0);
  1396. hash = (hash * 397) ^ (this.w || 0);
  1397. return hash;
  1398. };
  1399. Quaternion.prototype.asArray = function () {
  1400. return [this.x, this.y, this.z, this.w];
  1401. };
  1402. Quaternion.prototype.equals = function (otherQuaternion) {
  1403. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1404. };
  1405. Quaternion.prototype.clone = function () {
  1406. return new Quaternion(this.x, this.y, this.z, this.w);
  1407. };
  1408. Quaternion.prototype.copyFrom = function (other) {
  1409. this.x = other.x;
  1410. this.y = other.y;
  1411. this.z = other.z;
  1412. this.w = other.w;
  1413. return this;
  1414. };
  1415. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1416. this.x = x;
  1417. this.y = y;
  1418. this.z = z;
  1419. this.w = w;
  1420. return this;
  1421. };
  1422. Quaternion.prototype.add = function (other) {
  1423. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1424. };
  1425. Quaternion.prototype.subtract = function (other) {
  1426. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1427. };
  1428. Quaternion.prototype.scale = function (value) {
  1429. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1430. };
  1431. Quaternion.prototype.multiply = function (q1) {
  1432. var result = new Quaternion(0, 0, 0, 1.0);
  1433. this.multiplyToRef(q1, result);
  1434. return result;
  1435. };
  1436. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1437. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1438. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1439. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1440. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1441. result.copyFromFloats(x, y, z, w);
  1442. return this;
  1443. };
  1444. Quaternion.prototype.multiplyInPlace = function (q1) {
  1445. this.multiplyToRef(q1, this);
  1446. return this;
  1447. };
  1448. Quaternion.prototype.conjugateToRef = function (ref) {
  1449. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1450. return this;
  1451. };
  1452. Quaternion.prototype.conjugateInPlace = function () {
  1453. this.x *= -1;
  1454. this.y *= -1;
  1455. this.z *= -1;
  1456. return this;
  1457. };
  1458. Quaternion.prototype.conjugate = function () {
  1459. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1460. return result;
  1461. };
  1462. Quaternion.prototype.length = function () {
  1463. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1464. };
  1465. Quaternion.prototype.normalize = function () {
  1466. var length = 1.0 / this.length();
  1467. this.x *= length;
  1468. this.y *= length;
  1469. this.z *= length;
  1470. this.w *= length;
  1471. return this;
  1472. };
  1473. Quaternion.prototype.toEulerAngles = function (order) {
  1474. if (order === void 0) { order = "YZX"; }
  1475. var result = Vector3.Zero();
  1476. this.toEulerAnglesToRef(result, order);
  1477. return result;
  1478. };
  1479. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1480. if (order === void 0) { order = "YZX"; }
  1481. var heading, attitude, bank;
  1482. var x = this.x, y = this.y, z = this.z, w = this.w;
  1483. switch (order) {
  1484. case "YZX":
  1485. var test = x * y + z * w;
  1486. if (test > 0.499) {
  1487. heading = 2 * Math.atan2(x, w);
  1488. attitude = Math.PI / 2;
  1489. bank = 0;
  1490. }
  1491. if (test < -0.499) {
  1492. heading = -2 * Math.atan2(x, w);
  1493. attitude = -Math.PI / 2;
  1494. bank = 0;
  1495. }
  1496. if (isNaN(heading)) {
  1497. var sqx = x * x;
  1498. var sqy = y * y;
  1499. var sqz = z * z;
  1500. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1501. attitude = Math.asin(2 * test); // attitude
  1502. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1503. }
  1504. break;
  1505. default:
  1506. throw new Error("Euler order " + order + " not supported yet.");
  1507. }
  1508. result.y = heading;
  1509. result.z = attitude;
  1510. result.x = bank;
  1511. return this;
  1512. };
  1513. ;
  1514. Quaternion.prototype.toRotationMatrix = function (result) {
  1515. var xx = this.x * this.x;
  1516. var yy = this.y * this.y;
  1517. var zz = this.z * this.z;
  1518. var xy = this.x * this.y;
  1519. var zw = this.z * this.w;
  1520. var zx = this.z * this.x;
  1521. var yw = this.y * this.w;
  1522. var yz = this.y * this.z;
  1523. var xw = this.x * this.w;
  1524. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1525. result.m[1] = 2.0 * (xy + zw);
  1526. result.m[2] = 2.0 * (zx - yw);
  1527. result.m[3] = 0;
  1528. result.m[4] = 2.0 * (xy - zw);
  1529. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1530. result.m[6] = 2.0 * (yz + xw);
  1531. result.m[7] = 0;
  1532. result.m[8] = 2.0 * (zx + yw);
  1533. result.m[9] = 2.0 * (yz - xw);
  1534. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1535. result.m[11] = 0;
  1536. result.m[12] = 0;
  1537. result.m[13] = 0;
  1538. result.m[14] = 0;
  1539. result.m[15] = 1.0;
  1540. return this;
  1541. };
  1542. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1543. Quaternion.FromRotationMatrixToRef(matrix, this);
  1544. return this;
  1545. };
  1546. // Statics
  1547. Quaternion.FromRotationMatrix = function (matrix) {
  1548. var result = new Quaternion();
  1549. Quaternion.FromRotationMatrixToRef(matrix, result);
  1550. return result;
  1551. };
  1552. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1553. var data = matrix.m;
  1554. var m11 = data[0], m12 = data[4], m13 = data[8];
  1555. var m21 = data[1], m22 = data[5], m23 = data[9];
  1556. var m31 = data[2], m32 = data[6], m33 = data[10];
  1557. var trace = m11 + m22 + m33;
  1558. var s;
  1559. if (trace > 0) {
  1560. s = 0.5 / Math.sqrt(trace + 1.0);
  1561. result.w = 0.25 / s;
  1562. result.x = (m32 - m23) * s;
  1563. result.y = (m13 - m31) * s;
  1564. result.z = (m21 - m12) * s;
  1565. }
  1566. else if (m11 > m22 && m11 > m33) {
  1567. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1568. result.w = (m32 - m23) / s;
  1569. result.x = 0.25 * s;
  1570. result.y = (m12 + m21) / s;
  1571. result.z = (m13 + m31) / s;
  1572. }
  1573. else if (m22 > m33) {
  1574. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1575. result.w = (m13 - m31) / s;
  1576. result.x = (m12 + m21) / s;
  1577. result.y = 0.25 * s;
  1578. result.z = (m23 + m32) / s;
  1579. }
  1580. else {
  1581. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1582. result.w = (m21 - m12) / s;
  1583. result.x = (m13 + m31) / s;
  1584. result.y = (m23 + m32) / s;
  1585. result.z = 0.25 * s;
  1586. }
  1587. };
  1588. Quaternion.Inverse = function (q) {
  1589. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1590. };
  1591. Quaternion.Identity = function () {
  1592. return new Quaternion(0, 0, 0, 1);
  1593. };
  1594. Quaternion.RotationAxis = function (axis, angle) {
  1595. var result = new Quaternion();
  1596. var sin = Math.sin(angle / 2);
  1597. axis.normalize();
  1598. result.w = Math.cos(angle / 2);
  1599. result.x = axis.x * sin;
  1600. result.y = axis.y * sin;
  1601. result.z = axis.z * sin;
  1602. return result;
  1603. };
  1604. Quaternion.FromArray = function (array, offset) {
  1605. if (!offset) {
  1606. offset = 0;
  1607. }
  1608. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1609. };
  1610. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1611. var result = new Quaternion();
  1612. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1613. return result;
  1614. };
  1615. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1616. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1617. var halfRoll = roll * 0.5;
  1618. var halfPitch = pitch * 0.5;
  1619. var halfYaw = yaw * 0.5;
  1620. var sinRoll = Math.sin(halfRoll);
  1621. var cosRoll = Math.cos(halfRoll);
  1622. var sinPitch = Math.sin(halfPitch);
  1623. var cosPitch = Math.cos(halfPitch);
  1624. var sinYaw = Math.sin(halfYaw);
  1625. var cosYaw = Math.cos(halfYaw);
  1626. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1627. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1628. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1629. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1630. };
  1631. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1632. var result = new Quaternion();
  1633. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1634. return result;
  1635. };
  1636. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1637. // Produces a quaternion from Euler angles in the z-x-z orientation
  1638. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1639. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1640. var halfBeta = beta * 0.5;
  1641. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1642. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1643. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1644. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1645. };
  1646. Quaternion.Slerp = function (left, right, amount) {
  1647. var num2;
  1648. var num3;
  1649. var num = amount;
  1650. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1651. var flag = false;
  1652. if (num4 < 0) {
  1653. flag = true;
  1654. num4 = -num4;
  1655. }
  1656. if (num4 > 0.999999) {
  1657. num3 = 1 - num;
  1658. num2 = flag ? -num : num;
  1659. }
  1660. else {
  1661. var num5 = Math.acos(num4);
  1662. var num6 = (1.0 / Math.sin(num5));
  1663. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1664. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1665. }
  1666. 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));
  1667. };
  1668. return Quaternion;
  1669. })();
  1670. BABYLON.Quaternion = Quaternion;
  1671. var Matrix = (function () {
  1672. function Matrix() {
  1673. this.m = new Float32Array(16);
  1674. }
  1675. // Properties
  1676. Matrix.prototype.isIdentity = function () {
  1677. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1678. return false;
  1679. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1680. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1681. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1682. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1683. return false;
  1684. return true;
  1685. };
  1686. Matrix.prototype.determinant = function () {
  1687. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1688. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1689. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1690. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1691. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1692. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1693. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1694. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1695. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1696. };
  1697. // Methods
  1698. Matrix.prototype.toArray = function () {
  1699. return this.m;
  1700. };
  1701. Matrix.prototype.asArray = function () {
  1702. return this.toArray();
  1703. };
  1704. Matrix.prototype.invert = function () {
  1705. this.invertToRef(this);
  1706. return this;
  1707. };
  1708. Matrix.prototype.reset = function () {
  1709. for (var index = 0; index < 16; index++) {
  1710. this.m[index] = 0;
  1711. }
  1712. return this;
  1713. };
  1714. Matrix.prototype.add = function (other) {
  1715. var result = new Matrix();
  1716. this.addToRef(other, result);
  1717. return result;
  1718. };
  1719. Matrix.prototype.addToRef = function (other, result) {
  1720. for (var index = 0; index < 16; index++) {
  1721. result.m[index] = this.m[index] + other.m[index];
  1722. }
  1723. return this;
  1724. };
  1725. Matrix.prototype.addToSelf = function (other) {
  1726. for (var index = 0; index < 16; index++) {
  1727. this.m[index] += other.m[index];
  1728. }
  1729. return this;
  1730. };
  1731. Matrix.prototype.invertToRef = function (other) {
  1732. var l1 = this.m[0];
  1733. var l2 = this.m[1];
  1734. var l3 = this.m[2];
  1735. var l4 = this.m[3];
  1736. var l5 = this.m[4];
  1737. var l6 = this.m[5];
  1738. var l7 = this.m[6];
  1739. var l8 = this.m[7];
  1740. var l9 = this.m[8];
  1741. var l10 = this.m[9];
  1742. var l11 = this.m[10];
  1743. var l12 = this.m[11];
  1744. var l13 = this.m[12];
  1745. var l14 = this.m[13];
  1746. var l15 = this.m[14];
  1747. var l16 = this.m[15];
  1748. var l17 = (l11 * l16) - (l12 * l15);
  1749. var l18 = (l10 * l16) - (l12 * l14);
  1750. var l19 = (l10 * l15) - (l11 * l14);
  1751. var l20 = (l9 * l16) - (l12 * l13);
  1752. var l21 = (l9 * l15) - (l11 * l13);
  1753. var l22 = (l9 * l14) - (l10 * l13);
  1754. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1755. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1756. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1757. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1758. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1759. var l28 = (l7 * l16) - (l8 * l15);
  1760. var l29 = (l6 * l16) - (l8 * l14);
  1761. var l30 = (l6 * l15) - (l7 * l14);
  1762. var l31 = (l5 * l16) - (l8 * l13);
  1763. var l32 = (l5 * l15) - (l7 * l13);
  1764. var l33 = (l5 * l14) - (l6 * l13);
  1765. var l34 = (l7 * l12) - (l8 * l11);
  1766. var l35 = (l6 * l12) - (l8 * l10);
  1767. var l36 = (l6 * l11) - (l7 * l10);
  1768. var l37 = (l5 * l12) - (l8 * l9);
  1769. var l38 = (l5 * l11) - (l7 * l9);
  1770. var l39 = (l5 * l10) - (l6 * l9);
  1771. other.m[0] = l23 * l27;
  1772. other.m[4] = l24 * l27;
  1773. other.m[8] = l25 * l27;
  1774. other.m[12] = l26 * l27;
  1775. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1776. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1777. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1778. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1779. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1780. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1781. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1782. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1783. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1784. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1785. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1786. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1787. return this;
  1788. };
  1789. Matrix.prototype.setTranslation = function (vector3) {
  1790. this.m[12] = vector3.x;
  1791. this.m[13] = vector3.y;
  1792. this.m[14] = vector3.z;
  1793. return this;
  1794. };
  1795. Matrix.prototype.getTranslation = function () {
  1796. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1797. };
  1798. Matrix.prototype.multiply = function (other) {
  1799. var result = new Matrix();
  1800. this.multiplyToRef(other, result);
  1801. return result;
  1802. };
  1803. Matrix.prototype.copyFrom = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] = other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.copyToArray = function (array, offset) {
  1810. if (offset === void 0) { offset = 0; }
  1811. for (var index = 0; index < 16; index++) {
  1812. array[offset + index] = this.m[index];
  1813. }
  1814. return this;
  1815. };
  1816. Matrix.prototype.multiplyToRef = function (other, result) {
  1817. this.multiplyToArray(other, result.m, 0);
  1818. return this;
  1819. };
  1820. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1821. var tm0 = this.m[0];
  1822. var tm1 = this.m[1];
  1823. var tm2 = this.m[2];
  1824. var tm3 = this.m[3];
  1825. var tm4 = this.m[4];
  1826. var tm5 = this.m[5];
  1827. var tm6 = this.m[6];
  1828. var tm7 = this.m[7];
  1829. var tm8 = this.m[8];
  1830. var tm9 = this.m[9];
  1831. var tm10 = this.m[10];
  1832. var tm11 = this.m[11];
  1833. var tm12 = this.m[12];
  1834. var tm13 = this.m[13];
  1835. var tm14 = this.m[14];
  1836. var tm15 = this.m[15];
  1837. var om0 = other.m[0];
  1838. var om1 = other.m[1];
  1839. var om2 = other.m[2];
  1840. var om3 = other.m[3];
  1841. var om4 = other.m[4];
  1842. var om5 = other.m[5];
  1843. var om6 = other.m[6];
  1844. var om7 = other.m[7];
  1845. var om8 = other.m[8];
  1846. var om9 = other.m[9];
  1847. var om10 = other.m[10];
  1848. var om11 = other.m[11];
  1849. var om12 = other.m[12];
  1850. var om13 = other.m[13];
  1851. var om14 = other.m[14];
  1852. var om15 = other.m[15];
  1853. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1854. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1855. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1856. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1857. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1858. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1859. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1860. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1861. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1862. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1863. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1864. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1865. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1866. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1867. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1868. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1869. return this;
  1870. };
  1871. Matrix.prototype.equals = function (value) {
  1872. return value &&
  1873. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1874. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1875. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1876. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1877. };
  1878. Matrix.prototype.clone = function () {
  1879. 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]);
  1880. };
  1881. Matrix.prototype.getClassName = function () {
  1882. return "Matrix";
  1883. };
  1884. Matrix.prototype.getHashCode = function () {
  1885. var hash = this.m[0] || 0;
  1886. for (var i = 1; i < 16; i++) {
  1887. hash = (hash * 397) ^ (this.m[i] || 0);
  1888. }
  1889. return hash;
  1890. };
  1891. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1892. translation.x = this.m[12];
  1893. translation.y = this.m[13];
  1894. translation.z = this.m[14];
  1895. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1896. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1897. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1898. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1899. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1900. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1901. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1902. rotation.x = 0;
  1903. rotation.y = 0;
  1904. rotation.z = 0;
  1905. rotation.w = 1;
  1906. return false;
  1907. }
  1908. var rotationMatrix = Matrix.FromValues(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);
  1909. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1910. return true;
  1911. };
  1912. // Statics
  1913. Matrix.FromArray = function (array, offset) {
  1914. var result = new Matrix();
  1915. if (!offset) {
  1916. offset = 0;
  1917. }
  1918. Matrix.FromArrayToRef(array, offset, result);
  1919. return result;
  1920. };
  1921. Matrix.FromArrayToRef = function (array, offset, result) {
  1922. for (var index = 0; index < 16; index++) {
  1923. result.m[index] = array[index + offset];
  1924. }
  1925. };
  1926. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1927. for (var index = 0; index < 16; index++) {
  1928. result.m[index] = array[index + offset] * scale;
  1929. }
  1930. };
  1931. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1932. result.m[0] = initialM11;
  1933. result.m[1] = initialM12;
  1934. result.m[2] = initialM13;
  1935. result.m[3] = initialM14;
  1936. result.m[4] = initialM21;
  1937. result.m[5] = initialM22;
  1938. result.m[6] = initialM23;
  1939. result.m[7] = initialM24;
  1940. result.m[8] = initialM31;
  1941. result.m[9] = initialM32;
  1942. result.m[10] = initialM33;
  1943. result.m[11] = initialM34;
  1944. result.m[12] = initialM41;
  1945. result.m[13] = initialM42;
  1946. result.m[14] = initialM43;
  1947. result.m[15] = initialM44;
  1948. };
  1949. Matrix.prototype.getRow = function (index) {
  1950. if (index < 0 || index > 3) {
  1951. return null;
  1952. }
  1953. var i = index * 4;
  1954. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1955. };
  1956. Matrix.prototype.setRow = function (index, row) {
  1957. if (index < 0 || index > 3) {
  1958. return this;
  1959. }
  1960. var i = index * 4;
  1961. this.m[i + 0] = row.x;
  1962. this.m[i + 1] = row.y;
  1963. this.m[i + 2] = row.z;
  1964. this.m[i + 3] = row.w;
  1965. return this;
  1966. };
  1967. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1968. var result = new Matrix();
  1969. result.m[0] = initialM11;
  1970. result.m[1] = initialM12;
  1971. result.m[2] = initialM13;
  1972. result.m[3] = initialM14;
  1973. result.m[4] = initialM21;
  1974. result.m[5] = initialM22;
  1975. result.m[6] = initialM23;
  1976. result.m[7] = initialM24;
  1977. result.m[8] = initialM31;
  1978. result.m[9] = initialM32;
  1979. result.m[10] = initialM33;
  1980. result.m[11] = initialM34;
  1981. result.m[12] = initialM41;
  1982. result.m[13] = initialM42;
  1983. result.m[14] = initialM43;
  1984. result.m[15] = initialM44;
  1985. return result;
  1986. };
  1987. Matrix.Compose = function (scale, rotation, translation) {
  1988. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1989. var rotationMatrix = Matrix.Identity();
  1990. rotation.toRotationMatrix(rotationMatrix);
  1991. result = result.multiply(rotationMatrix);
  1992. result.setTranslation(translation);
  1993. return result;
  1994. };
  1995. Matrix.Identity = function () {
  1996. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1997. };
  1998. Matrix.IdentityToRef = function (result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2000. };
  2001. Matrix.Zero = function () {
  2002. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2003. };
  2004. Matrix.RotationX = function (angle) {
  2005. var result = new Matrix();
  2006. Matrix.RotationXToRef(angle, result);
  2007. return result;
  2008. };
  2009. Matrix.Invert = function (source) {
  2010. var result = new Matrix();
  2011. source.invertToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.RotationXToRef = function (angle, result) {
  2015. var s = Math.sin(angle);
  2016. var c = Math.cos(angle);
  2017. result.m[0] = 1.0;
  2018. result.m[15] = 1.0;
  2019. result.m[5] = c;
  2020. result.m[10] = c;
  2021. result.m[9] = -s;
  2022. result.m[6] = s;
  2023. result.m[1] = 0;
  2024. result.m[2] = 0;
  2025. result.m[3] = 0;
  2026. result.m[4] = 0;
  2027. result.m[7] = 0;
  2028. result.m[8] = 0;
  2029. result.m[11] = 0;
  2030. result.m[12] = 0;
  2031. result.m[13] = 0;
  2032. result.m[14] = 0;
  2033. };
  2034. Matrix.RotationY = function (angle) {
  2035. var result = new Matrix();
  2036. Matrix.RotationYToRef(angle, result);
  2037. return result;
  2038. };
  2039. Matrix.RotationYToRef = function (angle, result) {
  2040. var s = Math.sin(angle);
  2041. var c = Math.cos(angle);
  2042. result.m[5] = 1.0;
  2043. result.m[15] = 1.0;
  2044. result.m[0] = c;
  2045. result.m[2] = -s;
  2046. result.m[8] = s;
  2047. result.m[10] = c;
  2048. result.m[1] = 0;
  2049. result.m[3] = 0;
  2050. result.m[4] = 0;
  2051. result.m[6] = 0;
  2052. result.m[7] = 0;
  2053. result.m[9] = 0;
  2054. result.m[11] = 0;
  2055. result.m[12] = 0;
  2056. result.m[13] = 0;
  2057. result.m[14] = 0;
  2058. };
  2059. Matrix.RotationZ = function (angle) {
  2060. var result = new Matrix();
  2061. Matrix.RotationZToRef(angle, result);
  2062. return result;
  2063. };
  2064. Matrix.RotationZToRef = function (angle, result) {
  2065. var s = Math.sin(angle);
  2066. var c = Math.cos(angle);
  2067. result.m[10] = 1.0;
  2068. result.m[15] = 1.0;
  2069. result.m[0] = c;
  2070. result.m[1] = s;
  2071. result.m[4] = -s;
  2072. result.m[5] = c;
  2073. result.m[2] = 0;
  2074. result.m[3] = 0;
  2075. result.m[6] = 0;
  2076. result.m[7] = 0;
  2077. result.m[8] = 0;
  2078. result.m[9] = 0;
  2079. result.m[11] = 0;
  2080. result.m[12] = 0;
  2081. result.m[13] = 0;
  2082. result.m[14] = 0;
  2083. };
  2084. Matrix.RotationAxis = function (axis, angle) {
  2085. var result = Matrix.Zero();
  2086. Matrix.RotationAxisToRef(axis, angle, result);
  2087. return result;
  2088. };
  2089. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2090. var s = Math.sin(-angle);
  2091. var c = Math.cos(-angle);
  2092. var c1 = 1 - c;
  2093. axis.normalize();
  2094. result.m[0] = (axis.x * axis.x) * c1 + c;
  2095. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2096. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2097. result.m[3] = 0.0;
  2098. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2099. result.m[5] = (axis.y * axis.y) * c1 + c;
  2100. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2101. result.m[7] = 0.0;
  2102. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2103. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2104. result.m[10] = (axis.z * axis.z) * c1 + c;
  2105. result.m[11] = 0.0;
  2106. result.m[15] = 1.0;
  2107. };
  2108. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2109. var result = new Matrix();
  2110. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2111. return result;
  2112. };
  2113. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2114. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2115. this._tempQuaternion.toRotationMatrix(result);
  2116. };
  2117. Matrix.Scaling = function (x, y, z) {
  2118. var result = Matrix.Zero();
  2119. Matrix.ScalingToRef(x, y, z, result);
  2120. return result;
  2121. };
  2122. Matrix.ScalingToRef = function (x, y, z, result) {
  2123. result.m[0] = x;
  2124. result.m[1] = 0;
  2125. result.m[2] = 0;
  2126. result.m[3] = 0;
  2127. result.m[4] = 0;
  2128. result.m[5] = y;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[8] = 0;
  2132. result.m[9] = 0;
  2133. result.m[10] = z;
  2134. result.m[11] = 0;
  2135. result.m[12] = 0;
  2136. result.m[13] = 0;
  2137. result.m[14] = 0;
  2138. result.m[15] = 1.0;
  2139. };
  2140. Matrix.Translation = function (x, y, z) {
  2141. var result = Matrix.Identity();
  2142. Matrix.TranslationToRef(x, y, z, result);
  2143. return result;
  2144. };
  2145. Matrix.TranslationToRef = function (x, y, z, result) {
  2146. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2147. };
  2148. Matrix.Lerp = function (startValue, endValue, gradient) {
  2149. var result = Matrix.Zero();
  2150. for (var index = 0; index < 16; index++) {
  2151. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2152. }
  2153. return result;
  2154. };
  2155. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2156. var startScale = new Vector3(0, 0, 0);
  2157. var startRotation = new Quaternion();
  2158. var startTranslation = new Vector3(0, 0, 0);
  2159. startValue.decompose(startScale, startRotation, startTranslation);
  2160. var endScale = new Vector3(0, 0, 0);
  2161. var endRotation = new Quaternion();
  2162. var endTranslation = new Vector3(0, 0, 0);
  2163. endValue.decompose(endScale, endRotation, endTranslation);
  2164. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2165. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2166. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2167. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2168. };
  2169. Matrix.LookAtLH = function (eye, target, up) {
  2170. var result = Matrix.Zero();
  2171. Matrix.LookAtLHToRef(eye, target, up, result);
  2172. return result;
  2173. };
  2174. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2175. // Z axis
  2176. target.subtractToRef(eye, this._zAxis);
  2177. this._zAxis.normalize();
  2178. // X axis
  2179. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2180. if (this._xAxis.lengthSquared() === 0) {
  2181. this._xAxis.x = 1.0;
  2182. }
  2183. else {
  2184. this._xAxis.normalize();
  2185. }
  2186. // Y axis
  2187. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2188. this._yAxis.normalize();
  2189. // Eye angles
  2190. var ex = -Vector3.Dot(this._xAxis, eye);
  2191. var ey = -Vector3.Dot(this._yAxis, eye);
  2192. var ez = -Vector3.Dot(this._zAxis, eye);
  2193. 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);
  2194. };
  2195. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2196. var matrix = Matrix.Zero();
  2197. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2198. return matrix;
  2199. };
  2200. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2201. var hw = 2.0 / width;
  2202. var hh = 2.0 / height;
  2203. var id = 1.0 / (zfar - znear);
  2204. var nid = znear / (znear - zfar);
  2205. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2206. };
  2207. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2208. var matrix = Matrix.Zero();
  2209. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2210. return matrix;
  2211. };
  2212. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2213. result.m[0] = 2.0 / (right - left);
  2214. result.m[1] = result.m[2] = result.m[3] = 0;
  2215. result.m[5] = 2.0 / (top - bottom);
  2216. result.m[4] = result.m[6] = result.m[7] = 0;
  2217. result.m[10] = -1.0 / (znear - zfar);
  2218. result.m[8] = result.m[9] = result.m[11] = 0;
  2219. result.m[12] = (left + right) / (left - right);
  2220. result.m[13] = (top + bottom) / (bottom - top);
  2221. result.m[14] = znear / (znear - zfar);
  2222. result.m[15] = 1.0;
  2223. };
  2224. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2225. var matrix = Matrix.Zero();
  2226. matrix.m[0] = (2.0 * znear) / width;
  2227. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2228. matrix.m[5] = (2.0 * znear) / height;
  2229. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2230. matrix.m[10] = -zfar / (znear - zfar);
  2231. matrix.m[8] = matrix.m[9] = 0.0;
  2232. matrix.m[11] = 1.0;
  2233. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2234. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2235. return matrix;
  2236. };
  2237. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2238. var matrix = Matrix.Zero();
  2239. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2240. return matrix;
  2241. };
  2242. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2243. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2244. var tan = 1.0 / (Math.tan(fov * 0.5));
  2245. if (isVerticalFovFixed) {
  2246. result.m[0] = tan / aspect;
  2247. }
  2248. else {
  2249. result.m[0] = tan;
  2250. }
  2251. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2252. if (isVerticalFovFixed) {
  2253. result.m[5] = tan;
  2254. }
  2255. else {
  2256. result.m[5] = tan * aspect;
  2257. }
  2258. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2259. result.m[8] = result.m[9] = 0.0;
  2260. result.m[10] = -zfar / (znear - zfar);
  2261. result.m[11] = 1.0;
  2262. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2263. result.m[14] = (znear * zfar) / (znear - zfar);
  2264. };
  2265. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2266. var cw = viewport.width;
  2267. var ch = viewport.height;
  2268. var cx = viewport.x;
  2269. var cy = viewport.y;
  2270. 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);
  2271. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2272. };
  2273. Matrix.GetAsMatrix2x2 = function (matrix) {
  2274. return new Float32Array([
  2275. matrix.m[0], matrix.m[1],
  2276. matrix.m[4], matrix.m[5]
  2277. ]);
  2278. };
  2279. Matrix.GetAsMatrix3x3 = function (matrix) {
  2280. return new Float32Array([
  2281. matrix.m[0], matrix.m[1], matrix.m[2],
  2282. matrix.m[4], matrix.m[5], matrix.m[6],
  2283. matrix.m[8], matrix.m[9], matrix.m[10]
  2284. ]);
  2285. };
  2286. Matrix.Transpose = function (matrix) {
  2287. var result = new Matrix();
  2288. result.m[0] = matrix.m[0];
  2289. result.m[1] = matrix.m[4];
  2290. result.m[2] = matrix.m[8];
  2291. result.m[3] = matrix.m[12];
  2292. result.m[4] = matrix.m[1];
  2293. result.m[5] = matrix.m[5];
  2294. result.m[6] = matrix.m[9];
  2295. result.m[7] = matrix.m[13];
  2296. result.m[8] = matrix.m[2];
  2297. result.m[9] = matrix.m[6];
  2298. result.m[10] = matrix.m[10];
  2299. result.m[11] = matrix.m[14];
  2300. result.m[12] = matrix.m[3];
  2301. result.m[13] = matrix.m[7];
  2302. result.m[14] = matrix.m[11];
  2303. result.m[15] = matrix.m[15];
  2304. return result;
  2305. };
  2306. Matrix.Reflection = function (plane) {
  2307. var matrix = new Matrix();
  2308. Matrix.ReflectionToRef(plane, matrix);
  2309. return matrix;
  2310. };
  2311. Matrix.ReflectionToRef = function (plane, result) {
  2312. plane.normalize();
  2313. var x = plane.normal.x;
  2314. var y = plane.normal.y;
  2315. var z = plane.normal.z;
  2316. var temp = -2 * x;
  2317. var temp2 = -2 * y;
  2318. var temp3 = -2 * z;
  2319. result.m[0] = (temp * x) + 1;
  2320. result.m[1] = temp2 * x;
  2321. result.m[2] = temp3 * x;
  2322. result.m[3] = 0.0;
  2323. result.m[4] = temp * y;
  2324. result.m[5] = (temp2 * y) + 1;
  2325. result.m[6] = temp3 * y;
  2326. result.m[7] = 0.0;
  2327. result.m[8] = temp * z;
  2328. result.m[9] = temp2 * z;
  2329. result.m[10] = (temp3 * z) + 1;
  2330. result.m[11] = 0.0;
  2331. result.m[12] = temp * plane.d;
  2332. result.m[13] = temp2 * plane.d;
  2333. result.m[14] = temp3 * plane.d;
  2334. result.m[15] = 1.0;
  2335. };
  2336. Matrix._tempQuaternion = new Quaternion();
  2337. Matrix._xAxis = Vector3.Zero();
  2338. Matrix._yAxis = Vector3.Zero();
  2339. Matrix._zAxis = Vector3.Zero();
  2340. return Matrix;
  2341. })();
  2342. BABYLON.Matrix = Matrix;
  2343. var Plane = (function () {
  2344. function Plane(a, b, c, d) {
  2345. this.normal = new Vector3(a, b, c);
  2346. this.d = d;
  2347. }
  2348. Plane.prototype.asArray = function () {
  2349. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2350. };
  2351. // Methods
  2352. Plane.prototype.clone = function () {
  2353. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2354. };
  2355. Plane.prototype.getClassName = function () {
  2356. return "Plane";
  2357. };
  2358. Plane.prototype.getHashCode = function () {
  2359. var hash = this.normal.getHashCode();
  2360. hash = (hash * 397) ^ (this.d || 0);
  2361. return hash;
  2362. };
  2363. Plane.prototype.normalize = function () {
  2364. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2365. var magnitude = 0;
  2366. if (norm !== 0) {
  2367. magnitude = 1.0 / norm;
  2368. }
  2369. this.normal.x *= magnitude;
  2370. this.normal.y *= magnitude;
  2371. this.normal.z *= magnitude;
  2372. this.d *= magnitude;
  2373. return this;
  2374. };
  2375. Plane.prototype.transform = function (transformation) {
  2376. var transposedMatrix = Matrix.Transpose(transformation);
  2377. var x = this.normal.x;
  2378. var y = this.normal.y;
  2379. var z = this.normal.z;
  2380. var d = this.d;
  2381. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2382. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2383. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2384. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2385. return new Plane(normalX, normalY, normalZ, finalD);
  2386. };
  2387. Plane.prototype.dotCoordinate = function (point) {
  2388. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2389. };
  2390. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2391. var x1 = point2.x - point1.x;
  2392. var y1 = point2.y - point1.y;
  2393. var z1 = point2.z - point1.z;
  2394. var x2 = point3.x - point1.x;
  2395. var y2 = point3.y - point1.y;
  2396. var z2 = point3.z - point1.z;
  2397. var yz = (y1 * z2) - (z1 * y2);
  2398. var xz = (z1 * x2) - (x1 * z2);
  2399. var xy = (x1 * y2) - (y1 * x2);
  2400. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2401. var invPyth;
  2402. if (pyth !== 0) {
  2403. invPyth = 1.0 / pyth;
  2404. }
  2405. else {
  2406. invPyth = 0;
  2407. }
  2408. this.normal.x = yz * invPyth;
  2409. this.normal.y = xz * invPyth;
  2410. this.normal.z = xy * invPyth;
  2411. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2412. return this;
  2413. };
  2414. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2415. var dot = Vector3.Dot(this.normal, direction);
  2416. return (dot <= epsilon);
  2417. };
  2418. Plane.prototype.signedDistanceTo = function (point) {
  2419. return Vector3.Dot(point, this.normal) + this.d;
  2420. };
  2421. // Statics
  2422. Plane.FromArray = function (array) {
  2423. return new Plane(array[0], array[1], array[2], array[3]);
  2424. };
  2425. Plane.FromPoints = function (point1, point2, point3) {
  2426. var result = new Plane(0, 0, 0, 0);
  2427. result.copyFromPoints(point1, point2, point3);
  2428. return result;
  2429. };
  2430. Plane.FromPositionAndNormal = function (origin, normal) {
  2431. var result = new Plane(0, 0, 0, 0);
  2432. normal.normalize();
  2433. result.normal = normal;
  2434. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2435. return result;
  2436. };
  2437. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2438. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2439. return Vector3.Dot(point, normal) + d;
  2440. };
  2441. return Plane;
  2442. })();
  2443. BABYLON.Plane = Plane;
  2444. var Viewport = (function () {
  2445. function Viewport(x, y, width, height) {
  2446. this.x = x;
  2447. this.y = y;
  2448. this.width = width;
  2449. this.height = height;
  2450. }
  2451. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2452. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2453. };
  2454. return Viewport;
  2455. })();
  2456. BABYLON.Viewport = Viewport;
  2457. var Frustum = (function () {
  2458. function Frustum() {
  2459. }
  2460. Frustum.GetPlanes = function (transform) {
  2461. var frustumPlanes = [];
  2462. for (var index = 0; index < 6; index++) {
  2463. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2464. }
  2465. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2466. return frustumPlanes;
  2467. };
  2468. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2469. // Near
  2470. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2471. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2472. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2473. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2474. frustumPlanes[0].normalize();
  2475. // Far
  2476. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2477. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2478. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2479. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2480. frustumPlanes[1].normalize();
  2481. // Left
  2482. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2483. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2484. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2485. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2486. frustumPlanes[2].normalize();
  2487. // Right
  2488. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2489. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2490. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2491. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2492. frustumPlanes[3].normalize();
  2493. // Top
  2494. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2495. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2496. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2497. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2498. frustumPlanes[4].normalize();
  2499. // Bottom
  2500. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2501. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2502. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2503. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2504. frustumPlanes[5].normalize();
  2505. };
  2506. return Frustum;
  2507. })();
  2508. BABYLON.Frustum = Frustum;
  2509. (function (Space) {
  2510. Space[Space["LOCAL"] = 0] = "LOCAL";
  2511. Space[Space["WORLD"] = 1] = "WORLD";
  2512. })(BABYLON.Space || (BABYLON.Space = {}));
  2513. var Space = BABYLON.Space;
  2514. var Axis = (function () {
  2515. function Axis() {
  2516. }
  2517. Axis.X = new Vector3(1, 0, 0);
  2518. Axis.Y = new Vector3(0, 1, 0);
  2519. Axis.Z = new Vector3(0, 0, 1);
  2520. return Axis;
  2521. })();
  2522. BABYLON.Axis = Axis;
  2523. ;
  2524. var BezierCurve = (function () {
  2525. function BezierCurve() {
  2526. }
  2527. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2528. // Extract X (which is equal to time here)
  2529. var f0 = 1 - 3 * x2 + 3 * x1;
  2530. var f1 = 3 * x2 - 6 * x1;
  2531. var f2 = 3 * x1;
  2532. var refinedT = t;
  2533. for (var i = 0; i < 5; i++) {
  2534. var refinedT2 = refinedT * refinedT;
  2535. var refinedT3 = refinedT2 * refinedT;
  2536. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2537. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2538. refinedT -= (x - t) * slope;
  2539. refinedT = Math.min(1, Math.max(0, refinedT));
  2540. }
  2541. // Resolve cubic bezier for the given x
  2542. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2543. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2544. Math.pow(refinedT, 3);
  2545. };
  2546. return BezierCurve;
  2547. })();
  2548. BABYLON.BezierCurve = BezierCurve;
  2549. (function (Orientation) {
  2550. Orientation[Orientation["CW"] = 0] = "CW";
  2551. Orientation[Orientation["CCW"] = 1] = "CCW";
  2552. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2553. var Orientation = BABYLON.Orientation;
  2554. var Angle = (function () {
  2555. function Angle(radians) {
  2556. var _this = this;
  2557. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2558. this.radians = function () { return _this._radians; };
  2559. this._radians = radians;
  2560. if (this._radians < 0)
  2561. this._radians += (2 * Math.PI);
  2562. }
  2563. Angle.BetweenTwoPoints = function (a, b) {
  2564. var delta = b.subtract(a);
  2565. var theta = Math.atan2(delta.y, delta.x);
  2566. return new Angle(theta);
  2567. };
  2568. Angle.FromRadians = function (radians) {
  2569. return new Angle(radians);
  2570. };
  2571. Angle.FromDegrees = function (degrees) {
  2572. return new Angle(degrees * Math.PI / 180);
  2573. };
  2574. return Angle;
  2575. })();
  2576. BABYLON.Angle = Angle;
  2577. var Arc2 = (function () {
  2578. function Arc2(startPoint, midPoint, endPoint) {
  2579. this.startPoint = startPoint;
  2580. this.midPoint = midPoint;
  2581. this.endPoint = endPoint;
  2582. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2583. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2584. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2585. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2586. 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);
  2587. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2588. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2589. var a1 = this.startAngle.degrees();
  2590. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2591. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2592. // angles correction
  2593. if (a2 - a1 > +180.0)
  2594. a2 -= 360.0;
  2595. if (a2 - a1 < -180.0)
  2596. a2 += 360.0;
  2597. if (a3 - a2 > +180.0)
  2598. a3 -= 360.0;
  2599. if (a3 - a2 < -180.0)
  2600. a3 += 360.0;
  2601. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2602. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2603. }
  2604. return Arc2;
  2605. })();
  2606. BABYLON.Arc2 = Arc2;
  2607. var Path2 = (function () {
  2608. function Path2(x, y) {
  2609. this._points = new Array();
  2610. this._length = 0;
  2611. this.closed = false;
  2612. this._points.push(new Vector2(x, y));
  2613. }
  2614. Path2.prototype.addLineTo = function (x, y) {
  2615. if (closed) {
  2616. //Tools.Error("cannot add lines to closed paths");
  2617. return this;
  2618. }
  2619. var newPoint = new Vector2(x, y);
  2620. var previousPoint = this._points[this._points.length - 1];
  2621. this._points.push(newPoint);
  2622. this._length += newPoint.subtract(previousPoint).length();
  2623. return this;
  2624. };
  2625. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2626. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2627. if (closed) {
  2628. //Tools.Error("cannot add arcs to closed paths");
  2629. return this;
  2630. }
  2631. var startPoint = this._points[this._points.length - 1];
  2632. var midPoint = new Vector2(midX, midY);
  2633. var endPoint = new Vector2(endX, endY);
  2634. var arc = new Arc2(startPoint, midPoint, endPoint);
  2635. var increment = arc.angle.radians() / numberOfSegments;
  2636. if (arc.orientation === Orientation.CW)
  2637. increment *= -1;
  2638. var currentAngle = arc.startAngle.radians() + increment;
  2639. for (var i = 0; i < numberOfSegments; i++) {
  2640. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2641. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2642. this.addLineTo(x, y);
  2643. currentAngle += increment;
  2644. }
  2645. return this;
  2646. };
  2647. Path2.prototype.close = function () {
  2648. this.closed = true;
  2649. return this;
  2650. };
  2651. Path2.prototype.length = function () {
  2652. var result = this._length;
  2653. if (!this.closed) {
  2654. var lastPoint = this._points[this._points.length - 1];
  2655. var firstPoint = this._points[0];
  2656. result += (firstPoint.subtract(lastPoint).length());
  2657. }
  2658. return result;
  2659. };
  2660. Path2.prototype.getPoints = function () {
  2661. return this._points;
  2662. };
  2663. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2664. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2665. //Tools.Error("normalized length position should be between 0 and 1.");
  2666. return Vector2.Zero();
  2667. }
  2668. var lengthPosition = normalizedLengthPosition * this.length();
  2669. var previousOffset = 0;
  2670. for (var i = 0; i < this._points.length; i++) {
  2671. var j = (i + 1) % this._points.length;
  2672. var a = this._points[i];
  2673. var b = this._points[j];
  2674. var bToA = b.subtract(a);
  2675. var nextOffset = (bToA.length() + previousOffset);
  2676. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2677. var dir = bToA.normalize();
  2678. var localOffset = lengthPosition - previousOffset;
  2679. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2680. }
  2681. previousOffset = nextOffset;
  2682. }
  2683. //Tools.Error("internal error");
  2684. return Vector2.Zero();
  2685. };
  2686. Path2.StartingAt = function (x, y) {
  2687. return new Path2(x, y);
  2688. };
  2689. return Path2;
  2690. })();
  2691. BABYLON.Path2 = Path2;
  2692. var Path3D = (function () {
  2693. /**
  2694. * new Path3D(path, normal, raw)
  2695. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2696. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2697. * path : an array of Vector3, the curve axis of the Path3D
  2698. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2699. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2700. */
  2701. function Path3D(path, firstNormal, raw) {
  2702. this.path = path;
  2703. this._curve = new Array();
  2704. this._distances = new Array();
  2705. this._tangents = new Array();
  2706. this._normals = new Array();
  2707. this._binormals = new Array();
  2708. for (var p = 0; p < path.length; p++) {
  2709. this._curve[p] = path[p].clone(); // hard copy
  2710. }
  2711. this._raw = raw || false;
  2712. this._compute(firstNormal);
  2713. }
  2714. /**
  2715. * Returns the Path3D array of successive Vector3 designing its curve.
  2716. */
  2717. Path3D.prototype.getCurve = function () {
  2718. return this._curve;
  2719. };
  2720. /**
  2721. * Returns an array populated with tangent vectors on each Path3D curve point.
  2722. */
  2723. Path3D.prototype.getTangents = function () {
  2724. return this._tangents;
  2725. };
  2726. /**
  2727. * Returns an array populated with normal vectors on each Path3D curve point.
  2728. */
  2729. Path3D.prototype.getNormals = function () {
  2730. return this._normals;
  2731. };
  2732. /**
  2733. * Returns an array populated with binormal vectors on each Path3D curve point.
  2734. */
  2735. Path3D.prototype.getBinormals = function () {
  2736. return this._binormals;
  2737. };
  2738. /**
  2739. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2740. */
  2741. Path3D.prototype.getDistances = function () {
  2742. return this._distances;
  2743. };
  2744. /**
  2745. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2746. * Returns the same object updated.
  2747. */
  2748. Path3D.prototype.update = function (path, firstNormal) {
  2749. for (var p = 0; p < path.length; p++) {
  2750. this._curve[p].x = path[p].x;
  2751. this._curve[p].y = path[p].y;
  2752. this._curve[p].z = path[p].z;
  2753. }
  2754. this._compute(firstNormal);
  2755. return this;
  2756. };
  2757. // private function compute() : computes tangents, normals and binormals
  2758. Path3D.prototype._compute = function (firstNormal) {
  2759. var l = this._curve.length;
  2760. // first and last tangents
  2761. this._tangents[0] = this._getFirstNonNullVector(0);
  2762. if (!this._raw) {
  2763. this._tangents[0].normalize();
  2764. }
  2765. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2766. if (!this._raw) {
  2767. this._tangents[l - 1].normalize();
  2768. }
  2769. // normals and binormals at first point : arbitrary vector with _normalVector()
  2770. var tg0 = this._tangents[0];
  2771. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2772. this._normals[0] = pp0;
  2773. if (!this._raw) {
  2774. this._normals[0].normalize();
  2775. }
  2776. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2777. if (!this._raw) {
  2778. this._binormals[0].normalize();
  2779. }
  2780. this._distances[0] = 0;
  2781. // normals and binormals : next points
  2782. var prev; // previous vector (segment)
  2783. var cur; // current vector (segment)
  2784. var curTang; // current tangent
  2785. // previous normal
  2786. var prevBinor; // previous binormal
  2787. for (var i = 1; i < l; i++) {
  2788. // tangents
  2789. prev = this._getLastNonNullVector(i);
  2790. if (i < l - 1) {
  2791. cur = this._getFirstNonNullVector(i);
  2792. this._tangents[i] = prev.add(cur);
  2793. this._tangents[i].normalize();
  2794. }
  2795. this._distances[i] = this._distances[i - 1] + prev.length();
  2796. // normals and binormals
  2797. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2798. curTang = this._tangents[i];
  2799. prevBinor = this._binormals[i - 1];
  2800. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2801. if (!this._raw) {
  2802. this._normals[i].normalize();
  2803. }
  2804. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2805. if (!this._raw) {
  2806. this._binormals[i].normalize();
  2807. }
  2808. }
  2809. };
  2810. // private function getFirstNonNullVector(index)
  2811. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2812. Path3D.prototype._getFirstNonNullVector = function (index) {
  2813. var i = 1;
  2814. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2815. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2816. i++;
  2817. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2818. }
  2819. return nNVector;
  2820. };
  2821. // private function getLastNonNullVector(index)
  2822. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2823. Path3D.prototype._getLastNonNullVector = function (index) {
  2824. var i = 1;
  2825. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2826. while (nLVector.length() === 0 && index > i + 1) {
  2827. i++;
  2828. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2829. }
  2830. return nLVector;
  2831. };
  2832. // private function normalVector(v0, vt, va) :
  2833. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2834. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2835. Path3D.prototype._normalVector = function (v0, vt, va) {
  2836. var normal0;
  2837. if (va === undefined || va === null) {
  2838. var point;
  2839. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2840. point = new Vector3(0, -1, 0);
  2841. }
  2842. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2843. point = new Vector3(1, 0, 0);
  2844. }
  2845. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2846. point = new Vector3(0, 0, 1);
  2847. }
  2848. normal0 = Vector3.Cross(vt, point);
  2849. }
  2850. else {
  2851. normal0 = Vector3.Cross(vt, va);
  2852. Vector3.CrossToRef(normal0, vt, normal0);
  2853. }
  2854. normal0.normalize();
  2855. return normal0;
  2856. };
  2857. return Path3D;
  2858. })();
  2859. BABYLON.Path3D = Path3D;
  2860. var Curve3 = (function () {
  2861. /**
  2862. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2863. * A Curve3 is designed from a series of successive Vector3.
  2864. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2865. */
  2866. function Curve3(points) {
  2867. this._length = 0;
  2868. this._points = points;
  2869. this._length = this._computeLength(points);
  2870. }
  2871. /**
  2872. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2873. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2874. * @param v1 (Vector3) the control point
  2875. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2876. * @param nbPoints (integer) the wanted number of points in the curve
  2877. */
  2878. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2879. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2) {
  2882. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. 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)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. /**
  2891. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2892. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2893. * @param v1 (Vector3) the first control point
  2894. * @param v2 (Vector3) the second control point
  2895. * @param v3 (Vector3) the end point of the Cubic Bezier
  2896. * @param nbPoints (integer) the wanted number of points in the curve
  2897. */
  2898. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2899. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2900. var bez = new Array();
  2901. var equation = function (t, val0, val1, val2, val3) {
  2902. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2903. return res;
  2904. };
  2905. for (var i = 0; i <= nbPoints; i++) {
  2906. 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)));
  2907. }
  2908. return new Curve3(bez);
  2909. };
  2910. /**
  2911. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2912. * @param p1 (Vector3) the origin point of the Hermite Spline
  2913. * @param t1 (Vector3) the tangent vector at the origin point
  2914. * @param p2 (Vector3) the end point of the Hermite Spline
  2915. * @param t2 (Vector3) the tangent vector at the end point
  2916. * @param nbPoints (integer) the wanted number of points in the curve
  2917. */
  2918. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2919. var hermite = new Array();
  2920. var step = 1 / nbPoints;
  2921. for (var i = 0; i <= nbPoints; i++) {
  2922. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2923. }
  2924. return new Curve3(hermite);
  2925. };
  2926. /**
  2927. * Returns the Curve3 stored array of successive Vector3
  2928. */
  2929. Curve3.prototype.getPoints = function () {
  2930. return this._points;
  2931. };
  2932. /**
  2933. * Returns the computed length (float) of the curve.
  2934. */
  2935. Curve3.prototype.length = function () {
  2936. return this._length;
  2937. };
  2938. /**
  2939. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2940. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2941. * curveA and curveB keep unchanged.
  2942. */
  2943. Curve3.prototype.continue = function (curve) {
  2944. var lastPoint = this._points[this._points.length - 1];
  2945. var continuedPoints = this._points.slice();
  2946. var curvePoints = curve.getPoints();
  2947. for (var i = 1; i < curvePoints.length; i++) {
  2948. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2949. }
  2950. var continuedCurve = new Curve3(continuedPoints);
  2951. return continuedCurve;
  2952. };
  2953. Curve3.prototype._computeLength = function (path) {
  2954. var l = 0;
  2955. for (var i = 1; i < path.length; i++) {
  2956. l += (path[i].subtract(path[i - 1])).length();
  2957. }
  2958. return l;
  2959. };
  2960. return Curve3;
  2961. })();
  2962. BABYLON.Curve3 = Curve3;
  2963. // SphericalHarmonics
  2964. var SphericalHarmonics = (function () {
  2965. function SphericalHarmonics() {
  2966. this.L00 = Vector3.Zero();
  2967. this.L1_1 = Vector3.Zero();
  2968. this.L10 = Vector3.Zero();
  2969. this.L11 = Vector3.Zero();
  2970. this.L2_2 = Vector3.Zero();
  2971. this.L2_1 = Vector3.Zero();
  2972. this.L20 = Vector3.Zero();
  2973. this.L21 = Vector3.Zero();
  2974. this.L22 = Vector3.Zero();
  2975. }
  2976. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2977. var colorVector = new Vector3(color.r, color.g, color.b);
  2978. var c = colorVector.scale(deltaSolidAngle);
  2979. this.L00 = this.L00.add(c.scale(0.282095));
  2980. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2981. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2982. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2983. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2984. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2985. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2986. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2987. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2988. };
  2989. SphericalHarmonics.prototype.scale = function (scale) {
  2990. this.L00 = this.L00.scale(scale);
  2991. this.L1_1 = this.L1_1.scale(scale);
  2992. this.L10 = this.L10.scale(scale);
  2993. this.L11 = this.L11.scale(scale);
  2994. this.L2_2 = this.L2_2.scale(scale);
  2995. this.L2_1 = this.L2_1.scale(scale);
  2996. this.L20 = this.L20.scale(scale);
  2997. this.L21 = this.L21.scale(scale);
  2998. this.L22 = this.L22.scale(scale);
  2999. };
  3000. return SphericalHarmonics;
  3001. })();
  3002. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3003. // SphericalPolynomial
  3004. var SphericalPolynomial = (function () {
  3005. function SphericalPolynomial() {
  3006. this.x = Vector3.Zero();
  3007. this.y = Vector3.Zero();
  3008. this.z = Vector3.Zero();
  3009. this.xx = Vector3.Zero();
  3010. this.yy = Vector3.Zero();
  3011. this.zz = Vector3.Zero();
  3012. this.xy = Vector3.Zero();
  3013. this.yz = Vector3.Zero();
  3014. this.zx = Vector3.Zero();
  3015. }
  3016. SphericalPolynomial.prototype.addAmbient = function (color) {
  3017. var colorVector = new Vector3(color.r, color.g, color.b);
  3018. this.xx = this.xx.add(colorVector);
  3019. this.yy = this.yy.add(colorVector);
  3020. this.zz = this.zz.add(colorVector);
  3021. };
  3022. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3023. var result = new SphericalPolynomial();
  3024. result.x = harmonics.L11.scale(1.02333);
  3025. result.y = harmonics.L1_1.scale(1.02333);
  3026. result.z = harmonics.L10.scale(1.02333);
  3027. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3028. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3029. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3030. result.yz = harmonics.L2_1.scale(0.858086);
  3031. result.zx = harmonics.L21.scale(0.858086);
  3032. result.xy = harmonics.L2_2.scale(0.858086);
  3033. return result;
  3034. };
  3035. return SphericalPolynomial;
  3036. })();
  3037. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3038. // Vertex formats
  3039. var PositionNormalVertex = (function () {
  3040. function PositionNormalVertex(position, normal) {
  3041. if (position === void 0) { position = Vector3.Zero(); }
  3042. if (normal === void 0) { normal = Vector3.Up(); }
  3043. this.position = position;
  3044. this.normal = normal;
  3045. }
  3046. PositionNormalVertex.prototype.clone = function () {
  3047. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3048. };
  3049. return PositionNormalVertex;
  3050. })();
  3051. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3052. var PositionNormalTextureVertex = (function () {
  3053. function PositionNormalTextureVertex(position, normal, uv) {
  3054. if (position === void 0) { position = Vector3.Zero(); }
  3055. if (normal === void 0) { normal = Vector3.Up(); }
  3056. if (uv === void 0) { uv = Vector2.Zero(); }
  3057. this.position = position;
  3058. this.normal = normal;
  3059. this.uv = uv;
  3060. }
  3061. PositionNormalTextureVertex.prototype.clone = function () {
  3062. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3063. };
  3064. return PositionNormalTextureVertex;
  3065. })();
  3066. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3067. // Temporary pre-allocated objects for engine internal use
  3068. // usage in any internal function :
  3069. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3070. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3071. var Tmp = (function () {
  3072. function Tmp() {
  3073. }
  3074. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3075. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3076. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3077. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3078. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3079. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3080. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3081. Matrix.Zero(), Matrix.Zero(),
  3082. Matrix.Zero(), Matrix.Zero(),
  3083. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3084. return Tmp;
  3085. })();
  3086. BABYLON.Tmp = Tmp;
  3087. })(BABYLON || (BABYLON = {}));
  3088. var BABYLON;
  3089. (function (BABYLON) {
  3090. function generateSerializableMember(type, sourceName) {
  3091. return function (target, propertyKey) {
  3092. if (!target.__serializableMembers) {
  3093. target.__serializableMembers = {};
  3094. }
  3095. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3096. };
  3097. }
  3098. function serialize(sourceName) {
  3099. return generateSerializableMember(0, sourceName); // value member
  3100. }
  3101. BABYLON.serialize = serialize;
  3102. function serializeAsTexture(sourceName) {
  3103. return generateSerializableMember(1, sourceName); // texture member
  3104. }
  3105. BABYLON.serializeAsTexture = serializeAsTexture;
  3106. function serializeAsColor3(sourceName) {
  3107. return generateSerializableMember(2, sourceName); // color3 member
  3108. }
  3109. BABYLON.serializeAsColor3 = serializeAsColor3;
  3110. function serializeAsFresnelParameters(sourceName) {
  3111. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3112. }
  3113. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3114. function serializeAsVector2(sourceName) {
  3115. return generateSerializableMember(4, sourceName); // vector2 member
  3116. }
  3117. BABYLON.serializeAsVector2 = serializeAsVector2;
  3118. function serializeAsVector3(sourceName) {
  3119. return generateSerializableMember(5, sourceName); // vector3 member
  3120. }
  3121. BABYLON.serializeAsVector3 = serializeAsVector3;
  3122. function serializeAsMeshReference(sourceName) {
  3123. return generateSerializableMember(6, sourceName); // mesh reference member
  3124. }
  3125. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3126. var SerializationHelper = (function () {
  3127. function SerializationHelper() {
  3128. }
  3129. SerializationHelper.Serialize = function (entity, serializationObject) {
  3130. if (!serializationObject) {
  3131. serializationObject = {};
  3132. }
  3133. // Tags
  3134. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3135. // Properties
  3136. for (var property in entity.__serializableMembers) {
  3137. var propertyDescriptor = entity.__serializableMembers[property];
  3138. var targetPropertyName = propertyDescriptor.sourceName || property;
  3139. var propertyType = propertyDescriptor.type;
  3140. var sourceProperty = entity[property];
  3141. if (sourceProperty !== undefined && sourceProperty !== null) {
  3142. switch (propertyType) {
  3143. case 0:
  3144. serializationObject[targetPropertyName] = sourceProperty;
  3145. break;
  3146. case 1:
  3147. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3148. break;
  3149. case 2:
  3150. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3151. break;
  3152. case 3:
  3153. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3154. break;
  3155. case 4:
  3156. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3157. break;
  3158. case 5:
  3159. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3160. break;
  3161. case 6:
  3162. serializationObject[targetPropertyName] = sourceProperty.id;
  3163. break;
  3164. }
  3165. }
  3166. }
  3167. return serializationObject;
  3168. };
  3169. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3170. var destination = creationFunction();
  3171. // Tags
  3172. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3173. // Properties
  3174. for (var property in destination.__serializableMembers) {
  3175. var propertyDescriptor = destination.__serializableMembers[property];
  3176. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3177. var propertyType = propertyDescriptor.type;
  3178. if (sourceProperty !== undefined && sourceProperty !== null) {
  3179. switch (propertyType) {
  3180. case 0:
  3181. destination[property] = sourceProperty;
  3182. break;
  3183. case 1:
  3184. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3185. break;
  3186. case 2:
  3187. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3188. break;
  3189. case 3:
  3190. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3191. break;
  3192. case 4:
  3193. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3194. break;
  3195. case 5:
  3196. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3197. break;
  3198. case 6:
  3199. destination[property] = scene.getLastMeshByID(sourceProperty);
  3200. break;
  3201. }
  3202. }
  3203. }
  3204. return destination;
  3205. };
  3206. SerializationHelper.Clone = function (creationFunction, source) {
  3207. var destination = creationFunction();
  3208. // Tags
  3209. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3210. // Properties
  3211. for (var property in destination.__serializableMembers) {
  3212. var propertyDescriptor = destination.__serializableMembers[property];
  3213. var sourceProperty = source[property];
  3214. var propertyType = propertyDescriptor.type;
  3215. if (sourceProperty !== undefined && sourceProperty !== null) {
  3216. switch (propertyType) {
  3217. case 0: // Value
  3218. case 6:
  3219. destination[property] = sourceProperty;
  3220. break;
  3221. case 1: // Texture
  3222. case 2: // Color3
  3223. case 3: // FresnelParameters
  3224. case 4: // Vector2
  3225. case 5:
  3226. destination[property] = sourceProperty.clone();
  3227. break;
  3228. }
  3229. }
  3230. }
  3231. return destination;
  3232. };
  3233. return SerializationHelper;
  3234. })();
  3235. BABYLON.SerializationHelper = SerializationHelper;
  3236. })(BABYLON || (BABYLON = {}));
  3237. var BABYLON;
  3238. (function (BABYLON) {
  3239. /**
  3240. * A class serves as a medium between the observable and its observers
  3241. */
  3242. var EventState = (function () {
  3243. /**
  3244. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3245. */
  3246. function EventState(mask, skipNextObservers) {
  3247. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3248. this.mask = mask;
  3249. this.skipNextObservers = skipNextObservers;
  3250. }
  3251. return EventState;
  3252. })();
  3253. BABYLON.EventState = EventState;
  3254. /**
  3255. * Represent an Observer registered to a given Observable object.
  3256. */
  3257. var Observer = (function () {
  3258. function Observer(callback, mask) {
  3259. this.callback = callback;
  3260. this.mask = mask;
  3261. }
  3262. return Observer;
  3263. })();
  3264. BABYLON.Observer = Observer;
  3265. /**
  3266. * The Observable class is a simple implementation of the Observable pattern.
  3267. * 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.
  3268. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3269. * 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).
  3270. * 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.
  3271. */
  3272. var Observable = (function () {
  3273. function Observable() {
  3274. this._observers = new Array();
  3275. }
  3276. /**
  3277. * Create a new Observer with the specified callback
  3278. * @param callback the callback that will be executed for that Observer
  3279. * @param mask the mask used to filter observers
  3280. * @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.
  3281. */
  3282. Observable.prototype.add = function (callback, mask, insertFirst) {
  3283. if (mask === void 0) { mask = -1; }
  3284. if (insertFirst === void 0) { insertFirst = false; }
  3285. if (!callback) {
  3286. return null;
  3287. }
  3288. var observer = new Observer(callback, mask);
  3289. if (insertFirst) {
  3290. this._observers.unshift(observer);
  3291. }
  3292. else {
  3293. this._observers.push(observer);
  3294. }
  3295. return observer;
  3296. };
  3297. /**
  3298. * Remove an Observer from the Observable object
  3299. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3300. */
  3301. Observable.prototype.remove = function (observer) {
  3302. var index = this._observers.indexOf(observer);
  3303. if (index !== -1) {
  3304. this._observers.splice(index, 1);
  3305. return true;
  3306. }
  3307. return false;
  3308. };
  3309. /**
  3310. * Remove a callback from the Observable object
  3311. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3312. */
  3313. Observable.prototype.removeCallback = function (callback) {
  3314. for (var index = 0; index < this._observers.length; index++) {
  3315. if (this._observers[index].callback === callback) {
  3316. this._observers.splice(index, 1);
  3317. return true;
  3318. }
  3319. }
  3320. return false;
  3321. };
  3322. /**
  3323. * Notify all Observers by calling their respective callback with the given data
  3324. * @param eventData
  3325. * @param mask
  3326. */
  3327. Observable.prototype.notifyObservers = function (eventData, mask) {
  3328. if (mask === void 0) { mask = -1; }
  3329. var state = new EventState(mask);
  3330. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3331. var obs = _a[_i];
  3332. if (obs.mask & mask) {
  3333. obs.callback(eventData, state);
  3334. }
  3335. if (state.skipNextObservers) {
  3336. break;
  3337. }
  3338. }
  3339. };
  3340. /**
  3341. * return true is the Observable has at least one Observer registered
  3342. */
  3343. Observable.prototype.hasObservers = function () {
  3344. return this._observers.length > 0;
  3345. };
  3346. /**
  3347. * Clear the list of observers
  3348. */
  3349. Observable.prototype.clear = function () {
  3350. this._observers = new Array();
  3351. };
  3352. /**
  3353. * Clone the current observable
  3354. */
  3355. Observable.prototype.clone = function () {
  3356. var result = new Observable();
  3357. result._observers = this._observers.slice(0);
  3358. return result;
  3359. };
  3360. return Observable;
  3361. })();
  3362. BABYLON.Observable = Observable;
  3363. })(BABYLON || (BABYLON = {}));
  3364. var BABYLON;
  3365. (function (BABYLON) {
  3366. var Database = (function () {
  3367. function Database(urlToScene, callbackManifestChecked) {
  3368. // Handling various flavors of prefixed version of IndexedDB
  3369. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3370. this.callbackManifestChecked = callbackManifestChecked;
  3371. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3372. this.db = null;
  3373. this.enableSceneOffline = false;
  3374. this.enableTexturesOffline = false;
  3375. this.manifestVersionFound = 0;
  3376. this.mustUpdateRessources = false;
  3377. this.hasReachedQuota = false;
  3378. if (!Database.IDBStorageEnabled) {
  3379. this.callbackManifestChecked(true);
  3380. }
  3381. else {
  3382. this.checkManifestFile();
  3383. }
  3384. }
  3385. Database.prototype.checkManifestFile = function () {
  3386. var _this = this;
  3387. function noManifestFile() {
  3388. that.enableSceneOffline = false;
  3389. that.enableTexturesOffline = false;
  3390. that.callbackManifestChecked(false);
  3391. }
  3392. var that = this;
  3393. var timeStampUsed = false;
  3394. var manifestURL = this.currentSceneUrl + ".manifest";
  3395. var xhr = new XMLHttpRequest();
  3396. if (navigator.onLine) {
  3397. // Adding a timestamp to by-pass browsers' cache
  3398. timeStampUsed = true;
  3399. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3400. }
  3401. xhr.open("GET", manifestURL, true);
  3402. xhr.addEventListener("load", function () {
  3403. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3404. try {
  3405. var manifestFile = JSON.parse(xhr.response);
  3406. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3407. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3408. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3409. _this.manifestVersionFound = manifestFile.version;
  3410. }
  3411. if (_this.callbackManifestChecked) {
  3412. _this.callbackManifestChecked(true);
  3413. }
  3414. }
  3415. catch (ex) {
  3416. noManifestFile();
  3417. }
  3418. }
  3419. else {
  3420. noManifestFile();
  3421. }
  3422. }, false);
  3423. xhr.addEventListener("error", function (event) {
  3424. if (timeStampUsed) {
  3425. timeStampUsed = false;
  3426. // Let's retry without the timeStamp
  3427. // It could fail when coupled with HTML5 Offline API
  3428. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3429. xhr.open("GET", retryManifestURL, true);
  3430. xhr.send();
  3431. }
  3432. else {
  3433. noManifestFile();
  3434. }
  3435. }, false);
  3436. try {
  3437. xhr.send();
  3438. }
  3439. catch (ex) {
  3440. BABYLON.Tools.Error("Error on XHR send request.");
  3441. that.callbackManifestChecked(false);
  3442. }
  3443. };
  3444. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3445. var _this = this;
  3446. function handleError() {
  3447. that.isSupported = false;
  3448. if (errorCallback)
  3449. errorCallback();
  3450. }
  3451. var that = this;
  3452. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3453. // Your browser doesn't support IndexedDB
  3454. this.isSupported = false;
  3455. if (errorCallback)
  3456. errorCallback();
  3457. }
  3458. else {
  3459. // If the DB hasn't been opened or created yet
  3460. if (!this.db) {
  3461. this.hasReachedQuota = false;
  3462. this.isSupported = true;
  3463. var request = this.idbFactory.open("babylonjs", 1);
  3464. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3465. request.onerror = function (event) {
  3466. handleError();
  3467. };
  3468. // executes when a version change transaction cannot complete due to other active transactions
  3469. request.onblocked = function (event) {
  3470. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3471. handleError();
  3472. };
  3473. // DB has been opened successfully
  3474. request.onsuccess = function (event) {
  3475. _this.db = request.result;
  3476. successCallback();
  3477. };
  3478. // Initialization of the DB. Creating Scenes & Textures stores
  3479. request.onupgradeneeded = function (event) {
  3480. _this.db = (event.target).result;
  3481. try {
  3482. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3483. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3484. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3485. }
  3486. catch (ex) {
  3487. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3488. handleError();
  3489. }
  3490. };
  3491. }
  3492. else {
  3493. if (successCallback)
  3494. successCallback();
  3495. }
  3496. }
  3497. };
  3498. Database.prototype.loadImageFromDB = function (url, image) {
  3499. var _this = this;
  3500. var completeURL = Database.ReturnFullUrlLocation(url);
  3501. var saveAndLoadImage = function () {
  3502. if (!_this.hasReachedQuota && _this.db !== null) {
  3503. // the texture is not yet in the DB, let's try to save it
  3504. _this._saveImageIntoDBAsync(completeURL, image);
  3505. }
  3506. else {
  3507. image.src = url;
  3508. }
  3509. };
  3510. if (!this.mustUpdateRessources) {
  3511. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3512. }
  3513. else {
  3514. saveAndLoadImage();
  3515. }
  3516. };
  3517. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3518. if (this.isSupported && this.db !== null) {
  3519. var texture;
  3520. var transaction = this.db.transaction(["textures"]);
  3521. transaction.onabort = function (event) {
  3522. image.src = url;
  3523. };
  3524. transaction.oncomplete = function (event) {
  3525. var blobTextureURL;
  3526. if (texture) {
  3527. var URL = window.URL || window.webkitURL;
  3528. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3529. image.onerror = function () {
  3530. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3531. image.src = url;
  3532. };
  3533. image.src = blobTextureURL;
  3534. }
  3535. else {
  3536. notInDBCallback();
  3537. }
  3538. };
  3539. var getRequest = transaction.objectStore("textures").get(url);
  3540. getRequest.onsuccess = function (event) {
  3541. texture = (event.target).result;
  3542. };
  3543. getRequest.onerror = function (event) {
  3544. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3545. image.src = url;
  3546. };
  3547. }
  3548. else {
  3549. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3550. image.src = url;
  3551. }
  3552. };
  3553. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3554. var _this = this;
  3555. if (this.isSupported) {
  3556. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3557. var generateBlobUrl = function () {
  3558. var blobTextureURL;
  3559. if (blob) {
  3560. var URL = window.URL || window.webkitURL;
  3561. try {
  3562. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3563. }
  3564. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3565. catch (ex) {
  3566. blobTextureURL = URL.createObjectURL(blob);
  3567. }
  3568. }
  3569. image.src = blobTextureURL;
  3570. };
  3571. if (Database.IsUASupportingBlobStorage) {
  3572. var xhr = new XMLHttpRequest(), blob;
  3573. xhr.open("GET", url, true);
  3574. xhr.responseType = "blob";
  3575. xhr.addEventListener("load", function () {
  3576. if (xhr.status === 200) {
  3577. // Blob as response (XHR2)
  3578. blob = xhr.response;
  3579. var transaction = _this.db.transaction(["textures"], "readwrite");
  3580. // the transaction could abort because of a QuotaExceededError error
  3581. transaction.onabort = function (event) {
  3582. try {
  3583. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3584. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3585. this.hasReachedQuota = true;
  3586. }
  3587. }
  3588. catch (ex) { }
  3589. generateBlobUrl();
  3590. };
  3591. transaction.oncomplete = function (event) {
  3592. generateBlobUrl();
  3593. };
  3594. var newTexture = { textureUrl: url, data: blob };
  3595. try {
  3596. // Put the blob into the dabase
  3597. var addRequest = transaction.objectStore("textures").put(newTexture);
  3598. addRequest.onsuccess = function (event) {
  3599. };
  3600. addRequest.onerror = function (event) {
  3601. generateBlobUrl();
  3602. };
  3603. }
  3604. catch (ex) {
  3605. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3606. if (ex.code === 25) {
  3607. Database.IsUASupportingBlobStorage = false;
  3608. }
  3609. image.src = url;
  3610. }
  3611. }
  3612. else {
  3613. image.src = url;
  3614. }
  3615. }, false);
  3616. xhr.addEventListener("error", function (event) {
  3617. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3618. image.src = url;
  3619. }, false);
  3620. xhr.send();
  3621. }
  3622. else {
  3623. image.src = url;
  3624. }
  3625. }
  3626. else {
  3627. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3628. image.src = url;
  3629. }
  3630. };
  3631. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3632. var _this = this;
  3633. var updateVersion = function (event) {
  3634. // the version is not yet in the DB or we need to update it
  3635. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3636. };
  3637. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3638. };
  3639. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3640. var _this = this;
  3641. if (this.isSupported) {
  3642. var version;
  3643. try {
  3644. var transaction = this.db.transaction(["versions"]);
  3645. transaction.oncomplete = function (event) {
  3646. if (version) {
  3647. // If the version in the JSON file is > than the version in DB
  3648. if (_this.manifestVersionFound > version.data) {
  3649. _this.mustUpdateRessources = true;
  3650. updateInDBCallback();
  3651. }
  3652. else {
  3653. callback(version.data);
  3654. }
  3655. }
  3656. else {
  3657. _this.mustUpdateRessources = true;
  3658. updateInDBCallback();
  3659. }
  3660. };
  3661. transaction.onabort = function (event) {
  3662. callback(-1);
  3663. };
  3664. var getRequest = transaction.objectStore("versions").get(url);
  3665. getRequest.onsuccess = function (event) {
  3666. version = (event.target).result;
  3667. };
  3668. getRequest.onerror = function (event) {
  3669. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3670. callback(-1);
  3671. };
  3672. }
  3673. catch (ex) {
  3674. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3675. callback(-1);
  3676. }
  3677. }
  3678. else {
  3679. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3680. callback(-1);
  3681. }
  3682. };
  3683. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3684. var _this = this;
  3685. if (this.isSupported && !this.hasReachedQuota) {
  3686. try {
  3687. // Open a transaction to the database
  3688. var transaction = this.db.transaction(["versions"], "readwrite");
  3689. // the transaction could abort because of a QuotaExceededError error
  3690. transaction.onabort = function (event) {
  3691. try {
  3692. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3693. _this.hasReachedQuota = true;
  3694. }
  3695. }
  3696. catch (ex) { }
  3697. callback(-1);
  3698. };
  3699. transaction.oncomplete = function (event) {
  3700. callback(_this.manifestVersionFound);
  3701. };
  3702. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3703. // Put the scene into the database
  3704. var addRequest = transaction.objectStore("versions").put(newVersion);
  3705. addRequest.onsuccess = function (event) {
  3706. };
  3707. addRequest.onerror = function (event) {
  3708. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3709. };
  3710. }
  3711. catch (ex) {
  3712. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3713. callback(-1);
  3714. }
  3715. }
  3716. else {
  3717. callback(-1);
  3718. }
  3719. };
  3720. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3721. var _this = this;
  3722. var completeUrl = Database.ReturnFullUrlLocation(url);
  3723. var saveAndLoadFile = function (event) {
  3724. // the scene is not yet in the DB, let's try to save it
  3725. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3726. };
  3727. this._checkVersionFromDB(completeUrl, function (version) {
  3728. if (version !== -1) {
  3729. if (!_this.mustUpdateRessources) {
  3730. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3731. }
  3732. else {
  3733. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3734. }
  3735. }
  3736. else {
  3737. errorCallback();
  3738. }
  3739. });
  3740. };
  3741. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3742. if (this.isSupported) {
  3743. var targetStore;
  3744. if (url.indexOf(".babylon") !== -1) {
  3745. targetStore = "scenes";
  3746. }
  3747. else {
  3748. targetStore = "textures";
  3749. }
  3750. var file;
  3751. var transaction = this.db.transaction([targetStore]);
  3752. transaction.oncomplete = function (event) {
  3753. if (file) {
  3754. callback(file.data);
  3755. }
  3756. else {
  3757. notInDBCallback();
  3758. }
  3759. };
  3760. transaction.onabort = function (event) {
  3761. notInDBCallback();
  3762. };
  3763. var getRequest = transaction.objectStore(targetStore).get(url);
  3764. getRequest.onsuccess = function (event) {
  3765. file = (event.target).result;
  3766. };
  3767. getRequest.onerror = function (event) {
  3768. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3769. notInDBCallback();
  3770. };
  3771. }
  3772. else {
  3773. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3774. callback();
  3775. }
  3776. };
  3777. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3778. var _this = this;
  3779. if (this.isSupported) {
  3780. var targetStore;
  3781. if (url.indexOf(".babylon") !== -1) {
  3782. targetStore = "scenes";
  3783. }
  3784. else {
  3785. targetStore = "textures";
  3786. }
  3787. // Create XHR
  3788. var xhr = new XMLHttpRequest(), fileData;
  3789. xhr.open("GET", url, true);
  3790. if (useArrayBuffer) {
  3791. xhr.responseType = "arraybuffer";
  3792. }
  3793. xhr.onprogress = progressCallback;
  3794. xhr.addEventListener("load", function () {
  3795. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3796. // Blob as response (XHR2)
  3797. //fileData = xhr.responseText;
  3798. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3799. if (!_this.hasReachedQuota) {
  3800. // Open a transaction to the database
  3801. var transaction = _this.db.transaction([targetStore], "readwrite");
  3802. // the transaction could abort because of a QuotaExceededError error
  3803. transaction.onabort = function (event) {
  3804. try {
  3805. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3806. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3807. this.hasReachedQuota = true;
  3808. }
  3809. }
  3810. catch (ex) { }
  3811. callback(fileData);
  3812. };
  3813. transaction.oncomplete = function (event) {
  3814. callback(fileData);
  3815. };
  3816. var newFile;
  3817. if (targetStore === "scenes") {
  3818. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3819. }
  3820. else {
  3821. newFile = { textureUrl: url, data: fileData };
  3822. }
  3823. try {
  3824. // Put the scene into the database
  3825. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3826. addRequest.onsuccess = function (event) {
  3827. };
  3828. addRequest.onerror = function (event) {
  3829. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3830. };
  3831. }
  3832. catch (ex) {
  3833. callback(fileData);
  3834. }
  3835. }
  3836. else {
  3837. callback(fileData);
  3838. }
  3839. }
  3840. else {
  3841. callback();
  3842. }
  3843. }, false);
  3844. xhr.addEventListener("error", function (event) {
  3845. BABYLON.Tools.Error("error on XHR request.");
  3846. callback();
  3847. }, false);
  3848. xhr.send();
  3849. }
  3850. else {
  3851. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3852. callback();
  3853. }
  3854. };
  3855. Database.IsUASupportingBlobStorage = true;
  3856. Database.IDBStorageEnabled = true;
  3857. Database.parseURL = function (url) {
  3858. var a = document.createElement('a');
  3859. a.href = url;
  3860. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3861. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3862. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3863. return absLocation;
  3864. };
  3865. Database.ReturnFullUrlLocation = function (url) {
  3866. if (url.indexOf("http:/") === -1) {
  3867. return (Database.parseURL(window.location.href) + url);
  3868. }
  3869. else {
  3870. return url;
  3871. }
  3872. };
  3873. return Database;
  3874. })();
  3875. BABYLON.Database = Database;
  3876. })(BABYLON || (BABYLON = {}));
  3877. var BABYLON;
  3878. (function (BABYLON) {
  3879. var Internals;
  3880. (function (Internals) {
  3881. /*
  3882. * Based on jsTGALoader - Javascript loader for TGA file
  3883. * By Vincent Thibault
  3884. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3885. */
  3886. var TGATools = (function () {
  3887. function TGATools() {
  3888. }
  3889. TGATools.GetTGAHeader = function (data) {
  3890. var offset = 0;
  3891. var header = {
  3892. id_length: data[offset++],
  3893. colormap_type: data[offset++],
  3894. image_type: data[offset++],
  3895. colormap_index: data[offset++] | data[offset++] << 8,
  3896. colormap_length: data[offset++] | data[offset++] << 8,
  3897. colormap_size: data[offset++],
  3898. origin: [
  3899. data[offset++] | data[offset++] << 8,
  3900. data[offset++] | data[offset++] << 8
  3901. ],
  3902. width: data[offset++] | data[offset++] << 8,
  3903. height: data[offset++] | data[offset++] << 8,
  3904. pixel_size: data[offset++],
  3905. flags: data[offset++]
  3906. };
  3907. return header;
  3908. };
  3909. TGATools.UploadContent = function (gl, data) {
  3910. // Not enough data to contain header ?
  3911. if (data.length < 19) {
  3912. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3913. return;
  3914. }
  3915. // Read Header
  3916. var offset = 18;
  3917. var header = TGATools.GetTGAHeader(data);
  3918. // Assume it's a valid Targa file.
  3919. if (header.id_length + offset > data.length) {
  3920. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3921. return;
  3922. }
  3923. // Skip not needed data
  3924. offset += header.id_length;
  3925. var use_rle = false;
  3926. var use_pal = false;
  3927. var use_rgb = false;
  3928. var use_grey = false;
  3929. // Get some informations.
  3930. switch (header.image_type) {
  3931. case TGATools._TYPE_RLE_INDEXED:
  3932. use_rle = true;
  3933. case TGATools._TYPE_INDEXED:
  3934. use_pal = true;
  3935. break;
  3936. case TGATools._TYPE_RLE_RGB:
  3937. use_rle = true;
  3938. case TGATools._TYPE_RGB:
  3939. use_rgb = true;
  3940. break;
  3941. case TGATools._TYPE_RLE_GREY:
  3942. use_rle = true;
  3943. case TGATools._TYPE_GREY:
  3944. use_grey = true;
  3945. break;
  3946. }
  3947. var pixel_data;
  3948. var numAlphaBits = header.flags & 0xf;
  3949. var pixel_size = header.pixel_size >> 3;
  3950. var pixel_total = header.width * header.height * pixel_size;
  3951. // Read palettes
  3952. var palettes;
  3953. if (use_pal) {
  3954. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3955. }
  3956. // Read LRE
  3957. if (use_rle) {
  3958. pixel_data = new Uint8Array(pixel_total);
  3959. var c, count, i;
  3960. var localOffset = 0;
  3961. var pixels = new Uint8Array(pixel_size);
  3962. while (offset < pixel_total && localOffset < pixel_total) {
  3963. c = data[offset++];
  3964. count = (c & 0x7f) + 1;
  3965. // RLE pixels
  3966. if (c & 0x80) {
  3967. // Bind pixel tmp array
  3968. for (i = 0; i < pixel_size; ++i) {
  3969. pixels[i] = data[offset++];
  3970. }
  3971. // Copy pixel array
  3972. for (i = 0; i < count; ++i) {
  3973. pixel_data.set(pixels, localOffset + i * pixel_size);
  3974. }
  3975. localOffset += pixel_size * count;
  3976. }
  3977. else {
  3978. count *= pixel_size;
  3979. for (i = 0; i < count; ++i) {
  3980. pixel_data[localOffset + i] = data[offset++];
  3981. }
  3982. localOffset += count;
  3983. }
  3984. }
  3985. }
  3986. else {
  3987. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3988. }
  3989. // Load to texture
  3990. var x_start, y_start, x_step, y_step, y_end, x_end;
  3991. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3992. default:
  3993. case TGATools._ORIGIN_UL:
  3994. x_start = 0;
  3995. x_step = 1;
  3996. x_end = header.width;
  3997. y_start = 0;
  3998. y_step = 1;
  3999. y_end = header.height;
  4000. break;
  4001. case TGATools._ORIGIN_BL:
  4002. x_start = 0;
  4003. x_step = 1;
  4004. x_end = header.width;
  4005. y_start = header.height - 1;
  4006. y_step = -1;
  4007. y_end = -1;
  4008. break;
  4009. case TGATools._ORIGIN_UR:
  4010. x_start = header.width - 1;
  4011. x_step = -1;
  4012. x_end = -1;
  4013. y_start = 0;
  4014. y_step = 1;
  4015. y_end = header.height;
  4016. break;
  4017. case TGATools._ORIGIN_BR:
  4018. x_start = header.width - 1;
  4019. x_step = -1;
  4020. x_end = -1;
  4021. y_start = header.height - 1;
  4022. y_step = -1;
  4023. y_end = -1;
  4024. break;
  4025. }
  4026. // Load the specify method
  4027. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4028. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4029. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4030. };
  4031. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4032. var image = pixel_data, colormap = palettes;
  4033. var width = header.width, height = header.height;
  4034. var color, i = 0, x, y;
  4035. var imageData = new Uint8Array(width * height * 4);
  4036. for (y = y_start; y !== y_end; y += y_step) {
  4037. for (x = x_start; x !== x_end; x += x_step, i++) {
  4038. color = image[i];
  4039. imageData[(x + width * y) * 4 + 3] = 255;
  4040. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4041. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4042. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4043. }
  4044. }
  4045. return imageData;
  4046. };
  4047. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4048. var image = pixel_data;
  4049. var width = header.width, height = header.height;
  4050. var color, i = 0, x, y;
  4051. var imageData = new Uint8Array(width * height * 4);
  4052. for (y = y_start; y !== y_end; y += y_step) {
  4053. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4054. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4055. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4056. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4057. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4058. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4059. }
  4060. }
  4061. return imageData;
  4062. };
  4063. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4064. var image = pixel_data;
  4065. var width = header.width, height = header.height;
  4066. var i = 0, x, y;
  4067. var imageData = new Uint8Array(width * height * 4);
  4068. for (y = y_start; y !== y_end; y += y_step) {
  4069. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4070. imageData[(x + width * y) * 4 + 3] = 255;
  4071. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4072. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4073. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4074. }
  4075. }
  4076. return imageData;
  4077. };
  4078. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4079. var image = pixel_data;
  4080. var width = header.width, height = header.height;
  4081. var i = 0, x, y;
  4082. var imageData = new Uint8Array(width * height * 4);
  4083. for (y = y_start; y !== y_end; y += y_step) {
  4084. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4085. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4086. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4087. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4088. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4089. }
  4090. }
  4091. return imageData;
  4092. };
  4093. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4094. var image = pixel_data;
  4095. var width = header.width, height = header.height;
  4096. var color, i = 0, x, y;
  4097. var imageData = new Uint8Array(width * height * 4);
  4098. for (y = y_start; y !== y_end; y += y_step) {
  4099. for (x = x_start; x !== x_end; x += x_step, i++) {
  4100. color = image[i];
  4101. imageData[(x + width * y) * 4 + 0] = color;
  4102. imageData[(x + width * y) * 4 + 1] = color;
  4103. imageData[(x + width * y) * 4 + 2] = color;
  4104. imageData[(x + width * y) * 4 + 3] = 255;
  4105. }
  4106. }
  4107. return imageData;
  4108. };
  4109. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4110. var image = pixel_data;
  4111. var width = header.width, height = header.height;
  4112. var i = 0, x, y;
  4113. var imageData = new Uint8Array(width * height * 4);
  4114. for (y = y_start; y !== y_end; y += y_step) {
  4115. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4116. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4117. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4118. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4119. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4120. }
  4121. }
  4122. return imageData;
  4123. };
  4124. TGATools._TYPE_NO_DATA = 0;
  4125. TGATools._TYPE_INDEXED = 1;
  4126. TGATools._TYPE_RGB = 2;
  4127. TGATools._TYPE_GREY = 3;
  4128. TGATools._TYPE_RLE_INDEXED = 9;
  4129. TGATools._TYPE_RLE_RGB = 10;
  4130. TGATools._TYPE_RLE_GREY = 11;
  4131. TGATools._ORIGIN_MASK = 0x30;
  4132. TGATools._ORIGIN_SHIFT = 0x04;
  4133. TGATools._ORIGIN_BL = 0x00;
  4134. TGATools._ORIGIN_BR = 0x01;
  4135. TGATools._ORIGIN_UL = 0x02;
  4136. TGATools._ORIGIN_UR = 0x03;
  4137. return TGATools;
  4138. })();
  4139. Internals.TGATools = TGATools;
  4140. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4141. })(BABYLON || (BABYLON = {}));
  4142. var BABYLON;
  4143. (function (BABYLON) {
  4144. var SmartArray = (function () {
  4145. function SmartArray(capacity) {
  4146. this.length = 0;
  4147. this._duplicateId = 0;
  4148. this.data = new Array(capacity);
  4149. this._id = SmartArray._GlobalId++;
  4150. }
  4151. SmartArray.prototype.push = function (value) {
  4152. this.data[this.length++] = value;
  4153. if (this.length > this.data.length) {
  4154. this.data.length *= 2;
  4155. }
  4156. if (!value.__smartArrayFlags) {
  4157. value.__smartArrayFlags = {};
  4158. }
  4159. value.__smartArrayFlags[this._id] = this._duplicateId;
  4160. };
  4161. SmartArray.prototype.pushNoDuplicate = function (value) {
  4162. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4163. return;
  4164. }
  4165. this.push(value);
  4166. };
  4167. SmartArray.prototype.sort = function (compareFn) {
  4168. this.data.sort(compareFn);
  4169. };
  4170. SmartArray.prototype.reset = function () {
  4171. this.length = 0;
  4172. this._duplicateId++;
  4173. };
  4174. SmartArray.prototype.concat = function (array) {
  4175. if (array.length === 0) {
  4176. return;
  4177. }
  4178. if (this.length + array.length > this.data.length) {
  4179. this.data.length = (this.length + array.length) * 2;
  4180. }
  4181. for (var index = 0; index < array.length; index++) {
  4182. this.data[this.length++] = (array.data || array)[index];
  4183. }
  4184. };
  4185. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4186. if (array.length === 0) {
  4187. return;
  4188. }
  4189. if (this.length + array.length > this.data.length) {
  4190. this.data.length = (this.length + array.length) * 2;
  4191. }
  4192. for (var index = 0; index < array.length; index++) {
  4193. var item = (array.data || array)[index];
  4194. this.pushNoDuplicate(item);
  4195. }
  4196. };
  4197. SmartArray.prototype.indexOf = function (value) {
  4198. var position = this.data.indexOf(value);
  4199. if (position >= this.length) {
  4200. return -1;
  4201. }
  4202. return position;
  4203. };
  4204. // Statics
  4205. SmartArray._GlobalId = 0;
  4206. return SmartArray;
  4207. })();
  4208. BABYLON.SmartArray = SmartArray;
  4209. })(BABYLON || (BABYLON = {}));
  4210. var BABYLON;
  4211. (function (BABYLON) {
  4212. /**
  4213. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4214. * The underlying implementation relies on an associative array to ensure the best performances.
  4215. * The value can be anything including 'null' but except 'undefined'
  4216. */
  4217. var StringDictionary = (function () {
  4218. function StringDictionary() {
  4219. this._count = 0;
  4220. this._data = {};
  4221. }
  4222. /**
  4223. * Get a value based from its key
  4224. * @param key the given key to get the matching value from
  4225. * @return the value if found, otherwise undefined is returned
  4226. */
  4227. StringDictionary.prototype.get = function (key) {
  4228. var val = this._data[key];
  4229. if (val !== undefined) {
  4230. return val;
  4231. }
  4232. return undefined;
  4233. };
  4234. /**
  4235. * Get a value from its key or add it if it doesn't exist.
  4236. * This method will ensure you that a given key/data will be present in the dictionary.
  4237. * @param key the given key to get the matching value from
  4238. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4239. * The factory will only be invoked if there's no data for the given key.
  4240. * @return the value corresponding to the key.
  4241. */
  4242. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4243. var val = this.get(key);
  4244. if (val !== undefined) {
  4245. return val;
  4246. }
  4247. val = factory(key);
  4248. if (val) {
  4249. this.add(key, val);
  4250. }
  4251. return val;
  4252. };
  4253. /**
  4254. * Get a value from its key if present in the dictionary otherwise add it
  4255. * @param key the key to get the value from
  4256. * @param val if there's no such key/value pair in the dictionary add it with this value
  4257. * @return the value corresponding to the key
  4258. */
  4259. StringDictionary.prototype.getOrAdd = function (key, val) {
  4260. var curVal = this.get(key);
  4261. if (curVal !== undefined) {
  4262. return curVal;
  4263. }
  4264. this.add(key, val);
  4265. return val;
  4266. };
  4267. /**
  4268. * Check if there's a given key in the dictionary
  4269. * @param key the key to check for
  4270. * @return true if the key is present, false otherwise
  4271. */
  4272. StringDictionary.prototype.contains = function (key) {
  4273. return this._data[key] !== undefined;
  4274. };
  4275. /**
  4276. * Add a new key and its corresponding value
  4277. * @param key the key to add
  4278. * @param value the value corresponding to the key
  4279. * @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
  4280. */
  4281. StringDictionary.prototype.add = function (key, value) {
  4282. if (this._data[key] !== undefined) {
  4283. return false;
  4284. }
  4285. this._data[key] = value;
  4286. ++this._count;
  4287. return true;
  4288. };
  4289. StringDictionary.prototype.set = function (key, value) {
  4290. if (this._data[key] === undefined) {
  4291. return false;
  4292. }
  4293. this._data[key] = value;
  4294. return true;
  4295. };
  4296. /**
  4297. * Remove a key/value from the dictionary.
  4298. * @param key the key to remove
  4299. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4300. */
  4301. StringDictionary.prototype.remove = function (key) {
  4302. if (this.contains(key)) {
  4303. delete this._data[key];
  4304. --this._count;
  4305. return true;
  4306. }
  4307. return false;
  4308. };
  4309. /**
  4310. * Clear the whole content of the dictionary
  4311. */
  4312. StringDictionary.prototype.clear = function () {
  4313. this._data = {};
  4314. this._count = 0;
  4315. };
  4316. Object.defineProperty(StringDictionary.prototype, "count", {
  4317. get: function () {
  4318. return this._count;
  4319. },
  4320. enumerable: true,
  4321. configurable: true
  4322. });
  4323. /**
  4324. * Execute a callback on each key/val of the dictionary.
  4325. * Note that you can remove any element in this dictionary in the callback implementation
  4326. * @param callback the callback to execute on a given key/value pair
  4327. */
  4328. StringDictionary.prototype.forEach = function (callback) {
  4329. for (var cur in this._data) {
  4330. var val = this._data[cur];
  4331. callback(cur, val);
  4332. }
  4333. };
  4334. /**
  4335. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4336. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4337. * Note that you can remove any element in this dictionary in the callback implementation
  4338. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4339. */
  4340. StringDictionary.prototype.first = function (callback) {
  4341. for (var cur in this._data) {
  4342. var val = this._data[cur];
  4343. var res = callback(cur, val);
  4344. if (res) {
  4345. return res;
  4346. }
  4347. }
  4348. return null;
  4349. };
  4350. return StringDictionary;
  4351. })();
  4352. BABYLON.StringDictionary = StringDictionary;
  4353. })(BABYLON || (BABYLON = {}));
  4354. var BABYLON;
  4355. (function (BABYLON) {
  4356. // Screenshots
  4357. var screenshotCanvas;
  4358. var cloneValue = function (source, destinationObject) {
  4359. if (!source)
  4360. return null;
  4361. if (source instanceof BABYLON.Mesh) {
  4362. return null;
  4363. }
  4364. if (source instanceof BABYLON.SubMesh) {
  4365. return source.clone(destinationObject);
  4366. }
  4367. else if (source.clone) {
  4368. return source.clone();
  4369. }
  4370. return null;
  4371. };
  4372. var Tools = (function () {
  4373. function Tools() {
  4374. }
  4375. Tools.Instantiate = function (className) {
  4376. var arr = className.split(".");
  4377. var fn = (window || this);
  4378. for (var i = 0, len = arr.length; i < len; i++) {
  4379. fn = fn[arr[i]];
  4380. }
  4381. if (typeof fn !== "function") {
  4382. return null;
  4383. }
  4384. return fn;
  4385. };
  4386. Tools.SetImmediate = function (action) {
  4387. if (window.setImmediate) {
  4388. window.setImmediate(action);
  4389. }
  4390. else {
  4391. setTimeout(action, 1);
  4392. }
  4393. };
  4394. Tools.IsExponentOfTwo = function (value) {
  4395. var count = 1;
  4396. do {
  4397. count *= 2;
  4398. } while (count < value);
  4399. return count === value;
  4400. };
  4401. Tools.GetExponentOfTwo = function (value, max) {
  4402. var count = 1;
  4403. do {
  4404. count *= 2;
  4405. } while (count < value);
  4406. if (count > max)
  4407. count = max;
  4408. return count;
  4409. };
  4410. Tools.GetFilename = function (path) {
  4411. var index = path.lastIndexOf("/");
  4412. if (index < 0)
  4413. return path;
  4414. return path.substring(index + 1);
  4415. };
  4416. Tools.GetDOMTextContent = function (element) {
  4417. var result = "";
  4418. var child = element.firstChild;
  4419. while (child) {
  4420. if (child.nodeType === 3) {
  4421. result += child.textContent;
  4422. }
  4423. child = child.nextSibling;
  4424. }
  4425. return result;
  4426. };
  4427. Tools.ToDegrees = function (angle) {
  4428. return angle * 180 / Math.PI;
  4429. };
  4430. Tools.ToRadians = function (angle) {
  4431. return angle * Math.PI / 180;
  4432. };
  4433. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4434. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4435. var output = "";
  4436. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4437. var i = 0;
  4438. var bytes = new Uint8Array(buffer);
  4439. while (i < bytes.length) {
  4440. chr1 = bytes[i++];
  4441. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4442. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4443. enc1 = chr1 >> 2;
  4444. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4445. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4446. enc4 = chr3 & 63;
  4447. if (isNaN(chr2)) {
  4448. enc3 = enc4 = 64;
  4449. }
  4450. else if (isNaN(chr3)) {
  4451. enc4 = 64;
  4452. }
  4453. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4454. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4455. }
  4456. return "data:image/png;base64," + output;
  4457. };
  4458. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4459. if (bias === void 0) { bias = null; }
  4460. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4461. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4462. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4463. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4464. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4465. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4466. }
  4467. if (bias) {
  4468. minimum.x -= minimum.x * bias.x + bias.y;
  4469. minimum.y -= minimum.y * bias.x + bias.y;
  4470. minimum.z -= minimum.z * bias.x + bias.y;
  4471. maximum.x += maximum.x * bias.x + bias.y;
  4472. maximum.y += maximum.y * bias.x + bias.y;
  4473. maximum.z += maximum.z * bias.x + bias.y;
  4474. }
  4475. return {
  4476. minimum: minimum,
  4477. maximum: maximum
  4478. };
  4479. };
  4480. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4481. if (bias === void 0) { bias = null; }
  4482. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4483. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4484. for (var index = start; index < start + count; index++) {
  4485. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4486. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4487. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4488. }
  4489. if (bias) {
  4490. minimum.x -= minimum.x * bias.x + bias.y;
  4491. minimum.y -= minimum.y * bias.x + bias.y;
  4492. minimum.z -= minimum.z * bias.x + bias.y;
  4493. maximum.x += maximum.x * bias.x + bias.y;
  4494. maximum.y += maximum.y * bias.x + bias.y;
  4495. maximum.z += maximum.z * bias.x + bias.y;
  4496. }
  4497. return {
  4498. minimum: minimum,
  4499. maximum: maximum
  4500. };
  4501. };
  4502. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4503. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4504. return undefined;
  4505. return Array.isArray(obj) ? obj : [obj];
  4506. };
  4507. // Misc.
  4508. Tools.GetPointerPrefix = function () {
  4509. var eventPrefix = "pointer";
  4510. // Check if pointer events are supported
  4511. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4512. eventPrefix = "mouse";
  4513. }
  4514. return eventPrefix;
  4515. };
  4516. Tools.QueueNewFrame = function (func) {
  4517. if (window.requestAnimationFrame)
  4518. window.requestAnimationFrame(func);
  4519. else if (window.msRequestAnimationFrame)
  4520. window.msRequestAnimationFrame(func);
  4521. else if (window.webkitRequestAnimationFrame)
  4522. window.webkitRequestAnimationFrame(func);
  4523. else if (window.mozRequestAnimationFrame)
  4524. window.mozRequestAnimationFrame(func);
  4525. else if (window.oRequestAnimationFrame)
  4526. window.oRequestAnimationFrame(func);
  4527. else {
  4528. window.setTimeout(func, 16);
  4529. }
  4530. };
  4531. Tools.RequestFullscreen = function (element) {
  4532. if (element.requestFullscreen)
  4533. element.requestFullscreen();
  4534. else if (element.msRequestFullscreen)
  4535. element.msRequestFullscreen();
  4536. else if (element.webkitRequestFullscreen)
  4537. element.webkitRequestFullscreen();
  4538. else if (element.mozRequestFullScreen)
  4539. element.mozRequestFullScreen();
  4540. };
  4541. Tools.ExitFullscreen = function () {
  4542. if (document.exitFullscreen) {
  4543. document.exitFullscreen();
  4544. }
  4545. else if (document.mozCancelFullScreen) {
  4546. document.mozCancelFullScreen();
  4547. }
  4548. else if (document.webkitCancelFullScreen) {
  4549. document.webkitCancelFullScreen();
  4550. }
  4551. else if (document.msCancelFullScreen) {
  4552. document.msCancelFullScreen();
  4553. }
  4554. };
  4555. // External files
  4556. Tools.CleanUrl = function (url) {
  4557. url = url.replace(/#/mg, "%23");
  4558. return url;
  4559. };
  4560. Tools.LoadImage = function (url, onload, onerror, database) {
  4561. if (url instanceof ArrayBuffer) {
  4562. url = Tools.EncodeArrayBufferTobase64(url);
  4563. }
  4564. url = Tools.CleanUrl(url);
  4565. var img = new Image();
  4566. if (url.substr(0, 5) !== "data:") {
  4567. if (Tools.CorsBehavior) {
  4568. switch (typeof (Tools.CorsBehavior)) {
  4569. case "function":
  4570. var result = Tools.CorsBehavior(url);
  4571. if (result) {
  4572. img.crossOrigin = result;
  4573. }
  4574. break;
  4575. case "string":
  4576. default:
  4577. img.crossOrigin = Tools.CorsBehavior;
  4578. break;
  4579. }
  4580. }
  4581. }
  4582. img.onload = function () {
  4583. onload(img);
  4584. };
  4585. img.onerror = function (err) {
  4586. Tools.Error("Error while trying to load texture: " + url);
  4587. if (Tools.UseFallbackTexture) {
  4588. 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";
  4589. onload(img);
  4590. }
  4591. else {
  4592. onerror();
  4593. }
  4594. };
  4595. var noIndexedDB = function () {
  4596. img.src = url;
  4597. };
  4598. var loadFromIndexedDB = function () {
  4599. database.loadImageFromDB(url, img);
  4600. };
  4601. //ANY database to do!
  4602. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4603. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4604. }
  4605. else {
  4606. if (url.indexOf("file:") === -1) {
  4607. noIndexedDB();
  4608. }
  4609. else {
  4610. try {
  4611. var textureName = url.substring(5).toLowerCase();
  4612. var blobURL;
  4613. try {
  4614. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4615. }
  4616. catch (ex) {
  4617. // Chrome doesn't support oneTimeOnly parameter
  4618. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4619. }
  4620. img.src = blobURL;
  4621. }
  4622. catch (e) {
  4623. img.src = null;
  4624. }
  4625. }
  4626. }
  4627. return img;
  4628. };
  4629. //ANY
  4630. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4631. url = Tools.CleanUrl(url);
  4632. var noIndexedDB = function () {
  4633. var request = new XMLHttpRequest();
  4634. var loadUrl = Tools.BaseUrl + url;
  4635. request.open('GET', loadUrl, true);
  4636. if (useArrayBuffer) {
  4637. request.responseType = "arraybuffer";
  4638. }
  4639. request.onprogress = progressCallBack;
  4640. request.onreadystatechange = function () {
  4641. if (request.readyState === 4) {
  4642. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4643. callback(!useArrayBuffer ? request.responseText : request.response);
  4644. }
  4645. else {
  4646. if (onError) {
  4647. onError();
  4648. }
  4649. else {
  4650. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4651. }
  4652. }
  4653. }
  4654. };
  4655. request.send(null);
  4656. };
  4657. var loadFromIndexedDB = function () {
  4658. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4659. };
  4660. if (url.indexOf("file:") !== -1) {
  4661. var fileName = url.substring(5).toLowerCase();
  4662. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4663. }
  4664. else {
  4665. // Caching all files
  4666. if (database && database.enableSceneOffline) {
  4667. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4668. }
  4669. else {
  4670. noIndexedDB();
  4671. }
  4672. }
  4673. };
  4674. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4675. var reader = new FileReader();
  4676. reader.onload = function (e) {
  4677. //target doesn't have result from ts 1.3
  4678. callback(e.target['result']);
  4679. };
  4680. reader.onprogress = progressCallback;
  4681. reader.readAsDataURL(fileToLoad);
  4682. };
  4683. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4684. var reader = new FileReader();
  4685. reader.onerror = function (e) {
  4686. Tools.Log("Error while reading file: " + fileToLoad.name);
  4687. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4688. };
  4689. reader.onload = function (e) {
  4690. //target doesn't have result from ts 1.3
  4691. callback(e.target['result']);
  4692. };
  4693. reader.onprogress = progressCallBack;
  4694. if (!useArrayBuffer) {
  4695. // Asynchronous read
  4696. reader.readAsText(fileToLoad);
  4697. }
  4698. else {
  4699. reader.readAsArrayBuffer(fileToLoad);
  4700. }
  4701. };
  4702. //returns a downloadable url to a file content.
  4703. Tools.FileAsURL = function (content) {
  4704. var fileBlob = new Blob([content]);
  4705. var url = window.URL || window.webkitURL;
  4706. var link = url.createObjectURL(fileBlob);
  4707. return link;
  4708. };
  4709. // Misc.
  4710. Tools.Format = function (value, decimals) {
  4711. if (decimals === void 0) { decimals = 2; }
  4712. return value.toFixed(decimals);
  4713. };
  4714. Tools.CheckExtends = function (v, min, max) {
  4715. if (v.x < min.x)
  4716. min.x = v.x;
  4717. if (v.y < min.y)
  4718. min.y = v.y;
  4719. if (v.z < min.z)
  4720. min.z = v.z;
  4721. if (v.x > max.x)
  4722. max.x = v.x;
  4723. if (v.y > max.y)
  4724. max.y = v.y;
  4725. if (v.z > max.z)
  4726. max.z = v.z;
  4727. };
  4728. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4729. for (var prop in source) {
  4730. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4731. continue;
  4732. }
  4733. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4734. continue;
  4735. }
  4736. var sourceValue = source[prop];
  4737. var typeOfSourceValue = typeof sourceValue;
  4738. if (typeOfSourceValue === "function") {
  4739. continue;
  4740. }
  4741. if (typeOfSourceValue === "object") {
  4742. if (sourceValue instanceof Array) {
  4743. destination[prop] = [];
  4744. if (sourceValue.length > 0) {
  4745. if (typeof sourceValue[0] == "object") {
  4746. for (var index = 0; index < sourceValue.length; index++) {
  4747. var clonedValue = cloneValue(sourceValue[index], destination);
  4748. if (destination[prop].indexOf(clonedValue) === -1) {
  4749. destination[prop].push(clonedValue);
  4750. }
  4751. }
  4752. }
  4753. else {
  4754. destination[prop] = sourceValue.slice(0);
  4755. }
  4756. }
  4757. }
  4758. else {
  4759. destination[prop] = cloneValue(sourceValue, destination);
  4760. }
  4761. }
  4762. else {
  4763. destination[prop] = sourceValue;
  4764. }
  4765. }
  4766. };
  4767. Tools.IsEmpty = function (obj) {
  4768. for (var i in obj) {
  4769. return false;
  4770. }
  4771. return true;
  4772. };
  4773. Tools.RegisterTopRootEvents = function (events) {
  4774. for (var index = 0; index < events.length; index++) {
  4775. var event = events[index];
  4776. window.addEventListener(event.name, event.handler, false);
  4777. try {
  4778. if (window.parent) {
  4779. window.parent.addEventListener(event.name, event.handler, false);
  4780. }
  4781. }
  4782. catch (e) {
  4783. }
  4784. }
  4785. };
  4786. Tools.UnregisterTopRootEvents = function (events) {
  4787. for (var index = 0; index < events.length; index++) {
  4788. var event = events[index];
  4789. window.removeEventListener(event.name, event.handler);
  4790. try {
  4791. if (window.parent) {
  4792. window.parent.removeEventListener(event.name, event.handler);
  4793. }
  4794. }
  4795. catch (e) {
  4796. }
  4797. }
  4798. };
  4799. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4800. // Read the contents of the framebuffer
  4801. var numberOfChannelsByLine = width * 4;
  4802. var halfHeight = height / 2;
  4803. //Reading datas from WebGL
  4804. var data = engine.readPixels(0, 0, width, height);
  4805. //To flip image on Y axis.
  4806. for (var i = 0; i < halfHeight; i++) {
  4807. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4808. var currentCell = j + i * numberOfChannelsByLine;
  4809. var targetLine = height - i - 1;
  4810. var targetCell = j + targetLine * numberOfChannelsByLine;
  4811. var temp = data[currentCell];
  4812. data[currentCell] = data[targetCell];
  4813. data[targetCell] = temp;
  4814. }
  4815. }
  4816. // Create a 2D canvas to store the result
  4817. if (!screenshotCanvas) {
  4818. screenshotCanvas = document.createElement('canvas');
  4819. }
  4820. screenshotCanvas.width = width;
  4821. screenshotCanvas.height = height;
  4822. var context = screenshotCanvas.getContext('2d');
  4823. // Copy the pixels to a 2D canvas
  4824. var imageData = context.createImageData(width, height);
  4825. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4826. var castData = imageData.data;
  4827. castData.set(data);
  4828. context.putImageData(imageData, 0, 0);
  4829. var base64Image = screenshotCanvas.toDataURL();
  4830. if (successCallback) {
  4831. successCallback(base64Image);
  4832. }
  4833. else {
  4834. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4835. if (("download" in document.createElement("a"))) {
  4836. var a = window.document.createElement("a");
  4837. a.href = base64Image;
  4838. var date = new Date();
  4839. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4840. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4841. window.document.body.appendChild(a);
  4842. a.addEventListener("click", function () {
  4843. a.parentElement.removeChild(a);
  4844. });
  4845. a.click();
  4846. }
  4847. else {
  4848. var newWindow = window.open("");
  4849. var img = newWindow.document.createElement("img");
  4850. img.src = base64Image;
  4851. newWindow.document.body.appendChild(img);
  4852. }
  4853. }
  4854. };
  4855. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4856. var width;
  4857. var height;
  4858. //If a precision value is specified
  4859. if (size.precision) {
  4860. width = Math.round(engine.getRenderWidth() * size.precision);
  4861. height = Math.round(width / engine.getAspectRatio(camera));
  4862. size = { width: width, height: height };
  4863. }
  4864. else if (size.width && size.height) {
  4865. width = size.width;
  4866. height = size.height;
  4867. }
  4868. else if (size.width && !size.height) {
  4869. width = size.width;
  4870. height = Math.round(width / engine.getAspectRatio(camera));
  4871. size = { width: width, height: height };
  4872. }
  4873. else if (size.height && !size.width) {
  4874. height = size.height;
  4875. width = Math.round(height * engine.getAspectRatio(camera));
  4876. size = { width: width, height: height };
  4877. }
  4878. else if (!isNaN(size)) {
  4879. height = size;
  4880. width = size;
  4881. }
  4882. else {
  4883. Tools.Error("Invalid 'size' parameter !");
  4884. return;
  4885. }
  4886. var scene = camera.getScene();
  4887. var previousCamera = null;
  4888. if (scene.activeCamera !== camera) {
  4889. previousCamera = scene.activeCamera;
  4890. scene.activeCamera = camera;
  4891. }
  4892. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4893. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4894. texture.renderList = scene.meshes;
  4895. texture.onAfterRenderObservable.add(function () {
  4896. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4897. });
  4898. scene.incrementRenderId();
  4899. texture.render(true);
  4900. texture.dispose();
  4901. if (previousCamera) {
  4902. scene.activeCamera = previousCamera;
  4903. }
  4904. camera.getProjectionMatrix(true); // Force cache refresh;
  4905. };
  4906. // XHR response validator for local file scenario
  4907. Tools.ValidateXHRData = function (xhr, dataType) {
  4908. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4909. if (dataType === void 0) { dataType = 7; }
  4910. try {
  4911. if (dataType & 1) {
  4912. if (xhr.responseText && xhr.responseText.length > 0) {
  4913. return true;
  4914. }
  4915. else if (dataType === 1) {
  4916. return false;
  4917. }
  4918. }
  4919. if (dataType & 2) {
  4920. // Check header width and height since there is no "TGA" magic number
  4921. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4922. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4923. return true;
  4924. }
  4925. else if (dataType === 2) {
  4926. return false;
  4927. }
  4928. }
  4929. if (dataType & 4) {
  4930. // Check for the "DDS" magic number
  4931. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4932. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4933. return true;
  4934. }
  4935. else {
  4936. return false;
  4937. }
  4938. }
  4939. }
  4940. catch (e) {
  4941. }
  4942. return false;
  4943. };
  4944. Object.defineProperty(Tools, "NoneLogLevel", {
  4945. get: function () {
  4946. return Tools._NoneLogLevel;
  4947. },
  4948. enumerable: true,
  4949. configurable: true
  4950. });
  4951. Object.defineProperty(Tools, "MessageLogLevel", {
  4952. get: function () {
  4953. return Tools._MessageLogLevel;
  4954. },
  4955. enumerable: true,
  4956. configurable: true
  4957. });
  4958. Object.defineProperty(Tools, "WarningLogLevel", {
  4959. get: function () {
  4960. return Tools._WarningLogLevel;
  4961. },
  4962. enumerable: true,
  4963. configurable: true
  4964. });
  4965. Object.defineProperty(Tools, "ErrorLogLevel", {
  4966. get: function () {
  4967. return Tools._ErrorLogLevel;
  4968. },
  4969. enumerable: true,
  4970. configurable: true
  4971. });
  4972. Object.defineProperty(Tools, "AllLogLevel", {
  4973. get: function () {
  4974. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4975. },
  4976. enumerable: true,
  4977. configurable: true
  4978. });
  4979. Tools._AddLogEntry = function (entry) {
  4980. Tools._LogCache = entry + Tools._LogCache;
  4981. if (Tools.OnNewCacheEntry) {
  4982. Tools.OnNewCacheEntry(entry);
  4983. }
  4984. };
  4985. Tools._FormatMessage = function (message) {
  4986. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4987. var date = new Date();
  4988. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4989. };
  4990. Tools._LogDisabled = function (message) {
  4991. // nothing to do
  4992. };
  4993. Tools._LogEnabled = function (message) {
  4994. var formattedMessage = Tools._FormatMessage(message);
  4995. console.log("BJS - " + formattedMessage);
  4996. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4997. Tools._AddLogEntry(entry);
  4998. };
  4999. Tools._WarnDisabled = function (message) {
  5000. // nothing to do
  5001. };
  5002. Tools._WarnEnabled = function (message) {
  5003. var formattedMessage = Tools._FormatMessage(message);
  5004. console.warn("BJS - " + formattedMessage);
  5005. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5006. Tools._AddLogEntry(entry);
  5007. };
  5008. Tools._ErrorDisabled = function (message) {
  5009. // nothing to do
  5010. };
  5011. Tools._ErrorEnabled = function (message) {
  5012. Tools.errorsCount++;
  5013. var formattedMessage = Tools._FormatMessage(message);
  5014. console.error("BJS - " + formattedMessage);
  5015. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5016. Tools._AddLogEntry(entry);
  5017. };
  5018. Object.defineProperty(Tools, "LogCache", {
  5019. get: function () {
  5020. return Tools._LogCache;
  5021. },
  5022. enumerable: true,
  5023. configurable: true
  5024. });
  5025. Tools.ClearLogCache = function () {
  5026. Tools._LogCache = "";
  5027. Tools.errorsCount = 0;
  5028. };
  5029. Object.defineProperty(Tools, "LogLevels", {
  5030. set: function (level) {
  5031. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5032. Tools.Log = Tools._LogEnabled;
  5033. }
  5034. else {
  5035. Tools.Log = Tools._LogDisabled;
  5036. }
  5037. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5038. Tools.Warn = Tools._WarnEnabled;
  5039. }
  5040. else {
  5041. Tools.Warn = Tools._WarnDisabled;
  5042. }
  5043. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5044. Tools.Error = Tools._ErrorEnabled;
  5045. }
  5046. else {
  5047. Tools.Error = Tools._ErrorDisabled;
  5048. }
  5049. },
  5050. enumerable: true,
  5051. configurable: true
  5052. });
  5053. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5054. get: function () {
  5055. return Tools._PerformanceNoneLogLevel;
  5056. },
  5057. enumerable: true,
  5058. configurable: true
  5059. });
  5060. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5061. get: function () {
  5062. return Tools._PerformanceUserMarkLogLevel;
  5063. },
  5064. enumerable: true,
  5065. configurable: true
  5066. });
  5067. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5068. get: function () {
  5069. return Tools._PerformanceConsoleLogLevel;
  5070. },
  5071. enumerable: true,
  5072. configurable: true
  5073. });
  5074. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5075. set: function (level) {
  5076. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5077. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5078. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5079. return;
  5080. }
  5081. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5082. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5083. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5084. return;
  5085. }
  5086. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5087. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5093. };
  5094. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5095. };
  5096. Tools._StartUserMark = function (counterName, condition) {
  5097. if (condition === void 0) { condition = true; }
  5098. if (!condition || !Tools._performance.mark) {
  5099. return;
  5100. }
  5101. Tools._performance.mark(counterName + "-Begin");
  5102. };
  5103. Tools._EndUserMark = function (counterName, condition) {
  5104. if (condition === void 0) { condition = true; }
  5105. if (!condition || !Tools._performance.mark) {
  5106. return;
  5107. }
  5108. Tools._performance.mark(counterName + "-End");
  5109. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5110. };
  5111. Tools._StartPerformanceConsole = function (counterName, condition) {
  5112. if (condition === void 0) { condition = true; }
  5113. if (!condition) {
  5114. return;
  5115. }
  5116. Tools._StartUserMark(counterName, condition);
  5117. if (console.time) {
  5118. console.time(counterName);
  5119. }
  5120. };
  5121. Tools._EndPerformanceConsole = function (counterName, condition) {
  5122. if (condition === void 0) { condition = true; }
  5123. if (!condition) {
  5124. return;
  5125. }
  5126. Tools._EndUserMark(counterName, condition);
  5127. if (console.time) {
  5128. console.timeEnd(counterName);
  5129. }
  5130. };
  5131. Object.defineProperty(Tools, "Now", {
  5132. get: function () {
  5133. if (window.performance && window.performance.now) {
  5134. return window.performance.now();
  5135. }
  5136. return new Date().getTime();
  5137. },
  5138. enumerable: true,
  5139. configurable: true
  5140. });
  5141. /**
  5142. * This method will return the name of the class used to create the instance of the given object.
  5143. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5144. * @param object the object to get the class name from
  5145. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5146. */
  5147. Tools.getClassName = function (object, isType) {
  5148. if (isType === void 0) { isType = false; }
  5149. var name = null;
  5150. if (!isType && object.getClassName) {
  5151. name = object.getClassName();
  5152. }
  5153. else {
  5154. if (object instanceof Object) {
  5155. var classObj = isType ? object : Object.getPrototypeOf(object);
  5156. name = classObj.constructor["__bjsclassName__"];
  5157. }
  5158. if (!name) {
  5159. name = typeof object;
  5160. }
  5161. }
  5162. return name;
  5163. };
  5164. Tools.first = function (array, predicate) {
  5165. for (var _i = 0; _i < array.length; _i++) {
  5166. var el = array[_i];
  5167. if (predicate(el)) {
  5168. return el;
  5169. }
  5170. }
  5171. };
  5172. /**
  5173. * 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.
  5174. * @param array
  5175. */
  5176. Tools.arrayOrStringFeeder = function (array) {
  5177. return function (index) {
  5178. if (index >= array.length) {
  5179. return null;
  5180. }
  5181. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5182. if (val && val.getHashCode) {
  5183. val = val.getHashCode();
  5184. }
  5185. if (typeof val === "string") {
  5186. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5187. }
  5188. return val;
  5189. };
  5190. };
  5191. /**
  5192. * Compute the hashCode of a stream of number
  5193. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5194. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5195. * @return the hash code computed
  5196. */
  5197. Tools.hashCodeFromStream = function (feeder) {
  5198. // Based from here: http://stackoverflow.com/a/7616484/802124
  5199. var hash = 0;
  5200. var index = 0;
  5201. var chr = feeder(index++);
  5202. while (chr != null) {
  5203. hash = ((hash << 5) - hash) + chr;
  5204. hash |= 0; // Convert to 32bit integer
  5205. chr = feeder(index++);
  5206. }
  5207. return hash;
  5208. };
  5209. Tools.BaseUrl = "";
  5210. Tools.CorsBehavior = "anonymous";
  5211. Tools.UseFallbackTexture = true;
  5212. // Logs
  5213. Tools._NoneLogLevel = 0;
  5214. Tools._MessageLogLevel = 1;
  5215. Tools._WarningLogLevel = 2;
  5216. Tools._ErrorLogLevel = 4;
  5217. Tools._LogCache = "";
  5218. Tools.errorsCount = 0;
  5219. Tools.Log = Tools._LogEnabled;
  5220. Tools.Warn = Tools._WarnEnabled;
  5221. Tools.Error = Tools._ErrorEnabled;
  5222. // Performances
  5223. Tools._PerformanceNoneLogLevel = 0;
  5224. Tools._PerformanceUserMarkLogLevel = 1;
  5225. Tools._PerformanceConsoleLogLevel = 2;
  5226. Tools._performance = window.performance;
  5227. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5228. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5229. return Tools;
  5230. })();
  5231. BABYLON.Tools = Tools;
  5232. /**
  5233. * Use this className as a decorator on a given class definition to add it a name.
  5234. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5235. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5236. * @param name
  5237. */
  5238. function className(name) {
  5239. return function (target) {
  5240. target["__bjsclassName__"] = name;
  5241. };
  5242. }
  5243. BABYLON.className = className;
  5244. /**
  5245. * An implementation of a loop for asynchronous functions.
  5246. */
  5247. var AsyncLoop = (function () {
  5248. /**
  5249. * Constroctor.
  5250. * @param iterations the number of iterations.
  5251. * @param _fn the function to run each iteration
  5252. * @param _successCallback the callback that will be called upon succesful execution
  5253. * @param offset starting offset.
  5254. */
  5255. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5256. if (offset === void 0) { offset = 0; }
  5257. this.iterations = iterations;
  5258. this._fn = _fn;
  5259. this._successCallback = _successCallback;
  5260. this.index = offset - 1;
  5261. this._done = false;
  5262. }
  5263. /**
  5264. * Execute the next iteration. Must be called after the last iteration was finished.
  5265. */
  5266. AsyncLoop.prototype.executeNext = function () {
  5267. if (!this._done) {
  5268. if (this.index + 1 < this.iterations) {
  5269. ++this.index;
  5270. this._fn(this);
  5271. }
  5272. else {
  5273. this.breakLoop();
  5274. }
  5275. }
  5276. };
  5277. /**
  5278. * Break the loop and run the success callback.
  5279. */
  5280. AsyncLoop.prototype.breakLoop = function () {
  5281. this._done = true;
  5282. this._successCallback();
  5283. };
  5284. /**
  5285. * Helper function
  5286. */
  5287. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5288. if (offset === void 0) { offset = 0; }
  5289. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5290. loop.executeNext();
  5291. return loop;
  5292. };
  5293. /**
  5294. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5295. * @param iterations total number of iterations
  5296. * @param syncedIterations number of synchronous iterations in each async iteration.
  5297. * @param fn the function to call each iteration.
  5298. * @param callback a success call back that will be called when iterating stops.
  5299. * @param breakFunction a break condition (optional)
  5300. * @param timeout timeout settings for the setTimeout function. default - 0.
  5301. * @constructor
  5302. */
  5303. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5304. if (timeout === void 0) { timeout = 0; }
  5305. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5306. if (breakFunction && breakFunction())
  5307. loop.breakLoop();
  5308. else {
  5309. setTimeout(function () {
  5310. for (var i = 0; i < syncedIterations; ++i) {
  5311. var iteration = (loop.index * syncedIterations) + i;
  5312. if (iteration >= iterations)
  5313. break;
  5314. fn(iteration);
  5315. if (breakFunction && breakFunction()) {
  5316. loop.breakLoop();
  5317. break;
  5318. }
  5319. }
  5320. loop.executeNext();
  5321. }, timeout);
  5322. }
  5323. }, callback);
  5324. };
  5325. return AsyncLoop;
  5326. })();
  5327. BABYLON.AsyncLoop = AsyncLoop;
  5328. })(BABYLON || (BABYLON = {}));
  5329. var BABYLON;
  5330. (function (BABYLON) {
  5331. var Internals;
  5332. (function (Internals) {
  5333. var _AlphaState = (function () {
  5334. function _AlphaState() {
  5335. this._isAlphaBlendDirty = false;
  5336. this._isBlendFunctionParametersDirty = false;
  5337. this._alphaBlend = false;
  5338. this._blendFunctionParameters = new Array(4);
  5339. }
  5340. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5341. get: function () {
  5342. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5348. get: function () {
  5349. return this._alphaBlend;
  5350. },
  5351. set: function (value) {
  5352. if (this._alphaBlend === value) {
  5353. return;
  5354. }
  5355. this._alphaBlend = value;
  5356. this._isAlphaBlendDirty = true;
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5362. if (this._blendFunctionParameters[0] === value0 &&
  5363. this._blendFunctionParameters[1] === value1 &&
  5364. this._blendFunctionParameters[2] === value2 &&
  5365. this._blendFunctionParameters[3] === value3) {
  5366. return;
  5367. }
  5368. this._blendFunctionParameters[0] = value0;
  5369. this._blendFunctionParameters[1] = value1;
  5370. this._blendFunctionParameters[2] = value2;
  5371. this._blendFunctionParameters[3] = value3;
  5372. this._isBlendFunctionParametersDirty = true;
  5373. };
  5374. _AlphaState.prototype.reset = function () {
  5375. this._alphaBlend = false;
  5376. this._blendFunctionParameters[0] = null;
  5377. this._blendFunctionParameters[1] = null;
  5378. this._blendFunctionParameters[2] = null;
  5379. this._blendFunctionParameters[3] = null;
  5380. this._isAlphaBlendDirty = true;
  5381. this._isBlendFunctionParametersDirty = false;
  5382. };
  5383. _AlphaState.prototype.apply = function (gl) {
  5384. if (!this.isDirty) {
  5385. return;
  5386. }
  5387. // Alpha blend
  5388. if (this._isAlphaBlendDirty) {
  5389. if (this._alphaBlend) {
  5390. gl.enable(gl.BLEND);
  5391. }
  5392. else {
  5393. gl.disable(gl.BLEND);
  5394. }
  5395. this._isAlphaBlendDirty = false;
  5396. }
  5397. // Alpha function
  5398. if (this._isBlendFunctionParametersDirty) {
  5399. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5400. this._isBlendFunctionParametersDirty = false;
  5401. }
  5402. };
  5403. return _AlphaState;
  5404. })();
  5405. Internals._AlphaState = _AlphaState;
  5406. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5407. })(BABYLON || (BABYLON = {}));
  5408. var BABYLON;
  5409. (function (BABYLON) {
  5410. var Internals;
  5411. (function (Internals) {
  5412. var _DepthCullingState = (function () {
  5413. function _DepthCullingState() {
  5414. this._isDepthTestDirty = false;
  5415. this._isDepthMaskDirty = false;
  5416. this._isDepthFuncDirty = false;
  5417. this._isCullFaceDirty = false;
  5418. this._isCullDirty = false;
  5419. this._isZOffsetDirty = false;
  5420. }
  5421. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5422. get: function () {
  5423. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5424. },
  5425. enumerable: true,
  5426. configurable: true
  5427. });
  5428. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5429. get: function () {
  5430. return this._zOffset;
  5431. },
  5432. set: function (value) {
  5433. if (this._zOffset === value) {
  5434. return;
  5435. }
  5436. this._zOffset = value;
  5437. this._isZOffsetDirty = true;
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5443. get: function () {
  5444. return this._cullFace;
  5445. },
  5446. set: function (value) {
  5447. if (this._cullFace === value) {
  5448. return;
  5449. }
  5450. this._cullFace = value;
  5451. this._isCullFaceDirty = true;
  5452. },
  5453. enumerable: true,
  5454. configurable: true
  5455. });
  5456. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5457. get: function () {
  5458. return this._cull;
  5459. },
  5460. set: function (value) {
  5461. if (this._cull === value) {
  5462. return;
  5463. }
  5464. this._cull = value;
  5465. this._isCullDirty = true;
  5466. },
  5467. enumerable: true,
  5468. configurable: true
  5469. });
  5470. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5471. get: function () {
  5472. return this._depthFunc;
  5473. },
  5474. set: function (value) {
  5475. if (this._depthFunc === value) {
  5476. return;
  5477. }
  5478. this._depthFunc = value;
  5479. this._isDepthFuncDirty = true;
  5480. },
  5481. enumerable: true,
  5482. configurable: true
  5483. });
  5484. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5485. get: function () {
  5486. return this._depthMask;
  5487. },
  5488. set: function (value) {
  5489. if (this._depthMask === value) {
  5490. return;
  5491. }
  5492. this._depthMask = value;
  5493. this._isDepthMaskDirty = true;
  5494. },
  5495. enumerable: true,
  5496. configurable: true
  5497. });
  5498. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5499. get: function () {
  5500. return this._depthTest;
  5501. },
  5502. set: function (value) {
  5503. if (this._depthTest === value) {
  5504. return;
  5505. }
  5506. this._depthTest = value;
  5507. this._isDepthTestDirty = true;
  5508. },
  5509. enumerable: true,
  5510. configurable: true
  5511. });
  5512. _DepthCullingState.prototype.reset = function () {
  5513. this._depthMask = true;
  5514. this._depthTest = true;
  5515. this._depthFunc = null;
  5516. this._cull = null;
  5517. this._cullFace = null;
  5518. this._zOffset = 0;
  5519. this._isDepthTestDirty = true;
  5520. this._isDepthMaskDirty = true;
  5521. this._isDepthFuncDirty = false;
  5522. this._isCullFaceDirty = false;
  5523. this._isCullDirty = false;
  5524. this._isZOffsetDirty = false;
  5525. };
  5526. _DepthCullingState.prototype.apply = function (gl) {
  5527. if (!this.isDirty) {
  5528. return;
  5529. }
  5530. // Cull
  5531. if (this._isCullDirty) {
  5532. if (this.cull) {
  5533. gl.enable(gl.CULL_FACE);
  5534. }
  5535. else {
  5536. gl.disable(gl.CULL_FACE);
  5537. }
  5538. this._isCullDirty = false;
  5539. }
  5540. // Cull face
  5541. if (this._isCullFaceDirty) {
  5542. gl.cullFace(this.cullFace);
  5543. this._isCullFaceDirty = false;
  5544. }
  5545. // Depth mask
  5546. if (this._isDepthMaskDirty) {
  5547. gl.depthMask(this.depthMask);
  5548. this._isDepthMaskDirty = false;
  5549. }
  5550. // Depth test
  5551. if (this._isDepthTestDirty) {
  5552. if (this.depthTest) {
  5553. gl.enable(gl.DEPTH_TEST);
  5554. }
  5555. else {
  5556. gl.disable(gl.DEPTH_TEST);
  5557. }
  5558. this._isDepthTestDirty = false;
  5559. }
  5560. // Depth func
  5561. if (this._isDepthFuncDirty) {
  5562. gl.depthFunc(this.depthFunc);
  5563. this._isDepthFuncDirty = false;
  5564. }
  5565. // zOffset
  5566. if (this._isZOffsetDirty) {
  5567. if (this.zOffset) {
  5568. gl.enable(gl.POLYGON_OFFSET_FILL);
  5569. gl.polygonOffset(this.zOffset, 0);
  5570. }
  5571. else {
  5572. gl.disable(gl.POLYGON_OFFSET_FILL);
  5573. }
  5574. this._isZOffsetDirty = false;
  5575. }
  5576. };
  5577. return _DepthCullingState;
  5578. })();
  5579. Internals._DepthCullingState = _DepthCullingState;
  5580. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5581. })(BABYLON || (BABYLON = {}));
  5582. var BABYLON;
  5583. (function (BABYLON) {
  5584. var compileShader = function (gl, source, type, defines) {
  5585. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5586. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5587. gl.compileShader(shader);
  5588. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5589. throw new Error(gl.getShaderInfoLog(shader));
  5590. }
  5591. return shader;
  5592. };
  5593. var getWebGLTextureType = function (gl, type) {
  5594. var textureType = gl.UNSIGNED_BYTE;
  5595. if (type === Engine.TEXTURETYPE_FLOAT)
  5596. textureType = gl.FLOAT;
  5597. return textureType;
  5598. };
  5599. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5600. var magFilter = gl.NEAREST;
  5601. var minFilter = gl.NEAREST;
  5602. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5603. magFilter = gl.LINEAR;
  5604. if (generateMipMaps) {
  5605. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5606. }
  5607. else {
  5608. minFilter = gl.LINEAR;
  5609. }
  5610. }
  5611. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5612. magFilter = gl.LINEAR;
  5613. if (generateMipMaps) {
  5614. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5615. }
  5616. else {
  5617. minFilter = gl.LINEAR;
  5618. }
  5619. }
  5620. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5621. magFilter = gl.NEAREST;
  5622. if (generateMipMaps) {
  5623. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5624. }
  5625. else {
  5626. minFilter = gl.NEAREST;
  5627. }
  5628. }
  5629. return {
  5630. min: minFilter,
  5631. mag: magFilter
  5632. };
  5633. };
  5634. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5636. var engine = scene.getEngine();
  5637. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5638. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5639. gl.bindTexture(gl.TEXTURE_2D, texture);
  5640. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5641. texture._baseWidth = width;
  5642. texture._baseHeight = height;
  5643. texture._width = potWidth;
  5644. texture._height = potHeight;
  5645. texture.isReady = true;
  5646. processFunction(potWidth, potHeight);
  5647. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5650. if (!noMipmap && !isCompressed) {
  5651. gl.generateMipmap(gl.TEXTURE_2D);
  5652. }
  5653. gl.bindTexture(gl.TEXTURE_2D, null);
  5654. engine.resetTextureCache();
  5655. scene._removePendingData(texture);
  5656. if (onLoad) {
  5657. onLoad();
  5658. }
  5659. };
  5660. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5661. var img;
  5662. var onload = function () {
  5663. loadedImages[index] = img;
  5664. loadedImages._internalCount++;
  5665. scene._removePendingData(img);
  5666. if (loadedImages._internalCount === 6) {
  5667. onfinish(loadedImages);
  5668. }
  5669. };
  5670. var onerror = function () {
  5671. scene._removePendingData(img);
  5672. };
  5673. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5674. scene._addPendingData(img);
  5675. };
  5676. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5677. var loadedImages = [];
  5678. loadedImages._internalCount = 0;
  5679. for (var index = 0; index < 6; index++) {
  5680. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5681. }
  5682. };
  5683. var InstancingAttributeInfo = (function () {
  5684. function InstancingAttributeInfo() {
  5685. }
  5686. return InstancingAttributeInfo;
  5687. })();
  5688. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5689. var EngineCapabilities = (function () {
  5690. function EngineCapabilities() {
  5691. }
  5692. return EngineCapabilities;
  5693. })();
  5694. BABYLON.EngineCapabilities = EngineCapabilities;
  5695. /**
  5696. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5697. */
  5698. var Engine = (function () {
  5699. /**
  5700. * @constructor
  5701. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5702. * @param {boolean} [antialias] - enable antialias
  5703. * @param options - further options to be sent to the getContext function
  5704. */
  5705. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5706. var _this = this;
  5707. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5708. // Public members
  5709. this.isFullscreen = false;
  5710. this.isPointerLock = false;
  5711. this.cullBackFaces = true;
  5712. this.renderEvenInBackground = true;
  5713. // To enable/disable IDB support and avoid XHR on .manifest
  5714. this.enableOfflineSupport = true;
  5715. this.scenes = new Array();
  5716. this._windowIsBackground = false;
  5717. this._webGLVersion = "1.0";
  5718. this._drawCalls = 0;
  5719. this._renderingQueueLaunched = false;
  5720. this._activeRenderLoops = [];
  5721. // FPS
  5722. this.fpsRange = 60;
  5723. this.previousFramesDuration = [];
  5724. this.fps = 60;
  5725. this.deltaTime = 0;
  5726. // States
  5727. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5728. this._alphaState = new BABYLON.Internals._AlphaState();
  5729. this._alphaMode = Engine.ALPHA_DISABLE;
  5730. // Cache
  5731. this._loadedTexturesCache = new Array();
  5732. this._maxTextureChannels = 16;
  5733. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5734. this._compiledEffects = {};
  5735. this._uintIndicesCurrentlySet = false;
  5736. this._renderingCanvas = canvas;
  5737. this._externalData = new BABYLON.StringDictionary();
  5738. options = options || {};
  5739. options.antialias = antialias;
  5740. if (options.preserveDrawingBuffer === undefined) {
  5741. options.preserveDrawingBuffer = false;
  5742. }
  5743. // GL
  5744. //try {
  5745. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5746. // if (this._gl) {
  5747. // this._webGLVersion = "2.0";
  5748. // }
  5749. //} catch (e) {
  5750. // // Do nothing
  5751. //}
  5752. if (!this._gl) {
  5753. try {
  5754. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5755. }
  5756. catch (e) {
  5757. throw new Error("WebGL not supported");
  5758. }
  5759. }
  5760. if (!this._gl) {
  5761. throw new Error("WebGL not supported");
  5762. }
  5763. this._onBlur = function () {
  5764. _this._windowIsBackground = true;
  5765. };
  5766. this._onFocus = function () {
  5767. _this._windowIsBackground = false;
  5768. };
  5769. window.addEventListener("blur", this._onBlur);
  5770. window.addEventListener("focus", this._onFocus);
  5771. // Viewport
  5772. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5773. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5774. this.resize();
  5775. // Caps
  5776. this._caps = new EngineCapabilities();
  5777. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5778. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5779. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5780. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5781. // Infos
  5782. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5783. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5784. if (rendererInfo != null) {
  5785. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5786. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5787. }
  5788. if (!this._glVendor) {
  5789. this._glVendor = "Unknown vendor";
  5790. }
  5791. if (!this._glRenderer) {
  5792. this._glRenderer = "Unknown renderer";
  5793. }
  5794. // Extensions
  5795. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5796. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5797. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5798. 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');
  5799. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5800. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5801. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5802. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5803. this._caps.highPrecisionShaderSupported = true;
  5804. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5805. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5806. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5807. if (this._gl.getShaderPrecisionFormat) {
  5808. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5809. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5810. }
  5811. // Depth buffer
  5812. this.setDepthBuffer(true);
  5813. this.setDepthFunctionToLessOrEqual();
  5814. this.setDepthWrite(true);
  5815. // Fullscreen
  5816. this._onFullscreenChange = function () {
  5817. if (document.fullscreen !== undefined) {
  5818. _this.isFullscreen = document.fullscreen;
  5819. }
  5820. else if (document.mozFullScreen !== undefined) {
  5821. _this.isFullscreen = document.mozFullScreen;
  5822. }
  5823. else if (document.webkitIsFullScreen !== undefined) {
  5824. _this.isFullscreen = document.webkitIsFullScreen;
  5825. }
  5826. else if (document.msIsFullScreen !== undefined) {
  5827. _this.isFullscreen = document.msIsFullScreen;
  5828. }
  5829. // Pointer lock
  5830. if (_this.isFullscreen && _this._pointerLockRequested) {
  5831. canvas.requestPointerLock = canvas.requestPointerLock ||
  5832. canvas.msRequestPointerLock ||
  5833. canvas.mozRequestPointerLock ||
  5834. canvas.webkitRequestPointerLock;
  5835. if (canvas.requestPointerLock) {
  5836. canvas.requestPointerLock();
  5837. }
  5838. }
  5839. };
  5840. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5841. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5842. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5843. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5844. // Pointer lock
  5845. this._onPointerLockChange = function () {
  5846. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5847. document.webkitPointerLockElement === canvas ||
  5848. document.msPointerLockElement === canvas ||
  5849. document.pointerLockElement === canvas);
  5850. };
  5851. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5852. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5853. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5854. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5855. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5856. Engine.audioEngine = new BABYLON.AudioEngine();
  5857. }
  5858. //default loading screen
  5859. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5860. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5861. }
  5862. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5863. get: function () {
  5864. return Engine._ALPHA_DISABLE;
  5865. },
  5866. enumerable: true,
  5867. configurable: true
  5868. });
  5869. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5870. get: function () {
  5871. return Engine._ALPHA_ONEONE;
  5872. },
  5873. enumerable: true,
  5874. configurable: true
  5875. });
  5876. Object.defineProperty(Engine, "ALPHA_ADD", {
  5877. get: function () {
  5878. return Engine._ALPHA_ADD;
  5879. },
  5880. enumerable: true,
  5881. configurable: true
  5882. });
  5883. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5884. get: function () {
  5885. return Engine._ALPHA_COMBINE;
  5886. },
  5887. enumerable: true,
  5888. configurable: true
  5889. });
  5890. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5891. get: function () {
  5892. return Engine._ALPHA_SUBTRACT;
  5893. },
  5894. enumerable: true,
  5895. configurable: true
  5896. });
  5897. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5898. get: function () {
  5899. return Engine._ALPHA_MULTIPLY;
  5900. },
  5901. enumerable: true,
  5902. configurable: true
  5903. });
  5904. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5905. get: function () {
  5906. return Engine._ALPHA_MAXIMIZED;
  5907. },
  5908. enumerable: true,
  5909. configurable: true
  5910. });
  5911. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5912. get: function () {
  5913. return Engine._DELAYLOADSTATE_NONE;
  5914. },
  5915. enumerable: true,
  5916. configurable: true
  5917. });
  5918. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5919. get: function () {
  5920. return Engine._DELAYLOADSTATE_LOADED;
  5921. },
  5922. enumerable: true,
  5923. configurable: true
  5924. });
  5925. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5926. get: function () {
  5927. return Engine._DELAYLOADSTATE_LOADING;
  5928. },
  5929. enumerable: true,
  5930. configurable: true
  5931. });
  5932. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5933. get: function () {
  5934. return Engine._DELAYLOADSTATE_NOTLOADED;
  5935. },
  5936. enumerable: true,
  5937. configurable: true
  5938. });
  5939. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5940. get: function () {
  5941. return Engine._TEXTUREFORMAT_ALPHA;
  5942. },
  5943. enumerable: true,
  5944. configurable: true
  5945. });
  5946. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5947. get: function () {
  5948. return Engine._TEXTUREFORMAT_LUMINANCE;
  5949. },
  5950. enumerable: true,
  5951. configurable: true
  5952. });
  5953. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5954. get: function () {
  5955. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5956. },
  5957. enumerable: true,
  5958. configurable: true
  5959. });
  5960. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5961. get: function () {
  5962. return Engine._TEXTUREFORMAT_RGB;
  5963. },
  5964. enumerable: true,
  5965. configurable: true
  5966. });
  5967. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5968. get: function () {
  5969. return Engine._TEXTUREFORMAT_RGBA;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5975. get: function () {
  5976. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5977. },
  5978. enumerable: true,
  5979. configurable: true
  5980. });
  5981. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5982. get: function () {
  5983. return Engine._TEXTURETYPE_FLOAT;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. Object.defineProperty(Engine, "Version", {
  5989. get: function () {
  5990. return "2.4.0-beta";
  5991. },
  5992. enumerable: true,
  5993. configurable: true
  5994. });
  5995. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5996. get: function () {
  5997. return this._webGLVersion;
  5998. },
  5999. enumerable: true,
  6000. configurable: true
  6001. });
  6002. Engine.prototype._prepareWorkingCanvas = function () {
  6003. if (this._workingCanvas) {
  6004. return;
  6005. }
  6006. this._workingCanvas = document.createElement("canvas");
  6007. this._workingContext = this._workingCanvas.getContext("2d");
  6008. };
  6009. Engine.prototype.resetTextureCache = function () {
  6010. for (var index = 0; index < this._maxTextureChannels; index++) {
  6011. this._activeTexturesCache[index] = null;
  6012. }
  6013. };
  6014. Engine.prototype.getGlInfo = function () {
  6015. return {
  6016. vendor: this._glVendor,
  6017. renderer: this._glRenderer,
  6018. version: this._glVersion
  6019. };
  6020. };
  6021. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6022. if (useScreen === void 0) { useScreen = false; }
  6023. var viewport = camera.viewport;
  6024. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6025. };
  6026. Engine.prototype.getRenderWidth = function (useScreen) {
  6027. if (useScreen === void 0) { useScreen = false; }
  6028. if (!useScreen && this._currentRenderTarget) {
  6029. return this._currentRenderTarget._width;
  6030. }
  6031. return this._renderingCanvas.width;
  6032. };
  6033. Engine.prototype.getRenderHeight = function (useScreen) {
  6034. if (useScreen === void 0) { useScreen = false; }
  6035. if (!useScreen && this._currentRenderTarget) {
  6036. return this._currentRenderTarget._height;
  6037. }
  6038. return this._renderingCanvas.height;
  6039. };
  6040. Engine.prototype.getRenderingCanvas = function () {
  6041. return this._renderingCanvas;
  6042. };
  6043. Engine.prototype.getRenderingCanvasClientRect = function () {
  6044. return this._renderingCanvas.getBoundingClientRect();
  6045. };
  6046. Engine.prototype.setHardwareScalingLevel = function (level) {
  6047. this._hardwareScalingLevel = level;
  6048. this.resize();
  6049. };
  6050. Engine.prototype.getHardwareScalingLevel = function () {
  6051. return this._hardwareScalingLevel;
  6052. };
  6053. Engine.prototype.getLoadedTexturesCache = function () {
  6054. return this._loadedTexturesCache;
  6055. };
  6056. Engine.prototype.getCaps = function () {
  6057. return this._caps;
  6058. };
  6059. Object.defineProperty(Engine.prototype, "drawCalls", {
  6060. get: function () {
  6061. return this._drawCalls;
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. // Methods
  6067. Engine.prototype.resetDrawCalls = function () {
  6068. this._drawCalls = 0;
  6069. };
  6070. Engine.prototype.getDepthFunction = function () {
  6071. return this._depthCullingState.depthFunc;
  6072. };
  6073. Engine.prototype.setDepthFunction = function (depthFunc) {
  6074. this._depthCullingState.depthFunc = depthFunc;
  6075. };
  6076. Engine.prototype.setDepthFunctionToGreater = function () {
  6077. this._depthCullingState.depthFunc = this._gl.GREATER;
  6078. };
  6079. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6080. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6081. };
  6082. Engine.prototype.setDepthFunctionToLess = function () {
  6083. this._depthCullingState.depthFunc = this._gl.LESS;
  6084. };
  6085. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6086. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6087. };
  6088. /**
  6089. * stop executing a render loop function and remove it from the execution array
  6090. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6091. */
  6092. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6093. if (!renderFunction) {
  6094. this._activeRenderLoops = [];
  6095. return;
  6096. }
  6097. var index = this._activeRenderLoops.indexOf(renderFunction);
  6098. if (index >= 0) {
  6099. this._activeRenderLoops.splice(index, 1);
  6100. }
  6101. };
  6102. Engine.prototype._renderLoop = function () {
  6103. var shouldRender = true;
  6104. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6105. shouldRender = false;
  6106. }
  6107. if (shouldRender) {
  6108. // Start new frame
  6109. this.beginFrame();
  6110. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6111. var renderFunction = this._activeRenderLoops[index];
  6112. renderFunction();
  6113. }
  6114. // Present
  6115. this.endFrame();
  6116. }
  6117. if (this._activeRenderLoops.length > 0) {
  6118. // Register new frame
  6119. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6120. }
  6121. else {
  6122. this._renderingQueueLaunched = false;
  6123. }
  6124. };
  6125. /**
  6126. * Register and execute a render loop. The engine can have more than one render function.
  6127. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6128. * @example
  6129. * engine.runRenderLoop(function () {
  6130. * scene.render()
  6131. * })
  6132. */
  6133. Engine.prototype.runRenderLoop = function (renderFunction) {
  6134. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6135. return;
  6136. }
  6137. this._activeRenderLoops.push(renderFunction);
  6138. if (!this._renderingQueueLaunched) {
  6139. this._renderingQueueLaunched = true;
  6140. this._bindedRenderFunction = this._renderLoop.bind(this);
  6141. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6142. }
  6143. };
  6144. /**
  6145. * Toggle full screen mode.
  6146. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6147. */
  6148. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6149. if (this.isFullscreen) {
  6150. BABYLON.Tools.ExitFullscreen();
  6151. }
  6152. else {
  6153. this._pointerLockRequested = requestPointerLock;
  6154. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6155. }
  6156. };
  6157. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6158. this.applyStates();
  6159. if (backBuffer) {
  6160. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6161. }
  6162. if (depthStencil && this._depthCullingState.depthMask) {
  6163. this._gl.clearDepth(1.0);
  6164. }
  6165. var mode = 0;
  6166. if (backBuffer) {
  6167. mode |= this._gl.COLOR_BUFFER_BIT;
  6168. }
  6169. if (depthStencil && this._depthCullingState.depthMask) {
  6170. mode |= this._gl.DEPTH_BUFFER_BIT;
  6171. }
  6172. this._gl.clear(mode);
  6173. };
  6174. /**
  6175. * Set the WebGL's viewport
  6176. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6177. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6178. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6179. */
  6180. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6181. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6182. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6183. var x = viewport.x || 0;
  6184. var y = viewport.y || 0;
  6185. this._cachedViewport = viewport;
  6186. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6187. };
  6188. /**
  6189. * Directly set the WebGL Viewport
  6190. * The x, y, width & height are directly passed to the WebGL call
  6191. * @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.
  6192. */
  6193. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6194. var currentViewport = this._cachedViewport;
  6195. this._cachedViewport = null;
  6196. this._gl.viewport(x, y, width, height);
  6197. return currentViewport;
  6198. };
  6199. Engine.prototype.beginFrame = function () {
  6200. this._measureFps();
  6201. };
  6202. Engine.prototype.endFrame = function () {
  6203. //this.flushFramebuffer();
  6204. };
  6205. /**
  6206. * resize the view according to the canvas' size.
  6207. * @example
  6208. * window.addEventListener("resize", function () {
  6209. * engine.resize();
  6210. * });
  6211. */
  6212. Engine.prototype.resize = function () {
  6213. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6214. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6215. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6216. for (var index = 0; index < this.scenes.length; index++) {
  6217. var scene = this.scenes[index];
  6218. if (scene.debugLayer.isVisible()) {
  6219. scene.debugLayer._syncPositions();
  6220. }
  6221. }
  6222. };
  6223. /**
  6224. * force a specific size of the canvas
  6225. * @param {number} width - the new canvas' width
  6226. * @param {number} height - the new canvas' height
  6227. */
  6228. Engine.prototype.setSize = function (width, height) {
  6229. this._renderingCanvas.width = width;
  6230. this._renderingCanvas.height = height;
  6231. for (var index = 0; index < this.scenes.length; index++) {
  6232. var scene = this.scenes[index];
  6233. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6234. var cam = scene.cameras[camIndex];
  6235. cam._currentRenderId = 0;
  6236. }
  6237. }
  6238. };
  6239. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6240. this._currentRenderTarget = texture;
  6241. var gl = this._gl;
  6242. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6243. if (texture.isCube) {
  6244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6245. }
  6246. else {
  6247. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6248. }
  6249. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6250. this.wipeCaches();
  6251. };
  6252. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6253. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6254. this._currentRenderTarget = null;
  6255. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6256. var gl = this._gl;
  6257. gl.bindTexture(gl.TEXTURE_2D, texture);
  6258. gl.generateMipmap(gl.TEXTURE_2D);
  6259. gl.bindTexture(gl.TEXTURE_2D, null);
  6260. }
  6261. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6262. };
  6263. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6264. if (texture.generateMipMaps) {
  6265. var gl = this._gl;
  6266. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6267. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6268. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6269. }
  6270. };
  6271. Engine.prototype.flushFramebuffer = function () {
  6272. this._gl.flush();
  6273. };
  6274. Engine.prototype.restoreDefaultFramebuffer = function () {
  6275. this._currentRenderTarget = null;
  6276. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6277. this.setViewport(this._cachedViewport);
  6278. this.wipeCaches();
  6279. };
  6280. // VBOs
  6281. Engine.prototype._resetVertexBufferBinding = function () {
  6282. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  6283. this._cachedVertexBuffers = null;
  6284. };
  6285. Engine.prototype.createVertexBuffer = function (vertices) {
  6286. var vbo = this._gl.createBuffer();
  6287. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6288. if (vertices instanceof Float32Array) {
  6289. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6290. }
  6291. else {
  6292. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6293. }
  6294. this._resetVertexBufferBinding();
  6295. vbo.references = 1;
  6296. return vbo;
  6297. };
  6298. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6299. var vbo = this._gl.createBuffer();
  6300. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6301. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6302. this._resetVertexBufferBinding();
  6303. vbo.references = 1;
  6304. return vbo;
  6305. };
  6306. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6307. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6308. if (offset === undefined) {
  6309. offset = 0;
  6310. }
  6311. if (vertices instanceof Float32Array) {
  6312. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6313. }
  6314. else {
  6315. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6316. }
  6317. this._resetVertexBufferBinding();
  6318. };
  6319. Engine.prototype._resetIndexBufferBinding = function () {
  6320. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6321. this._cachedIndexBuffer = null;
  6322. };
  6323. Engine.prototype.createIndexBuffer = function (indices) {
  6324. var vbo = this._gl.createBuffer();
  6325. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6326. // Check for 32 bits indices
  6327. var arrayBuffer;
  6328. var need32Bits = false;
  6329. if (this._caps.uintIndices) {
  6330. for (var index = 0; index < indices.length; index++) {
  6331. if (indices[index] > 65535) {
  6332. need32Bits = true;
  6333. break;
  6334. }
  6335. }
  6336. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6337. }
  6338. else {
  6339. arrayBuffer = new Uint16Array(indices);
  6340. }
  6341. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6342. this._resetIndexBufferBinding();
  6343. vbo.references = 1;
  6344. vbo.is32Bits = need32Bits;
  6345. return vbo;
  6346. };
  6347. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6348. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6349. this._cachedVertexBuffers = vertexBuffer;
  6350. this._cachedEffectForVertexBuffers = effect;
  6351. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6352. var offset = 0;
  6353. for (var index = 0; index < vertexDeclaration.length; index++) {
  6354. var order = effect.getAttributeLocation(index);
  6355. if (order >= 0) {
  6356. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6357. }
  6358. offset += vertexDeclaration[index] * 4;
  6359. }
  6360. }
  6361. if (this._cachedIndexBuffer !== indexBuffer) {
  6362. this._cachedIndexBuffer = indexBuffer;
  6363. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6364. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6365. }
  6366. };
  6367. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6368. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6369. this._cachedVertexBuffers = vertexBuffers;
  6370. this._cachedEffectForVertexBuffers = effect;
  6371. var attributes = effect.getAttributesNames();
  6372. for (var index = 0; index < attributes.length; index++) {
  6373. var order = effect.getAttributeLocation(index);
  6374. if (order >= 0) {
  6375. var vertexBuffer = vertexBuffers[attributes[index]];
  6376. if (!vertexBuffer) {
  6377. continue;
  6378. }
  6379. var stride = vertexBuffer.getStrideSize();
  6380. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6381. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6382. }
  6383. }
  6384. }
  6385. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6386. this._cachedIndexBuffer = indexBuffer;
  6387. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6388. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6389. }
  6390. };
  6391. Engine.prototype._releaseBuffer = function (buffer) {
  6392. buffer.references--;
  6393. if (buffer.references === 0) {
  6394. this._gl.deleteBuffer(buffer);
  6395. return true;
  6396. }
  6397. return false;
  6398. };
  6399. Engine.prototype.createInstancesBuffer = function (capacity) {
  6400. var buffer = this._gl.createBuffer();
  6401. buffer.capacity = capacity;
  6402. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6403. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6404. return buffer;
  6405. };
  6406. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6407. this._gl.deleteBuffer(buffer);
  6408. };
  6409. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6410. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6411. if (data) {
  6412. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6413. }
  6414. if (offsetLocations[0].index !== undefined) {
  6415. var stride = 0;
  6416. for (var i = 0; i < offsetLocations.length; i++) {
  6417. var ai = offsetLocations[i];
  6418. stride += ai.attributeSize * 4;
  6419. }
  6420. for (var i = 0; i < offsetLocations.length; i++) {
  6421. var ai = offsetLocations[i];
  6422. this._gl.enableVertexAttribArray(ai.index);
  6423. this._gl.vertexAttribPointer(ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6424. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6425. }
  6426. }
  6427. else {
  6428. for (var index = 0; index < 4; index++) {
  6429. var offsetLocation = offsetLocations[index];
  6430. this._gl.enableVertexAttribArray(offsetLocation);
  6431. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6432. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6433. }
  6434. }
  6435. };
  6436. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6437. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6438. if (offsetLocations[0].index !== undefined) {
  6439. for (var i = 0; i < offsetLocations.length; i++) {
  6440. var ai = offsetLocations[i];
  6441. this._gl.disableVertexAttribArray(ai.index);
  6442. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 0);
  6443. }
  6444. }
  6445. else {
  6446. for (var index = 0; index < 4; index++) {
  6447. var offsetLocation = offsetLocations[index];
  6448. this._gl.disableVertexAttribArray(offsetLocation);
  6449. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6450. }
  6451. }
  6452. };
  6453. Engine.prototype.applyStates = function () {
  6454. this._depthCullingState.apply(this._gl);
  6455. this._alphaState.apply(this._gl);
  6456. };
  6457. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6458. // Apply states
  6459. this.applyStates();
  6460. this._drawCalls++;
  6461. // Render
  6462. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6463. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6464. if (instancesCount) {
  6465. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6466. return;
  6467. }
  6468. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6469. };
  6470. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6471. // Apply states
  6472. this.applyStates();
  6473. this._drawCalls++;
  6474. if (instancesCount) {
  6475. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6476. return;
  6477. }
  6478. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6479. };
  6480. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6481. // Apply states
  6482. this.applyStates();
  6483. this._drawCalls++;
  6484. if (instancesCount) {
  6485. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6486. return;
  6487. }
  6488. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6489. };
  6490. // Shaders
  6491. Engine.prototype._releaseEffect = function (effect) {
  6492. if (this._compiledEffects[effect._key]) {
  6493. delete this._compiledEffects[effect._key];
  6494. if (effect.getProgram()) {
  6495. this._gl.deleteProgram(effect.getProgram());
  6496. }
  6497. }
  6498. };
  6499. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6500. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6501. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6502. var name = vertex + "+" + fragment + "@" + defines;
  6503. if (this._compiledEffects[name]) {
  6504. return this._compiledEffects[name];
  6505. }
  6506. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6507. effect._key = name;
  6508. this._compiledEffects[name] = effect;
  6509. return effect;
  6510. };
  6511. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6512. if (uniformsNames === void 0) { uniformsNames = []; }
  6513. if (samplers === void 0) { samplers = []; }
  6514. if (defines === void 0) { defines = ""; }
  6515. return this.createEffect({
  6516. vertex: "particles",
  6517. fragmentElement: fragmentName
  6518. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6519. };
  6520. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6521. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6522. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6523. var shaderProgram = this._gl.createProgram();
  6524. this._gl.attachShader(shaderProgram, vertexShader);
  6525. this._gl.attachShader(shaderProgram, fragmentShader);
  6526. this._gl.linkProgram(shaderProgram);
  6527. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6528. if (!linked) {
  6529. var error = this._gl.getProgramInfoLog(shaderProgram);
  6530. if (error) {
  6531. throw new Error(error);
  6532. }
  6533. }
  6534. this._gl.deleteShader(vertexShader);
  6535. this._gl.deleteShader(fragmentShader);
  6536. return shaderProgram;
  6537. };
  6538. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6539. var results = [];
  6540. for (var index = 0; index < uniformsNames.length; index++) {
  6541. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6542. }
  6543. return results;
  6544. };
  6545. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6546. var results = [];
  6547. for (var index = 0; index < attributesNames.length; index++) {
  6548. try {
  6549. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6550. }
  6551. catch (e) {
  6552. results.push(-1);
  6553. }
  6554. }
  6555. return results;
  6556. };
  6557. Engine.prototype.enableEffect = function (effect) {
  6558. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6559. if (effect && effect.onBind) {
  6560. effect.onBind(effect);
  6561. }
  6562. return;
  6563. }
  6564. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6565. // Use program
  6566. this._gl.useProgram(effect.getProgram());
  6567. for (var i in this._vertexAttribArrays) {
  6568. //make sure this is a number)
  6569. var iAsNumber = +i;
  6570. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6571. continue;
  6572. }
  6573. this._vertexAttribArrays[iAsNumber] = false;
  6574. this._gl.disableVertexAttribArray(iAsNumber);
  6575. }
  6576. var attributesCount = effect.getAttributesCount();
  6577. for (var index = 0; index < attributesCount; index++) {
  6578. // Attributes
  6579. var order = effect.getAttributeLocation(index);
  6580. if (order >= 0) {
  6581. this._vertexAttribArrays[order] = true;
  6582. this._gl.enableVertexAttribArray(order);
  6583. }
  6584. }
  6585. this._currentEffect = effect;
  6586. if (effect.onBind) {
  6587. effect.onBind(effect);
  6588. }
  6589. };
  6590. Engine.prototype.setArray = function (uniform, array) {
  6591. if (!uniform)
  6592. return;
  6593. this._gl.uniform1fv(uniform, array);
  6594. };
  6595. Engine.prototype.setArray2 = function (uniform, array) {
  6596. if (!uniform || array.length % 2 !== 0)
  6597. return;
  6598. this._gl.uniform2fv(uniform, array);
  6599. };
  6600. Engine.prototype.setArray3 = function (uniform, array) {
  6601. if (!uniform || array.length % 3 !== 0)
  6602. return;
  6603. this._gl.uniform3fv(uniform, array);
  6604. };
  6605. Engine.prototype.setArray4 = function (uniform, array) {
  6606. if (!uniform || array.length % 4 !== 0)
  6607. return;
  6608. this._gl.uniform4fv(uniform, array);
  6609. };
  6610. Engine.prototype.setMatrices = function (uniform, matrices) {
  6611. if (!uniform)
  6612. return;
  6613. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6614. };
  6615. Engine.prototype.setMatrix = function (uniform, matrix) {
  6616. if (!uniform)
  6617. return;
  6618. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6619. };
  6620. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6621. if (!uniform)
  6622. return;
  6623. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6624. };
  6625. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6626. if (!uniform)
  6627. return;
  6628. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6629. };
  6630. Engine.prototype.setFloat = function (uniform, value) {
  6631. if (!uniform)
  6632. return;
  6633. this._gl.uniform1f(uniform, value);
  6634. };
  6635. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6636. if (!uniform)
  6637. return;
  6638. this._gl.uniform2f(uniform, x, y);
  6639. };
  6640. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6641. if (!uniform)
  6642. return;
  6643. this._gl.uniform3f(uniform, x, y, z);
  6644. };
  6645. Engine.prototype.setBool = function (uniform, bool) {
  6646. if (!uniform)
  6647. return;
  6648. this._gl.uniform1i(uniform, bool);
  6649. };
  6650. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6651. if (!uniform)
  6652. return;
  6653. this._gl.uniform4f(uniform, x, y, z, w);
  6654. };
  6655. Engine.prototype.setColor3 = function (uniform, color3) {
  6656. if (!uniform)
  6657. return;
  6658. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6659. };
  6660. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6661. if (!uniform)
  6662. return;
  6663. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6664. };
  6665. // States
  6666. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6667. if (zOffset === void 0) { zOffset = 0; }
  6668. if (reverseSide === void 0) { reverseSide = false; }
  6669. // Culling
  6670. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6671. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6672. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6673. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6674. if (culling) {
  6675. this._depthCullingState.cullFace = cullFace;
  6676. this._depthCullingState.cull = true;
  6677. }
  6678. else {
  6679. this._depthCullingState.cull = false;
  6680. }
  6681. }
  6682. // Z offset
  6683. this._depthCullingState.zOffset = zOffset;
  6684. };
  6685. Engine.prototype.setDepthBuffer = function (enable) {
  6686. this._depthCullingState.depthTest = enable;
  6687. };
  6688. Engine.prototype.getDepthWrite = function () {
  6689. return this._depthCullingState.depthMask;
  6690. };
  6691. Engine.prototype.setDepthWrite = function (enable) {
  6692. this._depthCullingState.depthMask = enable;
  6693. };
  6694. Engine.prototype.setColorWrite = function (enable) {
  6695. this._gl.colorMask(enable, enable, enable, enable);
  6696. };
  6697. Engine.prototype.setAlphaMode = function (mode) {
  6698. if (this._alphaMode === mode) {
  6699. return;
  6700. }
  6701. switch (mode) {
  6702. case Engine.ALPHA_DISABLE:
  6703. this.setDepthWrite(true);
  6704. this._alphaState.alphaBlend = false;
  6705. break;
  6706. case Engine.ALPHA_COMBINE:
  6707. this.setDepthWrite(false);
  6708. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6709. this._alphaState.alphaBlend = true;
  6710. break;
  6711. case Engine.ALPHA_ONEONE:
  6712. this.setDepthWrite(false);
  6713. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6714. this._alphaState.alphaBlend = true;
  6715. break;
  6716. case Engine.ALPHA_ADD:
  6717. this.setDepthWrite(false);
  6718. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6719. this._alphaState.alphaBlend = true;
  6720. break;
  6721. case Engine.ALPHA_SUBTRACT:
  6722. this.setDepthWrite(false);
  6723. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6724. this._alphaState.alphaBlend = true;
  6725. break;
  6726. case Engine.ALPHA_MULTIPLY:
  6727. this.setDepthWrite(false);
  6728. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6729. this._alphaState.alphaBlend = true;
  6730. break;
  6731. case Engine.ALPHA_MAXIMIZED:
  6732. this.setDepthWrite(false);
  6733. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6734. this._alphaState.alphaBlend = true;
  6735. break;
  6736. }
  6737. this._alphaMode = mode;
  6738. };
  6739. Engine.prototype.getAlphaMode = function () {
  6740. return this._alphaMode;
  6741. };
  6742. Engine.prototype.setAlphaTesting = function (enable) {
  6743. this._alphaTest = enable;
  6744. };
  6745. Engine.prototype.getAlphaTesting = function () {
  6746. return this._alphaTest;
  6747. };
  6748. // Textures
  6749. Engine.prototype.wipeCaches = function () {
  6750. this.resetTextureCache();
  6751. this._currentEffect = null;
  6752. this._depthCullingState.reset();
  6753. this._alphaState.reset();
  6754. this._cachedVertexBuffers = null;
  6755. this._cachedIndexBuffer = null;
  6756. this._cachedEffectForVertexBuffers = null;
  6757. };
  6758. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6759. var gl = this._gl;
  6760. gl.bindTexture(gl.TEXTURE_2D, texture);
  6761. var magFilter = gl.NEAREST;
  6762. var minFilter = gl.NEAREST;
  6763. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6764. magFilter = gl.LINEAR;
  6765. minFilter = gl.LINEAR;
  6766. }
  6767. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6768. magFilter = gl.LINEAR;
  6769. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6770. }
  6771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6773. gl.bindTexture(gl.TEXTURE_2D, null);
  6774. texture.samplingMode = samplingMode;
  6775. };
  6776. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6777. var _this = this;
  6778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6779. if (onLoad === void 0) { onLoad = null; }
  6780. if (onError === void 0) { onError = null; }
  6781. if (buffer === void 0) { buffer = null; }
  6782. var texture = this._gl.createTexture();
  6783. var extension;
  6784. var fromData = false;
  6785. if (url.substr(0, 5) === "data:") {
  6786. fromData = true;
  6787. }
  6788. if (!fromData)
  6789. extension = url.substr(url.length - 4, 4).toLowerCase();
  6790. else {
  6791. var oldUrl = url;
  6792. fromData = oldUrl.split(':');
  6793. url = oldUrl;
  6794. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6795. }
  6796. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6797. var isTGA = (extension === ".tga");
  6798. scene._addPendingData(texture);
  6799. texture.url = url;
  6800. texture.noMipmap = noMipmap;
  6801. texture.references = 1;
  6802. texture.samplingMode = samplingMode;
  6803. this._loadedTexturesCache.push(texture);
  6804. var onerror = function () {
  6805. scene._removePendingData(texture);
  6806. if (onError) {
  6807. onError();
  6808. }
  6809. };
  6810. var callback;
  6811. if (isTGA) {
  6812. callback = function (arrayBuffer) {
  6813. var data = new Uint8Array(arrayBuffer);
  6814. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6815. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6816. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6817. }, onLoad, samplingMode);
  6818. };
  6819. if (!(fromData instanceof Array))
  6820. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6821. callback(arrayBuffer);
  6822. }, onerror, scene.database, true);
  6823. else
  6824. callback(buffer);
  6825. }
  6826. else if (isDDS) {
  6827. callback = function (data) {
  6828. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6829. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6830. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6831. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6832. }, onLoad, samplingMode);
  6833. };
  6834. if (!(fromData instanceof Array))
  6835. BABYLON.Tools.LoadFile(url, function (data) {
  6836. callback(data);
  6837. }, onerror, scene.database, true);
  6838. else
  6839. callback(buffer);
  6840. }
  6841. else {
  6842. var onload = function (img) {
  6843. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6844. var isPot = (img.width === potWidth && img.height === potHeight);
  6845. if (!isPot) {
  6846. _this._prepareWorkingCanvas();
  6847. _this._workingCanvas.width = potWidth;
  6848. _this._workingCanvas.height = potHeight;
  6849. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6850. _this._workingContext.imageSmoothingEnabled = false;
  6851. _this._workingContext.mozImageSmoothingEnabled = false;
  6852. _this._workingContext.oImageSmoothingEnabled = false;
  6853. _this._workingContext.webkitImageSmoothingEnabled = false;
  6854. _this._workingContext.msImageSmoothingEnabled = false;
  6855. }
  6856. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6857. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6858. _this._workingContext.imageSmoothingEnabled = true;
  6859. _this._workingContext.mozImageSmoothingEnabled = true;
  6860. _this._workingContext.oImageSmoothingEnabled = true;
  6861. _this._workingContext.webkitImageSmoothingEnabled = true;
  6862. _this._workingContext.msImageSmoothingEnabled = true;
  6863. }
  6864. }
  6865. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6866. }, onLoad, samplingMode);
  6867. };
  6868. if (!(fromData instanceof Array))
  6869. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6870. else
  6871. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6872. }
  6873. return texture;
  6874. };
  6875. Engine.prototype._getInternalFormat = function (format) {
  6876. var internalFormat = this._gl.RGBA;
  6877. switch (format) {
  6878. case Engine.TEXTUREFORMAT_ALPHA:
  6879. internalFormat = this._gl.ALPHA;
  6880. break;
  6881. case Engine.TEXTUREFORMAT_LUMINANCE:
  6882. internalFormat = this._gl.LUMINANCE;
  6883. break;
  6884. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6885. internalFormat = this._gl.LUMINANCE_ALPHA;
  6886. break;
  6887. case Engine.TEXTUREFORMAT_RGB:
  6888. internalFormat = this._gl.RGB;
  6889. break;
  6890. case Engine.TEXTUREFORMAT_RGBA:
  6891. internalFormat = this._gl.RGBA;
  6892. break;
  6893. }
  6894. return internalFormat;
  6895. };
  6896. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6897. if (compression === void 0) { compression = null; }
  6898. var internalFormat = this._getInternalFormat(format);
  6899. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6900. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6901. if (texture._width % 4 !== 0) {
  6902. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  6903. }
  6904. if (compression) {
  6905. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6906. }
  6907. else {
  6908. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6909. }
  6910. if (texture.generateMipMaps) {
  6911. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6912. }
  6913. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6914. this.resetTextureCache();
  6915. texture.isReady = true;
  6916. };
  6917. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6918. if (compression === void 0) { compression = null; }
  6919. var texture = this._gl.createTexture();
  6920. texture._baseWidth = width;
  6921. texture._baseHeight = height;
  6922. texture._width = width;
  6923. texture._height = height;
  6924. texture.references = 1;
  6925. this.updateRawTexture(texture, data, format, invertY, compression);
  6926. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6927. // Filters
  6928. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6930. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6931. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6932. texture.samplingMode = samplingMode;
  6933. this._loadedTexturesCache.push(texture);
  6934. return texture;
  6935. };
  6936. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6937. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6938. var texture = this._gl.createTexture();
  6939. texture._baseWidth = width;
  6940. texture._baseHeight = height;
  6941. if (forceExponantOfTwo) {
  6942. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6943. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6944. }
  6945. this.resetTextureCache();
  6946. texture._width = width;
  6947. texture._height = height;
  6948. texture.isReady = false;
  6949. texture.generateMipMaps = generateMipMaps;
  6950. texture.references = 1;
  6951. texture.samplingMode = samplingMode;
  6952. this.updateTextureSamplingMode(samplingMode, texture);
  6953. this._loadedTexturesCache.push(texture);
  6954. return texture;
  6955. };
  6956. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6957. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6958. if (texture.isCube) {
  6959. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6960. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6961. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6962. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6963. }
  6964. else {
  6965. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6966. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6967. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6968. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6969. }
  6970. };
  6971. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  6972. if (premulAlpha === void 0) { premulAlpha = false; }
  6973. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6974. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6975. if (premulAlpha) {
  6976. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  6977. }
  6978. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6979. if (texture.generateMipMaps) {
  6980. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6981. }
  6982. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6983. this.resetTextureCache();
  6984. texture.isReady = true;
  6985. };
  6986. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6987. if (texture._isDisabled) {
  6988. return;
  6989. }
  6990. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6991. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6992. try {
  6993. // Testing video texture support
  6994. if (this._videoTextureSupported === undefined) {
  6995. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6996. if (this._gl.getError() !== 0) {
  6997. this._videoTextureSupported = false;
  6998. }
  6999. else {
  7000. this._videoTextureSupported = true;
  7001. }
  7002. }
  7003. // Copy video through the current working canvas if video texture is not supported
  7004. if (!this._videoTextureSupported) {
  7005. if (!texture._workingCanvas) {
  7006. texture._workingCanvas = document.createElement("canvas");
  7007. texture._workingContext = texture._workingCanvas.getContext("2d");
  7008. texture._workingCanvas.width = texture._width;
  7009. texture._workingCanvas.height = texture._height;
  7010. }
  7011. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7012. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7013. }
  7014. else {
  7015. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7016. }
  7017. if (texture.generateMipMaps) {
  7018. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7019. }
  7020. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7021. this.resetTextureCache();
  7022. texture.isReady = true;
  7023. }
  7024. catch (ex) {
  7025. // Something unexpected
  7026. // Let's disable the texture
  7027. texture._isDisabled = true;
  7028. }
  7029. };
  7030. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7031. // old version had a "generateMipMaps" arg instead of options.
  7032. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7033. // in the same way, generateDepthBuffer is defaulted to true
  7034. var generateMipMaps = false;
  7035. var generateDepthBuffer = true;
  7036. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7037. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7038. if (options !== undefined) {
  7039. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7040. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7041. type = options.type === undefined ? type : options.type;
  7042. if (options.samplingMode !== undefined) {
  7043. samplingMode = options.samplingMode;
  7044. }
  7045. if (type === Engine.TEXTURETYPE_FLOAT) {
  7046. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7047. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7048. }
  7049. }
  7050. var gl = this._gl;
  7051. var texture = gl.createTexture();
  7052. gl.bindTexture(gl.TEXTURE_2D, texture);
  7053. var width = size.width || size;
  7054. var height = size.height || size;
  7055. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7056. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7057. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7058. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7059. }
  7060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7064. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7065. var depthBuffer;
  7066. // Create the depth buffer
  7067. if (generateDepthBuffer) {
  7068. depthBuffer = gl.createRenderbuffer();
  7069. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7070. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7071. }
  7072. // Create the framebuffer
  7073. var framebuffer = gl.createFramebuffer();
  7074. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7075. if (generateDepthBuffer) {
  7076. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7077. }
  7078. if (generateMipMaps) {
  7079. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7080. }
  7081. // Unbind
  7082. gl.bindTexture(gl.TEXTURE_2D, null);
  7083. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7084. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7085. texture._framebuffer = framebuffer;
  7086. if (generateDepthBuffer) {
  7087. texture._depthBuffer = depthBuffer;
  7088. }
  7089. texture._width = width;
  7090. texture._height = height;
  7091. texture.isReady = true;
  7092. texture.generateMipMaps = generateMipMaps;
  7093. texture.references = 1;
  7094. texture.samplingMode = samplingMode;
  7095. this.resetTextureCache();
  7096. this._loadedTexturesCache.push(texture);
  7097. return texture;
  7098. };
  7099. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7100. var gl = this._gl;
  7101. var texture = gl.createTexture();
  7102. var generateMipMaps = true;
  7103. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7104. if (options !== undefined) {
  7105. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7106. if (options.samplingMode !== undefined) {
  7107. samplingMode = options.samplingMode;
  7108. }
  7109. }
  7110. texture.isCube = true;
  7111. texture.references = 1;
  7112. texture.generateMipMaps = generateMipMaps;
  7113. texture.references = 1;
  7114. texture.samplingMode = samplingMode;
  7115. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7116. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7117. for (var face = 0; face < 6; face++) {
  7118. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7119. }
  7120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7124. // Create the depth buffer
  7125. var depthBuffer = gl.createRenderbuffer();
  7126. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7127. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7128. // Create the framebuffer
  7129. var framebuffer = gl.createFramebuffer();
  7130. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  7131. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7132. // Mipmaps
  7133. if (texture.generateMipMaps) {
  7134. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7135. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7136. }
  7137. // Unbind
  7138. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7139. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7140. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7141. texture._framebuffer = framebuffer;
  7142. texture._depthBuffer = depthBuffer;
  7143. this.resetTextureCache();
  7144. texture._width = size;
  7145. texture._height = size;
  7146. texture.isReady = true;
  7147. return texture;
  7148. };
  7149. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7150. var _this = this;
  7151. var gl = this._gl;
  7152. var texture = gl.createTexture();
  7153. texture.isCube = true;
  7154. texture.url = rootUrl;
  7155. texture.references = 1;
  7156. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7157. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7158. if (isDDS) {
  7159. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7160. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7161. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7162. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7163. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7164. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7165. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7166. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7167. }
  7168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7172. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7173. _this.resetTextureCache();
  7174. texture._width = info.width;
  7175. texture._height = info.height;
  7176. texture.isReady = true;
  7177. }, null, null, true);
  7178. }
  7179. else {
  7180. cascadeLoad(rootUrl, scene, function (imgs) {
  7181. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7182. var height = width;
  7183. _this._prepareWorkingCanvas();
  7184. _this._workingCanvas.width = width;
  7185. _this._workingCanvas.height = height;
  7186. var faces = [
  7187. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7188. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7189. ];
  7190. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7191. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7192. for (var index = 0; index < faces.length; index++) {
  7193. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7194. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7195. }
  7196. if (!noMipmap) {
  7197. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7198. }
  7199. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7200. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7201. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7202. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7203. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7204. _this.resetTextureCache();
  7205. texture._width = width;
  7206. texture._height = height;
  7207. texture.isReady = true;
  7208. }, files);
  7209. }
  7210. return texture;
  7211. };
  7212. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7213. texture._width = width;
  7214. texture._height = height;
  7215. texture._size = width * height;
  7216. texture._baseWidth = width;
  7217. texture._baseHeight = height;
  7218. };
  7219. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7220. var _this = this;
  7221. var gl = this._gl;
  7222. var texture = gl.createTexture();
  7223. scene._addPendingData(texture);
  7224. texture.isCube = true;
  7225. texture.references = 1;
  7226. texture.url = url;
  7227. var internalFormat = this._getInternalFormat(format);
  7228. var textureType = gl.UNSIGNED_BYTE;
  7229. if (type === Engine.TEXTURETYPE_FLOAT) {
  7230. textureType = gl.FLOAT;
  7231. }
  7232. var width = size;
  7233. var height = width;
  7234. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7235. texture._width = width;
  7236. texture._height = height;
  7237. var onerror = function () {
  7238. scene._removePendingData(texture);
  7239. };
  7240. var internalCallback = function (data) {
  7241. var rgbeDataArrays = callback(data);
  7242. var facesIndex = [
  7243. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7244. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7245. ];
  7246. width = texture._width;
  7247. height = texture._height;
  7248. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7249. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  7250. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7251. if (!noMipmap && isPot) {
  7252. if (mipmmapGenerator) {
  7253. var arrayTemp = [];
  7254. // Data are known to be in +X +Y +Z -X -Y -Z
  7255. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7256. arrayTemp.push(rgbeDataArrays[0]); // +X
  7257. arrayTemp.push(rgbeDataArrays[3]); // -X
  7258. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7259. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7260. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7261. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7262. var mipData = mipmmapGenerator(arrayTemp);
  7263. for (var level = 0; level < mipData.length; level++) {
  7264. var mipSize = width >> level;
  7265. // mipData is order in +X -X +Y -Y +Z -Z
  7266. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7267. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7268. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7269. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7270. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7271. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7272. }
  7273. }
  7274. else {
  7275. // Data are known to be in +X +Y +Z -X -Y -Z
  7276. for (var index = 0; index < facesIndex.length; index++) {
  7277. var faceData = rgbeDataArrays[index];
  7278. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7279. }
  7280. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7281. }
  7282. }
  7283. else {
  7284. noMipmap = true;
  7285. }
  7286. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7289. }
  7290. else {
  7291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7293. }
  7294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7296. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7297. texture.isReady = true;
  7298. _this.resetTextureCache();
  7299. scene._removePendingData(texture);
  7300. };
  7301. BABYLON.Tools.LoadFile(url, function (data) {
  7302. internalCallback(data);
  7303. }, onerror, scene.database, true);
  7304. return texture;
  7305. };
  7306. ;
  7307. Engine.prototype._releaseTexture = function (texture) {
  7308. var gl = this._gl;
  7309. if (texture._framebuffer) {
  7310. gl.deleteFramebuffer(texture._framebuffer);
  7311. }
  7312. if (texture._depthBuffer) {
  7313. gl.deleteRenderbuffer(texture._depthBuffer);
  7314. }
  7315. gl.deleteTexture(texture);
  7316. // Unbind channels
  7317. this.unbindAllTextures();
  7318. var index = this._loadedTexturesCache.indexOf(texture);
  7319. if (index !== -1) {
  7320. this._loadedTexturesCache.splice(index, 1);
  7321. }
  7322. };
  7323. Engine.prototype.bindSamplers = function (effect) {
  7324. this._gl.useProgram(effect.getProgram());
  7325. var samplers = effect.getSamplers();
  7326. for (var index = 0; index < samplers.length; index++) {
  7327. var uniform = effect.getUniform(samplers[index]);
  7328. this._gl.uniform1i(uniform, index);
  7329. }
  7330. this._currentEffect = null;
  7331. };
  7332. Engine.prototype._bindTexture = function (channel, texture) {
  7333. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7334. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7335. this._activeTexturesCache[channel] = null;
  7336. };
  7337. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7338. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7339. };
  7340. Engine.prototype.unbindAllTextures = function () {
  7341. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7342. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7343. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7344. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7345. this._activeTexturesCache[channel] = null;
  7346. }
  7347. };
  7348. Engine.prototype.setTexture = function (channel, texture) {
  7349. if (channel < 0) {
  7350. return;
  7351. }
  7352. // Not ready?
  7353. if (!texture || !texture.isReady()) {
  7354. if (this._activeTexturesCache[channel] != null) {
  7355. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7356. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7357. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7358. this._activeTexturesCache[channel] = null;
  7359. }
  7360. return;
  7361. }
  7362. // Video
  7363. var alreadyActivated = false;
  7364. if (texture instanceof BABYLON.VideoTexture) {
  7365. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7366. alreadyActivated = true;
  7367. texture.update();
  7368. }
  7369. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7370. texture.delayLoad();
  7371. return;
  7372. }
  7373. if (this._activeTexturesCache[channel] === texture) {
  7374. return;
  7375. }
  7376. this._activeTexturesCache[channel] = texture;
  7377. var internalTexture = texture.getInternalTexture();
  7378. if (!alreadyActivated) {
  7379. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7380. }
  7381. if (internalTexture.isCube) {
  7382. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7383. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7384. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7385. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7386. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7387. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7388. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7389. }
  7390. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7391. }
  7392. else {
  7393. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7394. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7395. internalTexture._cachedWrapU = texture.wrapU;
  7396. switch (texture.wrapU) {
  7397. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7399. break;
  7400. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7401. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7402. break;
  7403. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7404. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7405. break;
  7406. }
  7407. }
  7408. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7409. internalTexture._cachedWrapV = texture.wrapV;
  7410. switch (texture.wrapV) {
  7411. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7413. break;
  7414. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7415. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7416. break;
  7417. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7418. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7419. break;
  7420. }
  7421. }
  7422. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7423. }
  7424. };
  7425. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7426. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7427. var value = texture.anisotropicFilteringLevel;
  7428. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7429. value = 1;
  7430. }
  7431. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7432. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7433. texture._cachedAnisotropicFilteringLevel = value;
  7434. }
  7435. };
  7436. Engine.prototype.readPixels = function (x, y, width, height) {
  7437. var data = new Uint8Array(height * width * 4);
  7438. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7439. return data;
  7440. };
  7441. /**
  7442. * Add an externaly attached data from its key.
  7443. * This method call will fail and return false, if such key already exists.
  7444. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7445. * @param key the unique key that identifies the data
  7446. * @param data the data object to associate to the key for this Engine instance
  7447. * @return true if no such key were already present and the data was added successfully, false otherwise
  7448. */
  7449. Engine.prototype.addExternalData = function (key, data) {
  7450. return this._externalData.add(key, data);
  7451. };
  7452. /**
  7453. * Get an externaly attached data from its key
  7454. * @param key the unique key that identifies the data
  7455. * @return the associated data, if present (can be null), or undefined if not present
  7456. */
  7457. Engine.prototype.getExternalData = function (key) {
  7458. return this._externalData.get(key);
  7459. };
  7460. /**
  7461. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7462. * @param key the unique key that identifies the data
  7463. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7464. * @return the associated data, can be null if the factory returned null.
  7465. */
  7466. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7467. return this._externalData.getOrAddWithFactory(key, factory);
  7468. };
  7469. /**
  7470. * Remove an externaly attached data from the Engine instance
  7471. * @param key the unique key that identifies the data
  7472. * @return true if the data was successfully removed, false if it doesn't exist
  7473. */
  7474. Engine.prototype.removeExternalData = function (key) {
  7475. return this._externalData.remove(key);
  7476. };
  7477. Engine.prototype.releaseInternalTexture = function (texture) {
  7478. if (!texture) {
  7479. return;
  7480. }
  7481. texture.references--;
  7482. // Final reference ?
  7483. if (texture.references === 0) {
  7484. var texturesCache = this.getLoadedTexturesCache();
  7485. var index = texturesCache.indexOf(texture);
  7486. if (index > -1) {
  7487. texturesCache.splice(index, 1);
  7488. }
  7489. this._releaseTexture(texture);
  7490. }
  7491. };
  7492. // Dispose
  7493. Engine.prototype.dispose = function () {
  7494. this.hideLoadingUI();
  7495. this.stopRenderLoop();
  7496. // Release scenes
  7497. while (this.scenes.length) {
  7498. this.scenes[0].dispose();
  7499. }
  7500. // Release audio engine
  7501. Engine.audioEngine.dispose();
  7502. // Release effects
  7503. for (var name in this._compiledEffects) {
  7504. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7505. }
  7506. // Unbind
  7507. for (var i in this._vertexAttribArrays) {
  7508. //making sure this is a string
  7509. var iAsNumber = +i;
  7510. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7511. continue;
  7512. }
  7513. this._gl.disableVertexAttribArray(iAsNumber);
  7514. }
  7515. this._gl = null;
  7516. // Events
  7517. window.removeEventListener("blur", this._onBlur);
  7518. window.removeEventListener("focus", this._onFocus);
  7519. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7520. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7521. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7522. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7523. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7524. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7525. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7526. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7527. };
  7528. // Loading screen
  7529. Engine.prototype.displayLoadingUI = function () {
  7530. this._loadingScreen.displayLoadingUI();
  7531. };
  7532. Engine.prototype.hideLoadingUI = function () {
  7533. this._loadingScreen.hideLoadingUI();
  7534. };
  7535. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7536. get: function () {
  7537. return this._loadingScreen;
  7538. },
  7539. set: function (loadingScreen) {
  7540. this._loadingScreen = loadingScreen;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7546. set: function (text) {
  7547. this._loadingScreen.loadingUIText = text;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7553. set: function (color) {
  7554. this._loadingScreen.loadingUIBackgroundColor = color;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. // FPS
  7560. Engine.prototype.getFps = function () {
  7561. return this.fps;
  7562. };
  7563. Engine.prototype.getDeltaTime = function () {
  7564. return this.deltaTime;
  7565. };
  7566. Engine.prototype._measureFps = function () {
  7567. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7568. var length = this.previousFramesDuration.length;
  7569. if (length >= 2) {
  7570. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7571. }
  7572. if (length >= this.fpsRange) {
  7573. if (length > this.fpsRange) {
  7574. this.previousFramesDuration.splice(0, 1);
  7575. length = this.previousFramesDuration.length;
  7576. }
  7577. var sum = 0;
  7578. for (var id = 0; id < length - 1; id++) {
  7579. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7580. }
  7581. this.fps = 1000.0 / (sum / (length - 1));
  7582. }
  7583. };
  7584. // Statics
  7585. Engine.isSupported = function () {
  7586. try {
  7587. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7588. if (navigator.isCocoonJS) {
  7589. return true;
  7590. }
  7591. var tempcanvas = document.createElement("canvas");
  7592. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7593. return gl != null && !!window.WebGLRenderingContext;
  7594. }
  7595. catch (e) {
  7596. return false;
  7597. }
  7598. };
  7599. // Const statics
  7600. Engine._ALPHA_DISABLE = 0;
  7601. Engine._ALPHA_ADD = 1;
  7602. Engine._ALPHA_COMBINE = 2;
  7603. Engine._ALPHA_SUBTRACT = 3;
  7604. Engine._ALPHA_MULTIPLY = 4;
  7605. Engine._ALPHA_MAXIMIZED = 5;
  7606. Engine._ALPHA_ONEONE = 6;
  7607. Engine._DELAYLOADSTATE_NONE = 0;
  7608. Engine._DELAYLOADSTATE_LOADED = 1;
  7609. Engine._DELAYLOADSTATE_LOADING = 2;
  7610. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7611. Engine._TEXTUREFORMAT_ALPHA = 0;
  7612. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7613. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7614. Engine._TEXTUREFORMAT_RGB = 4;
  7615. Engine._TEXTUREFORMAT_RGBA = 5;
  7616. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7617. Engine._TEXTURETYPE_FLOAT = 1;
  7618. // Updatable statics so stick with vars here
  7619. Engine.CollisionsEpsilon = 0.001;
  7620. Engine.CodeRepository = "src/";
  7621. Engine.ShadersRepository = "src/Shaders/";
  7622. return Engine;
  7623. })();
  7624. BABYLON.Engine = Engine;
  7625. })(BABYLON || (BABYLON = {}));
  7626. var BABYLON;
  7627. (function (BABYLON) {
  7628. /**
  7629. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7630. */
  7631. var Node = (function () {
  7632. /**
  7633. * @constructor
  7634. * @param {string} name - the name and id to be given to this node
  7635. * @param {BABYLON.Scene} the scene this node will be added to
  7636. */
  7637. function Node(name, scene) {
  7638. this.state = "";
  7639. this.animations = new Array();
  7640. this._ranges = {};
  7641. this._childrenFlag = -1;
  7642. this._isEnabled = true;
  7643. this._isReady = true;
  7644. this._currentRenderId = -1;
  7645. this._parentRenderId = -1;
  7646. this.name = name;
  7647. this.id = name;
  7648. this._scene = scene;
  7649. this._initCache();
  7650. }
  7651. Object.defineProperty(Node.prototype, "parent", {
  7652. get: function () {
  7653. return this._parentNode;
  7654. },
  7655. set: function (parent) {
  7656. if (this._parentNode === parent) {
  7657. return;
  7658. }
  7659. if (this._parentNode) {
  7660. var index = this._parentNode._children.indexOf(this);
  7661. if (index !== -1) {
  7662. this._parentNode._children.splice(index, 1);
  7663. }
  7664. }
  7665. this._parentNode = parent;
  7666. if (this._parentNode) {
  7667. if (!this._parentNode._children) {
  7668. this._parentNode._children = new Array();
  7669. }
  7670. this._parentNode._children.push(this);
  7671. }
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Node.prototype.getScene = function () {
  7677. return this._scene;
  7678. };
  7679. Node.prototype.getEngine = function () {
  7680. return this._scene.getEngine();
  7681. };
  7682. // override it in derived class
  7683. Node.prototype.getWorldMatrix = function () {
  7684. return BABYLON.Matrix.Identity();
  7685. };
  7686. // override it in derived class if you add new variables to the cache
  7687. // and call the parent class method
  7688. Node.prototype._initCache = function () {
  7689. this._cache = {};
  7690. this._cache.parent = undefined;
  7691. };
  7692. Node.prototype.updateCache = function (force) {
  7693. if (!force && this.isSynchronized())
  7694. return;
  7695. this._cache.parent = this.parent;
  7696. this._updateCache();
  7697. };
  7698. // override it in derived class if you add new variables to the cache
  7699. // and call the parent class method if !ignoreParentClass
  7700. Node.prototype._updateCache = function (ignoreParentClass) {
  7701. };
  7702. // override it in derived class if you add new variables to the cache
  7703. Node.prototype._isSynchronized = function () {
  7704. return true;
  7705. };
  7706. Node.prototype._markSyncedWithParent = function () {
  7707. this._parentRenderId = this.parent._currentRenderId;
  7708. };
  7709. Node.prototype.isSynchronizedWithParent = function () {
  7710. if (!this.parent) {
  7711. return true;
  7712. }
  7713. if (this._parentRenderId !== this.parent._currentRenderId) {
  7714. return false;
  7715. }
  7716. return this.parent.isSynchronized();
  7717. };
  7718. Node.prototype.isSynchronized = function (updateCache) {
  7719. var check = this.hasNewParent();
  7720. check = check || !this.isSynchronizedWithParent();
  7721. check = check || !this._isSynchronized();
  7722. if (updateCache)
  7723. this.updateCache(true);
  7724. return !check;
  7725. };
  7726. Node.prototype.hasNewParent = function (update) {
  7727. if (this._cache.parent === this.parent)
  7728. return false;
  7729. if (update)
  7730. this._cache.parent = this.parent;
  7731. return true;
  7732. };
  7733. /**
  7734. * Is this node ready to be used/rendered
  7735. * @return {boolean} is it ready
  7736. */
  7737. Node.prototype.isReady = function () {
  7738. return this._isReady;
  7739. };
  7740. /**
  7741. * Is this node enabled.
  7742. * If the node has a parent and is enabled, the parent will be inspected as well.
  7743. * @return {boolean} whether this node (and its parent) is enabled.
  7744. * @see setEnabled
  7745. */
  7746. Node.prototype.isEnabled = function () {
  7747. if (!this._isEnabled) {
  7748. return false;
  7749. }
  7750. if (this.parent) {
  7751. return this.parent.isEnabled();
  7752. }
  7753. return true;
  7754. };
  7755. /**
  7756. * Set the enabled state of this node.
  7757. * @param {boolean} value - the new enabled state
  7758. * @see isEnabled
  7759. */
  7760. Node.prototype.setEnabled = function (value) {
  7761. this._isEnabled = value;
  7762. };
  7763. /**
  7764. * Is this node a descendant of the given node.
  7765. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7766. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7767. * @see parent
  7768. */
  7769. Node.prototype.isDescendantOf = function (ancestor) {
  7770. if (this.parent) {
  7771. if (this.parent === ancestor) {
  7772. return true;
  7773. }
  7774. return this.parent.isDescendantOf(ancestor);
  7775. }
  7776. return false;
  7777. };
  7778. /**
  7779. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7780. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7781. * @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.
  7782. * @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.
  7783. */
  7784. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7785. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7786. if (!this._children) {
  7787. return;
  7788. }
  7789. for (var index = 0; index < this._children.length; index++) {
  7790. var item = this._children[index];
  7791. if (!predicate || predicate(item)) {
  7792. results.push(item);
  7793. }
  7794. if (!directDescendantsOnly) {
  7795. item._getDescendants(results, false, predicate);
  7796. }
  7797. }
  7798. };
  7799. /**
  7800. * Will return all nodes that have this node as ascendant.
  7801. * @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.
  7802. * @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.
  7803. * @return {BABYLON.Node[]} all children nodes of all types.
  7804. */
  7805. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7806. var results = [];
  7807. this._getDescendants(results, directDescendantsOnly, predicate);
  7808. return results;
  7809. };
  7810. /**
  7811. * @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.
  7812. * @Deprecated, legacy support.
  7813. * use getDecendants instead.
  7814. */
  7815. Node.prototype.getChildren = function (predicate) {
  7816. return this.getDescendants(true, predicate);
  7817. };
  7818. /**
  7819. * Get all child-meshes of this node.
  7820. */
  7821. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7822. var results = [];
  7823. this._getDescendants(results, directDecendantsOnly, function (node) {
  7824. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7825. });
  7826. return results;
  7827. };
  7828. Node.prototype._setReady = function (state) {
  7829. if (state === this._isReady) {
  7830. return;
  7831. }
  7832. if (!state) {
  7833. this._isReady = false;
  7834. return;
  7835. }
  7836. this._isReady = true;
  7837. if (this.onReady) {
  7838. this.onReady(this);
  7839. }
  7840. };
  7841. Node.prototype.getAnimationByName = function (name) {
  7842. for (var i = 0; i < this.animations.length; i++) {
  7843. var animation = this.animations[i];
  7844. if (animation.name === name) {
  7845. return animation;
  7846. }
  7847. }
  7848. return null;
  7849. };
  7850. Node.prototype.createAnimationRange = function (name, from, to) {
  7851. // check name not already in use
  7852. if (!this._ranges[name]) {
  7853. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7854. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7855. if (this.animations[i]) {
  7856. this.animations[i].createRange(name, from, to);
  7857. }
  7858. }
  7859. }
  7860. };
  7861. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7862. if (deleteFrames === void 0) { deleteFrames = true; }
  7863. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7864. if (this.animations[i]) {
  7865. this.animations[i].deleteRange(name, deleteFrames);
  7866. }
  7867. }
  7868. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7869. };
  7870. Node.prototype.getAnimationRange = function (name) {
  7871. return this._ranges[name];
  7872. };
  7873. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7874. var range = this.getAnimationRange(name);
  7875. if (!range) {
  7876. return null;
  7877. }
  7878. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7879. };
  7880. Node.prototype.serializeAnimationRanges = function () {
  7881. var serializationRanges = [];
  7882. for (var name in this._ranges) {
  7883. var range = {};
  7884. range.name = name;
  7885. range.from = this._ranges[name].from;
  7886. range.to = this._ranges[name].to;
  7887. serializationRanges.push(range);
  7888. }
  7889. return serializationRanges;
  7890. };
  7891. Node.prototype.dispose = function () {
  7892. this.parent = null;
  7893. };
  7894. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7895. if (parsedNode.ranges) {
  7896. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7897. var data = parsedNode.ranges[index];
  7898. node.createAnimationRange(data.name, data.from, data.to);
  7899. }
  7900. }
  7901. };
  7902. __decorate([
  7903. BABYLON.serialize()
  7904. ], Node.prototype, "name", void 0);
  7905. __decorate([
  7906. BABYLON.serialize()
  7907. ], Node.prototype, "id", void 0);
  7908. __decorate([
  7909. BABYLON.serialize()
  7910. ], Node.prototype, "uniqueId", void 0);
  7911. __decorate([
  7912. BABYLON.serialize()
  7913. ], Node.prototype, "state", void 0);
  7914. return Node;
  7915. })();
  7916. BABYLON.Node = Node;
  7917. })(BABYLON || (BABYLON = {}));
  7918. var BABYLON;
  7919. (function (BABYLON) {
  7920. var FilesInput = (function () {
  7921. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7922. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7923. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7924. this._engine = p_engine;
  7925. this._canvas = p_canvas;
  7926. this._currentScene = p_scene;
  7927. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7928. this._progressCallback = p_progressCallback;
  7929. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7930. this._textureLoadingCallback = p_textureLoadingCallback;
  7931. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7932. }
  7933. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7934. var _this = this;
  7935. if (p_elementToMonitor) {
  7936. this._elementToMonitor = p_elementToMonitor;
  7937. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7938. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7939. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7940. }
  7941. };
  7942. FilesInput.prototype.renderFunction = function () {
  7943. if (this._additionnalRenderLoopLogicCallback) {
  7944. this._additionnalRenderLoopLogicCallback();
  7945. }
  7946. if (this._currentScene) {
  7947. if (this._textureLoadingCallback) {
  7948. var remaining = this._currentScene.getWaitingItemsCount();
  7949. if (remaining > 0) {
  7950. this._textureLoadingCallback(remaining);
  7951. }
  7952. }
  7953. this._currentScene.render();
  7954. }
  7955. };
  7956. FilesInput.prototype.drag = function (e) {
  7957. e.stopPropagation();
  7958. e.preventDefault();
  7959. };
  7960. FilesInput.prototype.drop = function (eventDrop) {
  7961. eventDrop.stopPropagation();
  7962. eventDrop.preventDefault();
  7963. this.loadFiles(eventDrop);
  7964. };
  7965. FilesInput.prototype.loadFiles = function (event) {
  7966. if (this._startingProcessingFilesCallback)
  7967. this._startingProcessingFilesCallback();
  7968. // Handling data transfer via drag'n'drop
  7969. if (event && event.dataTransfer && event.dataTransfer.files) {
  7970. this._filesToLoad = event.dataTransfer.files;
  7971. }
  7972. // Handling files from input files
  7973. if (event && event.target && event.target.files) {
  7974. this._filesToLoad = event.target.files;
  7975. }
  7976. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7977. for (var i = 0; i < this._filesToLoad.length; i++) {
  7978. switch (this._filesToLoad[i].type) {
  7979. case "image/jpeg":
  7980. case "image/png":
  7981. case "image/bmp":
  7982. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7983. break;
  7984. case "image/targa":
  7985. case "image/vnd.ms-dds":
  7986. case "audio/wav":
  7987. case "audio/x-wav":
  7988. case "audio/mp3":
  7989. case "audio/mpeg":
  7990. case "audio/mpeg3":
  7991. case "audio/x-mpeg-3":
  7992. case "audio/ogg":
  7993. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7994. break;
  7995. default:
  7996. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7997. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7998. }
  7999. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8000. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8001. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8002. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8003. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8004. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8005. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8006. this._sceneFileToLoad = this._filesToLoad[i];
  8007. }
  8008. break;
  8009. }
  8010. }
  8011. this.reload();
  8012. }
  8013. };
  8014. FilesInput.prototype.reload = function () {
  8015. var _this = this;
  8016. var that = this;
  8017. // If a ".babylon" file has been provided
  8018. if (this._sceneFileToLoad) {
  8019. if (this._currentScene) {
  8020. if (BABYLON.Tools.errorsCount > 0) {
  8021. BABYLON.Tools.ClearLogCache();
  8022. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8023. }
  8024. this._engine.stopRenderLoop();
  8025. this._currentScene.dispose();
  8026. }
  8027. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8028. that._currentScene = newScene;
  8029. // Wait for textures and shaders to be ready
  8030. that._currentScene.executeWhenReady(function () {
  8031. // Attach camera to canvas inputs
  8032. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8033. that._currentScene.createDefaultCameraOrLight();
  8034. }
  8035. that._currentScene.activeCamera.attachControl(that._canvas);
  8036. if (that._sceneLoadedCallback) {
  8037. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8038. }
  8039. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8040. });
  8041. }, function (progress) {
  8042. if (_this._progressCallback) {
  8043. _this._progressCallback(progress);
  8044. }
  8045. });
  8046. }
  8047. else {
  8048. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8049. }
  8050. };
  8051. FilesInput.FilesTextures = new Array();
  8052. FilesInput.FilesToLoad = new Array();
  8053. return FilesInput;
  8054. })();
  8055. BABYLON.FilesInput = FilesInput;
  8056. })(BABYLON || (BABYLON = {}));
  8057. var BABYLON;
  8058. (function (BABYLON) {
  8059. var IntersectionInfo = (function () {
  8060. function IntersectionInfo(bu, bv, distance) {
  8061. this.bu = bu;
  8062. this.bv = bv;
  8063. this.distance = distance;
  8064. this.faceId = 0;
  8065. this.subMeshId = 0;
  8066. }
  8067. return IntersectionInfo;
  8068. })();
  8069. BABYLON.IntersectionInfo = IntersectionInfo;
  8070. var PickingInfo = (function () {
  8071. function PickingInfo() {
  8072. this.hit = false;
  8073. this.distance = 0;
  8074. this.pickedPoint = null;
  8075. this.pickedMesh = null;
  8076. this.bu = 0;
  8077. this.bv = 0;
  8078. this.faceId = -1;
  8079. this.subMeshId = 0;
  8080. this.pickedSprite = null;
  8081. }
  8082. // Methods
  8083. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8084. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8085. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8086. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8087. return null;
  8088. }
  8089. var indices = this.pickedMesh.getIndices();
  8090. var result;
  8091. if (useVerticesNormals) {
  8092. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8093. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8094. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8095. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8096. normal0 = normal0.scale(this.bu);
  8097. normal1 = normal1.scale(this.bv);
  8098. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8099. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8100. }
  8101. else {
  8102. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8103. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8104. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8105. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8106. var p1p2 = vertex1.subtract(vertex2);
  8107. var p3p2 = vertex3.subtract(vertex2);
  8108. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8109. }
  8110. if (useWorldCoordinates) {
  8111. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8112. }
  8113. return BABYLON.Vector3.Normalize(result);
  8114. };
  8115. PickingInfo.prototype.getTextureCoordinates = function () {
  8116. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8117. return null;
  8118. }
  8119. var indices = this.pickedMesh.getIndices();
  8120. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8121. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8122. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8123. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8124. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8125. uv1 = uv1.scale(this.bu);
  8126. uv2 = uv2.scale(this.bv);
  8127. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8128. };
  8129. return PickingInfo;
  8130. })();
  8131. BABYLON.PickingInfo = PickingInfo;
  8132. })(BABYLON || (BABYLON = {}));
  8133. var BABYLON;
  8134. (function (BABYLON) {
  8135. var BoundingSphere = (function () {
  8136. function BoundingSphere(minimum, maximum) {
  8137. this.minimum = minimum;
  8138. this.maximum = maximum;
  8139. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8140. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8141. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8142. this.radius = distance * 0.5;
  8143. this.centerWorld = BABYLON.Vector3.Zero();
  8144. this._update(BABYLON.Matrix.Identity());
  8145. }
  8146. // Methods
  8147. BoundingSphere.prototype._update = function (world) {
  8148. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8149. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8150. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8151. };
  8152. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8153. for (var i = 0; i < 6; i++) {
  8154. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8155. return false;
  8156. }
  8157. return true;
  8158. };
  8159. BoundingSphere.prototype.intersectsPoint = function (point) {
  8160. var x = this.centerWorld.x - point.x;
  8161. var y = this.centerWorld.y - point.y;
  8162. var z = this.centerWorld.z - point.z;
  8163. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8164. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8165. return false;
  8166. return true;
  8167. };
  8168. // Statics
  8169. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8170. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8171. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8172. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8173. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8174. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8175. return false;
  8176. return true;
  8177. };
  8178. return BoundingSphere;
  8179. })();
  8180. BABYLON.BoundingSphere = BoundingSphere;
  8181. })(BABYLON || (BABYLON = {}));
  8182. var BABYLON;
  8183. (function (BABYLON) {
  8184. var BoundingBox = (function () {
  8185. function BoundingBox(minimum, maximum) {
  8186. this.minimum = minimum;
  8187. this.maximum = maximum;
  8188. this.vectors = new Array();
  8189. this.vectorsWorld = new Array();
  8190. // Bounding vectors
  8191. this.vectors.push(this.minimum.clone());
  8192. this.vectors.push(this.maximum.clone());
  8193. this.vectors.push(this.minimum.clone());
  8194. this.vectors[2].x = this.maximum.x;
  8195. this.vectors.push(this.minimum.clone());
  8196. this.vectors[3].y = this.maximum.y;
  8197. this.vectors.push(this.minimum.clone());
  8198. this.vectors[4].z = this.maximum.z;
  8199. this.vectors.push(this.maximum.clone());
  8200. this.vectors[5].z = this.minimum.z;
  8201. this.vectors.push(this.maximum.clone());
  8202. this.vectors[6].x = this.minimum.x;
  8203. this.vectors.push(this.maximum.clone());
  8204. this.vectors[7].y = this.minimum.y;
  8205. // OBB
  8206. this.center = this.maximum.add(this.minimum).scale(0.5);
  8207. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8208. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8209. // World
  8210. for (var index = 0; index < this.vectors.length; index++) {
  8211. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8212. }
  8213. this.minimumWorld = BABYLON.Vector3.Zero();
  8214. this.maximumWorld = BABYLON.Vector3.Zero();
  8215. this._update(BABYLON.Matrix.Identity());
  8216. }
  8217. // Methods
  8218. BoundingBox.prototype.getWorldMatrix = function () {
  8219. return this._worldMatrix;
  8220. };
  8221. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8222. this._worldMatrix.copyFrom(matrix);
  8223. return this;
  8224. };
  8225. BoundingBox.prototype._update = function (world) {
  8226. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8227. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8228. for (var index = 0; index < this.vectors.length; index++) {
  8229. var v = this.vectorsWorld[index];
  8230. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8231. if (v.x < this.minimumWorld.x)
  8232. this.minimumWorld.x = v.x;
  8233. if (v.y < this.minimumWorld.y)
  8234. this.minimumWorld.y = v.y;
  8235. if (v.z < this.minimumWorld.z)
  8236. this.minimumWorld.z = v.z;
  8237. if (v.x > this.maximumWorld.x)
  8238. this.maximumWorld.x = v.x;
  8239. if (v.y > this.maximumWorld.y)
  8240. this.maximumWorld.y = v.y;
  8241. if (v.z > this.maximumWorld.z)
  8242. this.maximumWorld.z = v.z;
  8243. }
  8244. // OBB
  8245. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8246. this.center.scaleInPlace(0.5);
  8247. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8248. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8249. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8250. this._worldMatrix = world;
  8251. };
  8252. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8253. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8254. };
  8255. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8256. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8257. };
  8258. BoundingBox.prototype.intersectsPoint = function (point) {
  8259. var delta = -BABYLON.Epsilon;
  8260. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8261. return false;
  8262. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8263. return false;
  8264. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8265. return false;
  8266. return true;
  8267. };
  8268. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8269. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8270. };
  8271. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8272. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8273. return false;
  8274. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8275. return false;
  8276. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8277. return false;
  8278. return true;
  8279. };
  8280. // Statics
  8281. BoundingBox.Intersects = function (box0, box1) {
  8282. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8283. return false;
  8284. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8285. return false;
  8286. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8287. return false;
  8288. return true;
  8289. };
  8290. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8291. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8292. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8293. return (num <= (sphereRadius * sphereRadius));
  8294. };
  8295. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8296. for (var p = 0; p < 6; p++) {
  8297. for (var i = 0; i < 8; i++) {
  8298. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8299. return false;
  8300. }
  8301. }
  8302. }
  8303. return true;
  8304. };
  8305. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8306. for (var p = 0; p < 6; p++) {
  8307. var inCount = 8;
  8308. for (var i = 0; i < 8; i++) {
  8309. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8310. --inCount;
  8311. }
  8312. else {
  8313. break;
  8314. }
  8315. }
  8316. if (inCount === 0)
  8317. return false;
  8318. }
  8319. return true;
  8320. };
  8321. return BoundingBox;
  8322. })();
  8323. BABYLON.BoundingBox = BoundingBox;
  8324. })(BABYLON || (BABYLON = {}));
  8325. var BABYLON;
  8326. (function (BABYLON) {
  8327. var computeBoxExtents = function (axis, box) {
  8328. var p = BABYLON.Vector3.Dot(box.center, axis);
  8329. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8330. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8331. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8332. var r = r0 + r1 + r2;
  8333. return {
  8334. min: p - r,
  8335. max: p + r
  8336. };
  8337. };
  8338. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8339. var axisOverlap = function (axis, box0, box1) {
  8340. var result0 = computeBoxExtents(axis, box0);
  8341. var result1 = computeBoxExtents(axis, box1);
  8342. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8343. };
  8344. var BoundingInfo = (function () {
  8345. function BoundingInfo(minimum, maximum) {
  8346. this.minimum = minimum;
  8347. this.maximum = maximum;
  8348. this._isLocked = false;
  8349. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8350. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8351. }
  8352. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8353. get: function () {
  8354. return this._isLocked;
  8355. },
  8356. set: function (value) {
  8357. this._isLocked = value;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. // Methods
  8363. BoundingInfo.prototype.update = function (world) {
  8364. if (this._isLocked) {
  8365. return;
  8366. }
  8367. this.boundingBox._update(world);
  8368. this.boundingSphere._update(world);
  8369. };
  8370. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8371. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8372. return false;
  8373. return this.boundingBox.isInFrustum(frustumPlanes);
  8374. };
  8375. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8376. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8377. };
  8378. BoundingInfo.prototype._checkCollision = function (collider) {
  8379. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8380. };
  8381. BoundingInfo.prototype.intersectsPoint = function (point) {
  8382. if (!this.boundingSphere.centerWorld) {
  8383. return false;
  8384. }
  8385. if (!this.boundingSphere.intersectsPoint(point)) {
  8386. return false;
  8387. }
  8388. if (!this.boundingBox.intersectsPoint(point)) {
  8389. return false;
  8390. }
  8391. return true;
  8392. };
  8393. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8394. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8395. return false;
  8396. }
  8397. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8398. return false;
  8399. }
  8400. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8401. return false;
  8402. }
  8403. if (!precise) {
  8404. return true;
  8405. }
  8406. var box0 = this.boundingBox;
  8407. var box1 = boundingInfo.boundingBox;
  8408. if (!axisOverlap(box0.directions[0], box0, box1))
  8409. return false;
  8410. if (!axisOverlap(box0.directions[1], box0, box1))
  8411. return false;
  8412. if (!axisOverlap(box0.directions[2], box0, box1))
  8413. return false;
  8414. if (!axisOverlap(box1.directions[0], box0, box1))
  8415. return false;
  8416. if (!axisOverlap(box1.directions[1], box0, box1))
  8417. return false;
  8418. if (!axisOverlap(box1.directions[2], box0, box1))
  8419. return false;
  8420. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8421. return false;
  8422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8423. return false;
  8424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8425. return false;
  8426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8427. return false;
  8428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8429. return false;
  8430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8431. return false;
  8432. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8433. return false;
  8434. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8435. return false;
  8436. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8437. return false;
  8438. return true;
  8439. };
  8440. return BoundingInfo;
  8441. })();
  8442. BABYLON.BoundingInfo = BoundingInfo;
  8443. })(BABYLON || (BABYLON = {}));
  8444. var BABYLON;
  8445. (function (BABYLON) {
  8446. var Ray = (function () {
  8447. function Ray(origin, direction, length) {
  8448. if (length === void 0) { length = Number.MAX_VALUE; }
  8449. this.origin = origin;
  8450. this.direction = direction;
  8451. this.length = length;
  8452. }
  8453. // Methods
  8454. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8455. var d = 0.0;
  8456. var maxValue = Number.MAX_VALUE;
  8457. var inv;
  8458. var min;
  8459. var max;
  8460. var temp;
  8461. if (Math.abs(this.direction.x) < 0.0000001) {
  8462. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8463. return false;
  8464. }
  8465. }
  8466. else {
  8467. inv = 1.0 / this.direction.x;
  8468. min = (minimum.x - this.origin.x) * inv;
  8469. max = (maximum.x - this.origin.x) * inv;
  8470. if (max === -Infinity) {
  8471. max = Infinity;
  8472. }
  8473. if (min > max) {
  8474. temp = min;
  8475. min = max;
  8476. max = temp;
  8477. }
  8478. d = Math.max(min, d);
  8479. maxValue = Math.min(max, maxValue);
  8480. if (d > maxValue) {
  8481. return false;
  8482. }
  8483. }
  8484. if (Math.abs(this.direction.y) < 0.0000001) {
  8485. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8486. return false;
  8487. }
  8488. }
  8489. else {
  8490. inv = 1.0 / this.direction.y;
  8491. min = (minimum.y - this.origin.y) * inv;
  8492. max = (maximum.y - this.origin.y) * inv;
  8493. if (max === -Infinity) {
  8494. max = Infinity;
  8495. }
  8496. if (min > max) {
  8497. temp = min;
  8498. min = max;
  8499. max = temp;
  8500. }
  8501. d = Math.max(min, d);
  8502. maxValue = Math.min(max, maxValue);
  8503. if (d > maxValue) {
  8504. return false;
  8505. }
  8506. }
  8507. if (Math.abs(this.direction.z) < 0.0000001) {
  8508. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8509. return false;
  8510. }
  8511. }
  8512. else {
  8513. inv = 1.0 / this.direction.z;
  8514. min = (minimum.z - this.origin.z) * inv;
  8515. max = (maximum.z - this.origin.z) * inv;
  8516. if (max === -Infinity) {
  8517. max = Infinity;
  8518. }
  8519. if (min > max) {
  8520. temp = min;
  8521. min = max;
  8522. max = temp;
  8523. }
  8524. d = Math.max(min, d);
  8525. maxValue = Math.min(max, maxValue);
  8526. if (d > maxValue) {
  8527. return false;
  8528. }
  8529. }
  8530. return true;
  8531. };
  8532. Ray.prototype.intersectsBox = function (box) {
  8533. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8534. };
  8535. Ray.prototype.intersectsSphere = function (sphere) {
  8536. var x = sphere.center.x - this.origin.x;
  8537. var y = sphere.center.y - this.origin.y;
  8538. var z = sphere.center.z - this.origin.z;
  8539. var pyth = (x * x) + (y * y) + (z * z);
  8540. var rr = sphere.radius * sphere.radius;
  8541. if (pyth <= rr) {
  8542. return true;
  8543. }
  8544. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8545. if (dot < 0.0) {
  8546. return false;
  8547. }
  8548. var temp = pyth - (dot * dot);
  8549. return temp <= rr;
  8550. };
  8551. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8552. if (!this._edge1) {
  8553. this._edge1 = BABYLON.Vector3.Zero();
  8554. this._edge2 = BABYLON.Vector3.Zero();
  8555. this._pvec = BABYLON.Vector3.Zero();
  8556. this._tvec = BABYLON.Vector3.Zero();
  8557. this._qvec = BABYLON.Vector3.Zero();
  8558. }
  8559. vertex1.subtractToRef(vertex0, this._edge1);
  8560. vertex2.subtractToRef(vertex0, this._edge2);
  8561. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8562. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8563. if (det === 0) {
  8564. return null;
  8565. }
  8566. var invdet = 1 / det;
  8567. this.origin.subtractToRef(vertex0, this._tvec);
  8568. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8569. if (bu < 0 || bu > 1.0) {
  8570. return null;
  8571. }
  8572. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8573. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8574. if (bv < 0 || bu + bv > 1.0) {
  8575. return null;
  8576. }
  8577. //check if the distance is longer than the predefined length.
  8578. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8579. if (distance > this.length) {
  8580. return null;
  8581. }
  8582. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8583. };
  8584. Ray.prototype.intersectsPlane = function (plane) {
  8585. var distance;
  8586. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8587. if (Math.abs(result1) < 9.99999997475243E-07) {
  8588. return null;
  8589. }
  8590. else {
  8591. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8592. distance = (-plane.d - result2) / result1;
  8593. if (distance < 0.0) {
  8594. if (distance < -9.99999997475243E-07) {
  8595. return null;
  8596. }
  8597. else {
  8598. return 0;
  8599. }
  8600. }
  8601. return distance;
  8602. }
  8603. };
  8604. /**
  8605. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8606. * @param sega the first point of the segment to test the intersection against
  8607. * @param segb the second point of the segment to test the intersection against
  8608. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8609. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8610. */
  8611. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8612. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8613. var u = segb.subtract(sega);
  8614. var v = rsegb.subtract(this.origin);
  8615. var w = sega.subtract(this.origin);
  8616. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8617. var b = BABYLON.Vector3.Dot(u, v);
  8618. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8619. var d = BABYLON.Vector3.Dot(u, w);
  8620. var e = BABYLON.Vector3.Dot(v, w);
  8621. var D = a * c - b * b; // always >= 0
  8622. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8623. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8624. // compute the line parameters of the two closest points
  8625. if (D < Ray.smallnum) {
  8626. sN = 0.0; // force using point P0 on segment S1
  8627. sD = 1.0; // to prevent possible division by 0.0 later
  8628. tN = e;
  8629. tD = c;
  8630. }
  8631. else {
  8632. sN = (b * e - c * d);
  8633. tN = (a * e - b * d);
  8634. if (sN < 0.0) {
  8635. sN = 0.0;
  8636. tN = e;
  8637. tD = c;
  8638. }
  8639. else if (sN > sD) {
  8640. sN = sD;
  8641. tN = e + b;
  8642. tD = c;
  8643. }
  8644. }
  8645. if (tN < 0.0) {
  8646. tN = 0.0;
  8647. // recompute sc for this edge
  8648. if (-d < 0.0) {
  8649. sN = 0.0;
  8650. }
  8651. else if (-d > a)
  8652. sN = sD;
  8653. else {
  8654. sN = -d;
  8655. sD = a;
  8656. }
  8657. }
  8658. else if (tN > tD) {
  8659. tN = tD;
  8660. // recompute sc for this edge
  8661. if ((-d + b) < 0.0) {
  8662. sN = 0;
  8663. }
  8664. else if ((-d + b) > a) {
  8665. sN = sD;
  8666. }
  8667. else {
  8668. sN = (-d + b);
  8669. sD = a;
  8670. }
  8671. }
  8672. // finally do the division to get sc and tc
  8673. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8674. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8675. // get the difference of the two closest points
  8676. var qtc = v.multiplyByFloats(tc, tc, tc);
  8677. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8678. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8679. if (isIntersected) {
  8680. return qtc.length();
  8681. }
  8682. return -1;
  8683. };
  8684. // Statics
  8685. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8686. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8687. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8688. var direction = end.subtract(start);
  8689. direction.normalize();
  8690. return new Ray(start, direction);
  8691. };
  8692. /**
  8693. * 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
  8694. * transformed to the given world matrix.
  8695. * @param origin The origin point
  8696. * @param end The end point
  8697. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8698. */
  8699. Ray.CreateNewFromTo = function (origin, end, world) {
  8700. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8701. var direction = end.subtract(origin);
  8702. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8703. direction.normalize();
  8704. return Ray.Transform(new Ray(origin, direction, length), world);
  8705. };
  8706. Ray.Transform = function (ray, matrix) {
  8707. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8708. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8709. newDirection.normalize();
  8710. return new Ray(newOrigin, newDirection, ray.length);
  8711. };
  8712. Ray.smallnum = 0.00000001;
  8713. Ray.rayl = 10e8;
  8714. return Ray;
  8715. })();
  8716. BABYLON.Ray = Ray;
  8717. })(BABYLON || (BABYLON = {}));
  8718. var BABYLON;
  8719. (function (BABYLON) {
  8720. var AbstractMesh = (function (_super) {
  8721. __extends(AbstractMesh, _super);
  8722. // Constructor
  8723. function AbstractMesh(name, scene) {
  8724. var _this = this;
  8725. _super.call(this, name, scene);
  8726. // Events
  8727. /**
  8728. * An event triggered when the mesh is disposed.
  8729. * @type {BABYLON.Observable}
  8730. */
  8731. this.onDisposeObservable = new BABYLON.Observable();
  8732. /**
  8733. * An event triggered when this mesh collides with another one
  8734. * @type {BABYLON.Observable}
  8735. */
  8736. this.onCollideObservable = new BABYLON.Observable();
  8737. /**
  8738. * An event triggered when the collision's position changes
  8739. * @type {BABYLON.Observable}
  8740. */
  8741. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8742. /**
  8743. * An event triggered after the world matrix is updated
  8744. * @type {BABYLON.Observable}
  8745. */
  8746. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8747. // Properties
  8748. this.definedFacingForward = true; // orientation for POV movement & rotation
  8749. this.position = new BABYLON.Vector3(0, 0, 0);
  8750. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8751. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8752. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8753. this.visibility = 1.0;
  8754. this.alphaIndex = Number.MAX_VALUE;
  8755. this.infiniteDistance = false;
  8756. this.isVisible = true;
  8757. this.isPickable = true;
  8758. this.showBoundingBox = false;
  8759. this.showSubMeshesBoundingBox = false;
  8760. this.isBlocker = false;
  8761. this.renderingGroupId = 0;
  8762. this.receiveShadows = false;
  8763. this.renderOutline = false;
  8764. this.outlineColor = BABYLON.Color3.Red();
  8765. this.outlineWidth = 0.02;
  8766. this.renderOverlay = false;
  8767. this.overlayColor = BABYLON.Color3.Red();
  8768. this.overlayAlpha = 0.5;
  8769. this.hasVertexAlpha = false;
  8770. this.useVertexColors = true;
  8771. this.applyFog = true;
  8772. this.computeBonesUsingShaders = true;
  8773. this.scalingDeterminant = 1;
  8774. this.numBoneInfluencers = 4;
  8775. this.useOctreeForRenderingSelection = true;
  8776. this.useOctreeForPicking = true;
  8777. this.useOctreeForCollisions = true;
  8778. this.layerMask = 0x0FFFFFFF;
  8779. this.alwaysSelectAsActiveMesh = false;
  8780. // Collisions
  8781. this._checkCollisions = false;
  8782. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8783. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8784. this._collider = new BABYLON.Collider();
  8785. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8786. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8787. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8788. // Edges
  8789. this.edgesWidth = 1;
  8790. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8791. // Cache
  8792. this._localWorld = BABYLON.Matrix.Zero();
  8793. this._worldMatrix = BABYLON.Matrix.Zero();
  8794. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8795. this._absolutePosition = BABYLON.Vector3.Zero();
  8796. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8797. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8798. this._isDirty = false;
  8799. this._pivotMatrix = BABYLON.Matrix.Identity();
  8800. this._isDisposed = false;
  8801. this._renderId = 0;
  8802. this._intersectionsInProgress = new Array();
  8803. this._isWorldMatrixFrozen = false;
  8804. this._unIndexed = false;
  8805. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8806. if (collidedMesh === void 0) { collidedMesh = null; }
  8807. //TODO move this to the collision coordinator!
  8808. if (_this.getScene().workerCollisions)
  8809. newPosition.multiplyInPlace(_this._collider.radius);
  8810. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8811. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8812. _this.position.addInPlace(_this._diffPositionForCollisions);
  8813. }
  8814. if (collidedMesh) {
  8815. _this.onCollideObservable.notifyObservers(collidedMesh);
  8816. }
  8817. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8818. };
  8819. scene.addMesh(this);
  8820. }
  8821. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8822. get: function () {
  8823. return AbstractMesh._BILLBOARDMODE_NONE;
  8824. },
  8825. enumerable: true,
  8826. configurable: true
  8827. });
  8828. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8829. get: function () {
  8830. return AbstractMesh._BILLBOARDMODE_X;
  8831. },
  8832. enumerable: true,
  8833. configurable: true
  8834. });
  8835. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8836. get: function () {
  8837. return AbstractMesh._BILLBOARDMODE_Y;
  8838. },
  8839. enumerable: true,
  8840. configurable: true
  8841. });
  8842. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8843. get: function () {
  8844. return AbstractMesh._BILLBOARDMODE_Z;
  8845. },
  8846. enumerable: true,
  8847. configurable: true
  8848. });
  8849. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8850. get: function () {
  8851. return AbstractMesh._BILLBOARDMODE_ALL;
  8852. },
  8853. enumerable: true,
  8854. configurable: true
  8855. });
  8856. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  8857. set: function (callback) {
  8858. if (this._onDisposeObserver) {
  8859. this.onDisposeObservable.remove(this._onDisposeObserver);
  8860. }
  8861. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  8862. },
  8863. enumerable: true,
  8864. configurable: true
  8865. });
  8866. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8867. set: function (callback) {
  8868. if (this._onCollideObserver) {
  8869. this.onCollideObservable.remove(this._onCollideObserver);
  8870. }
  8871. this._onCollideObserver = this.onCollideObservable.add(callback);
  8872. },
  8873. enumerable: true,
  8874. configurable: true
  8875. });
  8876. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8877. set: function (callback) {
  8878. if (this._onCollisionPositionChangeObserver) {
  8879. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8880. }
  8881. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8882. },
  8883. enumerable: true,
  8884. configurable: true
  8885. });
  8886. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8887. get: function () {
  8888. return this._skeleton;
  8889. },
  8890. set: function (value) {
  8891. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8892. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8893. }
  8894. if (value && value.needInitialSkinMatrix) {
  8895. value._registerMeshWithPoseMatrix(this);
  8896. }
  8897. this._skeleton = value;
  8898. if (!this._skeleton) {
  8899. this._bonesTransformMatrices = null;
  8900. }
  8901. },
  8902. enumerable: true,
  8903. configurable: true
  8904. });
  8905. /**
  8906. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8907. */
  8908. AbstractMesh.prototype.toString = function (fullDetails) {
  8909. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8910. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8911. if (this._skeleton) {
  8912. ret += ", skeleton: " + this._skeleton.name;
  8913. }
  8914. if (fullDetails) {
  8915. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8916. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8917. }
  8918. return ret;
  8919. };
  8920. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8921. /**
  8922. * Getting the rotation object.
  8923. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8924. */
  8925. get: function () {
  8926. return this._rotation;
  8927. },
  8928. set: function (newRotation) {
  8929. this._rotation = newRotation;
  8930. },
  8931. enumerable: true,
  8932. configurable: true
  8933. });
  8934. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8935. get: function () {
  8936. return this._scaling;
  8937. },
  8938. set: function (newScaling) {
  8939. this._scaling = newScaling;
  8940. if (this.physicsImpostor) {
  8941. this.physicsImpostor.forceUpdate();
  8942. }
  8943. },
  8944. enumerable: true,
  8945. configurable: true
  8946. });
  8947. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8948. get: function () {
  8949. return this._rotationQuaternion;
  8950. },
  8951. set: function (quaternion) {
  8952. this._rotationQuaternion = quaternion;
  8953. //reset the rotation vector.
  8954. if (quaternion && this.rotation.length()) {
  8955. this.rotation.copyFromFloats(0, 0, 0);
  8956. }
  8957. },
  8958. enumerable: true,
  8959. configurable: true
  8960. });
  8961. // Methods
  8962. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8963. this._poseMatrix.copyFrom(matrix);
  8964. };
  8965. AbstractMesh.prototype.getPoseMatrix = function () {
  8966. return this._poseMatrix;
  8967. };
  8968. AbstractMesh.prototype.disableEdgesRendering = function () {
  8969. if (this._edgesRenderer !== undefined) {
  8970. this._edgesRenderer.dispose();
  8971. this._edgesRenderer = undefined;
  8972. }
  8973. };
  8974. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8975. if (epsilon === void 0) { epsilon = 0.95; }
  8976. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8977. this.disableEdgesRendering();
  8978. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8979. };
  8980. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8981. get: function () {
  8982. return false;
  8983. },
  8984. enumerable: true,
  8985. configurable: true
  8986. });
  8987. AbstractMesh.prototype.getLOD = function (camera) {
  8988. return this;
  8989. };
  8990. AbstractMesh.prototype.getTotalVertices = function () {
  8991. return 0;
  8992. };
  8993. AbstractMesh.prototype.getIndices = function () {
  8994. return null;
  8995. };
  8996. AbstractMesh.prototype.getVerticesData = function (kind) {
  8997. return null;
  8998. };
  8999. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9000. return false;
  9001. };
  9002. AbstractMesh.prototype.getBoundingInfo = function () {
  9003. if (this._masterMesh) {
  9004. return this._masterMesh.getBoundingInfo();
  9005. }
  9006. if (!this._boundingInfo) {
  9007. this._updateBoundingInfo();
  9008. }
  9009. return this._boundingInfo;
  9010. };
  9011. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9012. get: function () {
  9013. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9014. },
  9015. enumerable: true,
  9016. configurable: true
  9017. });
  9018. AbstractMesh.prototype._preActivate = function () {
  9019. };
  9020. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9021. };
  9022. AbstractMesh.prototype._activate = function (renderId) {
  9023. this._renderId = renderId;
  9024. };
  9025. AbstractMesh.prototype.getWorldMatrix = function () {
  9026. if (this._masterMesh) {
  9027. return this._masterMesh.getWorldMatrix();
  9028. }
  9029. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9030. this.computeWorldMatrix();
  9031. }
  9032. return this._worldMatrix;
  9033. };
  9034. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9035. get: function () {
  9036. return this._worldMatrix;
  9037. },
  9038. enumerable: true,
  9039. configurable: true
  9040. });
  9041. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9042. get: function () {
  9043. return this._absolutePosition;
  9044. },
  9045. enumerable: true,
  9046. configurable: true
  9047. });
  9048. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9049. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9050. this.computeWorldMatrix(true);
  9051. this._isWorldMatrixFrozen = true;
  9052. };
  9053. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9054. this._isWorldMatrixFrozen = false;
  9055. this.computeWorldMatrix(true);
  9056. };
  9057. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9058. get: function () {
  9059. return this._isWorldMatrixFrozen;
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9065. axis.normalize();
  9066. if (!this.rotationQuaternion) {
  9067. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9068. this.rotation = BABYLON.Vector3.Zero();
  9069. }
  9070. var rotationQuaternion;
  9071. if (!space || space === BABYLON.Space.LOCAL) {
  9072. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9073. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9074. }
  9075. else {
  9076. if (this.parent) {
  9077. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9078. invertParentWorldMatrix.invert();
  9079. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9080. }
  9081. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9082. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9083. }
  9084. };
  9085. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9086. var displacementVector = axis.scale(distance);
  9087. if (!space || space === BABYLON.Space.LOCAL) {
  9088. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9089. this.setPositionWithLocalVector(tempV3);
  9090. }
  9091. else {
  9092. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9093. }
  9094. };
  9095. AbstractMesh.prototype.getAbsolutePosition = function () {
  9096. this.computeWorldMatrix();
  9097. return this._absolutePosition;
  9098. };
  9099. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9100. if (!absolutePosition) {
  9101. return;
  9102. }
  9103. var absolutePositionX;
  9104. var absolutePositionY;
  9105. var absolutePositionZ;
  9106. if (absolutePosition.x === undefined) {
  9107. if (arguments.length < 3) {
  9108. return;
  9109. }
  9110. absolutePositionX = arguments[0];
  9111. absolutePositionY = arguments[1];
  9112. absolutePositionZ = arguments[2];
  9113. }
  9114. else {
  9115. absolutePositionX = absolutePosition.x;
  9116. absolutePositionY = absolutePosition.y;
  9117. absolutePositionZ = absolutePosition.z;
  9118. }
  9119. if (this.parent) {
  9120. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9121. invertParentWorldMatrix.invert();
  9122. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9123. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9124. }
  9125. else {
  9126. this.position.x = absolutePositionX;
  9127. this.position.y = absolutePositionY;
  9128. this.position.z = absolutePositionZ;
  9129. }
  9130. };
  9131. // ================================== Point of View Movement =================================
  9132. /**
  9133. * Perform relative position change from the point of view of behind the front of the mesh.
  9134. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9135. * Supports definition of mesh facing forward or backward.
  9136. * @param {number} amountRight
  9137. * @param {number} amountUp
  9138. * @param {number} amountForward
  9139. */
  9140. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9141. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9142. };
  9143. /**
  9144. * Calculate relative position change from the point of view of behind the front of the mesh.
  9145. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9146. * Supports definition of mesh facing forward or backward.
  9147. * @param {number} amountRight
  9148. * @param {number} amountUp
  9149. * @param {number} amountForward
  9150. */
  9151. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9152. var rotMatrix = new BABYLON.Matrix();
  9153. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9154. rotQuaternion.toRotationMatrix(rotMatrix);
  9155. var translationDelta = BABYLON.Vector3.Zero();
  9156. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9157. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9158. return translationDelta;
  9159. };
  9160. // ================================== Point of View Rotation =================================
  9161. /**
  9162. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9163. * Supports definition of mesh facing forward or backward.
  9164. * @param {number} flipBack
  9165. * @param {number} twirlClockwise
  9166. * @param {number} tiltRight
  9167. */
  9168. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9169. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9170. };
  9171. /**
  9172. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9173. * Supports definition of mesh facing forward or backward.
  9174. * @param {number} flipBack
  9175. * @param {number} twirlClockwise
  9176. * @param {number} tiltRight
  9177. */
  9178. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9179. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9180. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9181. };
  9182. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9183. this._pivotMatrix = matrix;
  9184. this._cache.pivotMatrixUpdated = true;
  9185. };
  9186. AbstractMesh.prototype.getPivotMatrix = function () {
  9187. return this._pivotMatrix;
  9188. };
  9189. AbstractMesh.prototype._isSynchronized = function () {
  9190. if (this._isDirty) {
  9191. return false;
  9192. }
  9193. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9194. return false;
  9195. if (this._cache.pivotMatrixUpdated) {
  9196. return false;
  9197. }
  9198. if (this.infiniteDistance) {
  9199. return false;
  9200. }
  9201. if (!this._cache.position.equals(this.position))
  9202. return false;
  9203. if (this.rotationQuaternion) {
  9204. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9205. return false;
  9206. }
  9207. else {
  9208. if (!this._cache.rotation.equals(this.rotation))
  9209. return false;
  9210. }
  9211. if (!this._cache.scaling.equals(this.scaling))
  9212. return false;
  9213. return true;
  9214. };
  9215. AbstractMesh.prototype._initCache = function () {
  9216. _super.prototype._initCache.call(this);
  9217. this._cache.localMatrixUpdated = false;
  9218. this._cache.position = BABYLON.Vector3.Zero();
  9219. this._cache.scaling = BABYLON.Vector3.Zero();
  9220. this._cache.rotation = BABYLON.Vector3.Zero();
  9221. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9222. this._cache.billboardMode = -1;
  9223. };
  9224. AbstractMesh.prototype.markAsDirty = function (property) {
  9225. if (property === "rotation") {
  9226. this.rotationQuaternion = null;
  9227. }
  9228. this._currentRenderId = Number.MAX_VALUE;
  9229. this._isDirty = true;
  9230. };
  9231. AbstractMesh.prototype._updateBoundingInfo = function () {
  9232. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9233. this._boundingInfo.update(this.worldMatrixFromCache);
  9234. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9235. };
  9236. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9237. if (!this.subMeshes) {
  9238. return;
  9239. }
  9240. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9241. var subMesh = this.subMeshes[subIndex];
  9242. if (!subMesh.IsGlobal) {
  9243. subMesh.updateBoundingInfo(matrix);
  9244. }
  9245. }
  9246. };
  9247. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9248. if (this._isWorldMatrixFrozen) {
  9249. return this._worldMatrix;
  9250. }
  9251. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9252. this._currentRenderId = this.getScene().getRenderId();
  9253. return this._worldMatrix;
  9254. }
  9255. this._cache.position.copyFrom(this.position);
  9256. this._cache.scaling.copyFrom(this.scaling);
  9257. this._cache.pivotMatrixUpdated = false;
  9258. this._cache.billboardMode = this.billboardMode;
  9259. this._currentRenderId = this.getScene().getRenderId();
  9260. this._isDirty = false;
  9261. // Scaling
  9262. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9263. // Rotation
  9264. //rotate, if quaternion is set and rotation was used
  9265. if (this.rotationQuaternion) {
  9266. var len = this.rotation.length();
  9267. if (len) {
  9268. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9269. this.rotation.copyFromFloats(0, 0, 0);
  9270. }
  9271. }
  9272. if (this.rotationQuaternion) {
  9273. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9274. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9275. }
  9276. else {
  9277. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9278. this._cache.rotation.copyFrom(this.rotation);
  9279. }
  9280. // Translation
  9281. if (this.infiniteDistance && !this.parent) {
  9282. var camera = this.getScene().activeCamera;
  9283. if (camera) {
  9284. var cameraWorldMatrix = camera.getWorldMatrix();
  9285. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9286. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9287. }
  9288. }
  9289. else {
  9290. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9291. }
  9292. // Composing transformations
  9293. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9294. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9295. // Billboarding
  9296. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9297. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9298. var localPosition = BABYLON.Tmp.Vector3[0];
  9299. if (this.parent && this.parent.getWorldMatrix) {
  9300. this._markSyncedWithParent();
  9301. var parentMatrix;
  9302. if (this._meshToBoneReferal) {
  9303. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9304. parentMatrix = BABYLON.Tmp.Matrix[6];
  9305. }
  9306. else {
  9307. parentMatrix = this.parent.getWorldMatrix();
  9308. }
  9309. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9310. localPosition = BABYLON.Tmp.Vector3[1];
  9311. }
  9312. var zero = this.getScene().activeCamera.globalPosition.clone();
  9313. if (this.parent && this.parent.position) {
  9314. localPosition.addInPlace(this.parent.position);
  9315. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9316. }
  9317. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9318. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9319. zero.x = localPosition.x + BABYLON.Epsilon;
  9320. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9321. zero.y = localPosition.y + BABYLON.Epsilon;
  9322. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9323. zero.z = localPosition.z + BABYLON.Epsilon;
  9324. }
  9325. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9326. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9327. BABYLON.Tmp.Matrix[3].invert();
  9328. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9329. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9330. }
  9331. // Local world
  9332. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9333. // Parent
  9334. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9335. this._markSyncedWithParent();
  9336. if (this._meshToBoneReferal) {
  9337. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9338. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9339. }
  9340. else {
  9341. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9342. }
  9343. }
  9344. else {
  9345. this._worldMatrix.copyFrom(this._localWorld);
  9346. }
  9347. // Bounding info
  9348. this._updateBoundingInfo();
  9349. // Absolute position
  9350. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9351. // Callbacks
  9352. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9353. if (!this._poseMatrix) {
  9354. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9355. }
  9356. return this._worldMatrix;
  9357. };
  9358. /**
  9359. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9360. * @param func: callback function to add
  9361. */
  9362. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9363. this.onAfterWorldMatrixUpdateObservable.add(func);
  9364. };
  9365. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9366. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9367. };
  9368. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9369. this.computeWorldMatrix();
  9370. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9371. };
  9372. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9373. this.computeWorldMatrix();
  9374. var invLocalWorldMatrix = this._localWorld.clone();
  9375. invLocalWorldMatrix.invert();
  9376. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9377. };
  9378. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9379. this.computeWorldMatrix(true);
  9380. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9381. };
  9382. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9383. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9384. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9385. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9386. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9387. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9388. /// <returns>Mesh oriented towards targetMesh</returns>
  9389. yawCor = yawCor || 0; // default to zero if undefined
  9390. pitchCor = pitchCor || 0;
  9391. rollCor = rollCor || 0;
  9392. var dv = targetPoint.subtract(this.position);
  9393. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9394. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9395. var pitch = Math.atan2(dv.y, len);
  9396. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9397. };
  9398. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9399. this._meshToBoneReferal = affectedMesh;
  9400. this.parent = bone;
  9401. if (bone.getWorldMatrix().determinant() < 0) {
  9402. this.scalingDeterminant *= -1;
  9403. }
  9404. };
  9405. AbstractMesh.prototype.detachFromBone = function () {
  9406. if (this.parent.getWorldMatrix().determinant() < 0) {
  9407. this.scalingDeterminant *= -1;
  9408. }
  9409. this._meshToBoneReferal = null;
  9410. this.parent = null;
  9411. };
  9412. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9413. return this._boundingInfo.isInFrustum(frustumPlanes);
  9414. };
  9415. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9416. if (!camera) {
  9417. camera = this.getScene().activeCamera;
  9418. }
  9419. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9420. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9421. return false;
  9422. }
  9423. return true;
  9424. };
  9425. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9426. if (!this._boundingInfo || !mesh._boundingInfo) {
  9427. return false;
  9428. }
  9429. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9430. };
  9431. AbstractMesh.prototype.intersectsPoint = function (point) {
  9432. if (!this._boundingInfo) {
  9433. return false;
  9434. }
  9435. return this._boundingInfo.intersectsPoint(point);
  9436. };
  9437. // Physics
  9438. /**
  9439. * @Deprecated. Use new PhysicsImpostor instead.
  9440. * */
  9441. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9442. //legacy support
  9443. if (impostor.impostor) {
  9444. options = impostor;
  9445. impostor = impostor.impostor;
  9446. }
  9447. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9448. return this.physicsImpostor.physicsBody;
  9449. };
  9450. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9451. return this.physicsImpostor;
  9452. };
  9453. /**
  9454. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9455. */
  9456. AbstractMesh.prototype.getPhysicsMass = function () {
  9457. return this.physicsImpostor.getParam("mass");
  9458. };
  9459. /**
  9460. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9461. */
  9462. AbstractMesh.prototype.getPhysicsFriction = function () {
  9463. return this.physicsImpostor.getParam("friction");
  9464. };
  9465. /**
  9466. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9467. */
  9468. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9469. return this.physicsImpostor.getParam("resitution");
  9470. };
  9471. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9472. if (!camera) {
  9473. camera = this.getScene().activeCamera;
  9474. }
  9475. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9476. };
  9477. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9478. if (!camera) {
  9479. camera = this.getScene().activeCamera;
  9480. }
  9481. return this.absolutePosition.subtract(camera.position).length();
  9482. };
  9483. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9484. if (!this.physicsImpostor) {
  9485. return;
  9486. }
  9487. this.physicsImpostor.applyImpulse(force, contactPoint);
  9488. };
  9489. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9490. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9491. return;
  9492. }
  9493. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9494. mainPivot: pivot1,
  9495. connectedPivot: pivot2,
  9496. nativeParams: options
  9497. });
  9498. };
  9499. /**
  9500. * @Deprecated
  9501. */
  9502. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9503. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9504. this.updatePhysicsBody();
  9505. };
  9506. /**
  9507. * @Deprecated
  9508. * Calling this function is not needed anymore.
  9509. * The physics engine takes care of transofmration automatically.
  9510. */
  9511. AbstractMesh.prototype.updatePhysicsBody = function () {
  9512. //Unneeded
  9513. };
  9514. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9515. // Collisions
  9516. get: function () {
  9517. return this._checkCollisions;
  9518. },
  9519. set: function (collisionEnabled) {
  9520. this._checkCollisions = collisionEnabled;
  9521. if (this.getScene().workerCollisions) {
  9522. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9523. }
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9529. var globalPosition = this.getAbsolutePosition();
  9530. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9531. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9532. this._collider.radius = this.ellipsoid;
  9533. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9534. };
  9535. // Submeshes octree
  9536. /**
  9537. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9538. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9539. */
  9540. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9541. if (maxCapacity === void 0) { maxCapacity = 64; }
  9542. if (maxDepth === void 0) { maxDepth = 2; }
  9543. if (!this._submeshesOctree) {
  9544. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9545. }
  9546. this.computeWorldMatrix(true);
  9547. // Update octree
  9548. var bbox = this.getBoundingInfo().boundingBox;
  9549. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9550. return this._submeshesOctree;
  9551. };
  9552. // Collisions
  9553. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9554. this._generatePointsArray();
  9555. // Transformation
  9556. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9557. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9558. subMesh._lastColliderWorldVertices = [];
  9559. subMesh._trianglePlanes = [];
  9560. var start = subMesh.verticesStart;
  9561. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9562. for (var i = start; i < end; i++) {
  9563. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9564. }
  9565. }
  9566. // Collide
  9567. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9568. if (collider.collisionFound) {
  9569. collider.collidedMesh = this;
  9570. }
  9571. };
  9572. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9573. var subMeshes;
  9574. var len;
  9575. // Octrees
  9576. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9577. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9578. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9579. len = intersections.length;
  9580. subMeshes = intersections.data;
  9581. }
  9582. else {
  9583. subMeshes = this.subMeshes;
  9584. len = subMeshes.length;
  9585. }
  9586. for (var index = 0; index < len; index++) {
  9587. var subMesh = subMeshes[index];
  9588. // Bounding test
  9589. if (len > 1 && !subMesh._checkCollision(collider))
  9590. continue;
  9591. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9592. }
  9593. };
  9594. AbstractMesh.prototype._checkCollision = function (collider) {
  9595. // Bounding box test
  9596. if (!this._boundingInfo._checkCollision(collider))
  9597. return;
  9598. // Transformation matrix
  9599. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9600. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9601. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9602. };
  9603. // Picking
  9604. AbstractMesh.prototype._generatePointsArray = function () {
  9605. return false;
  9606. };
  9607. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9608. var pickingInfo = new BABYLON.PickingInfo();
  9609. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9610. return pickingInfo;
  9611. }
  9612. if (!this._generatePointsArray()) {
  9613. return pickingInfo;
  9614. }
  9615. var intersectInfo = null;
  9616. // Octrees
  9617. var subMeshes;
  9618. var len;
  9619. if (this._submeshesOctree && this.useOctreeForPicking) {
  9620. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9621. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9622. len = intersections.length;
  9623. subMeshes = intersections.data;
  9624. }
  9625. else {
  9626. subMeshes = this.subMeshes;
  9627. len = subMeshes.length;
  9628. }
  9629. for (var index = 0; index < len; index++) {
  9630. var subMesh = subMeshes[index];
  9631. // Bounding test
  9632. if (len > 1 && !subMesh.canIntersects(ray))
  9633. continue;
  9634. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9635. if (currentIntersectInfo) {
  9636. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9637. intersectInfo = currentIntersectInfo;
  9638. intersectInfo.subMeshId = index;
  9639. if (fastCheck) {
  9640. break;
  9641. }
  9642. }
  9643. }
  9644. }
  9645. if (intersectInfo) {
  9646. // Get picked point
  9647. var world = this.getWorldMatrix();
  9648. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9649. var direction = ray.direction.clone();
  9650. direction = direction.scale(intersectInfo.distance);
  9651. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9652. var pickedPoint = worldOrigin.add(worldDirection);
  9653. // Return result
  9654. pickingInfo.hit = true;
  9655. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9656. pickingInfo.pickedPoint = pickedPoint;
  9657. pickingInfo.pickedMesh = this;
  9658. pickingInfo.bu = intersectInfo.bu;
  9659. pickingInfo.bv = intersectInfo.bv;
  9660. pickingInfo.faceId = intersectInfo.faceId;
  9661. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9662. return pickingInfo;
  9663. }
  9664. return pickingInfo;
  9665. };
  9666. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9667. return null;
  9668. };
  9669. AbstractMesh.prototype.releaseSubMeshes = function () {
  9670. if (this.subMeshes) {
  9671. while (this.subMeshes.length) {
  9672. this.subMeshes[0].dispose();
  9673. }
  9674. }
  9675. else {
  9676. this.subMeshes = new Array();
  9677. }
  9678. };
  9679. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9680. var _this = this;
  9681. var index;
  9682. // Action manager
  9683. if (this.actionManager) {
  9684. this.actionManager.dispose();
  9685. this.actionManager = null;
  9686. }
  9687. // Skeleton
  9688. this.skeleton = null;
  9689. // Animations
  9690. this.getScene().stopAnimation(this);
  9691. // Physics
  9692. if (this.physicsImpostor) {
  9693. this.physicsImpostor.dispose();
  9694. }
  9695. // Intersections in progress
  9696. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9697. var other = this._intersectionsInProgress[index];
  9698. var pos = other._intersectionsInProgress.indexOf(this);
  9699. other._intersectionsInProgress.splice(pos, 1);
  9700. }
  9701. this._intersectionsInProgress = [];
  9702. // Lights
  9703. var lights = this.getScene().lights;
  9704. lights.forEach(function (light) {
  9705. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9706. if (meshIndex !== -1) {
  9707. light.includedOnlyMeshes.splice(meshIndex, 1);
  9708. }
  9709. meshIndex = light.excludedMeshes.indexOf(_this);
  9710. if (meshIndex !== -1) {
  9711. light.excludedMeshes.splice(meshIndex, 1);
  9712. }
  9713. });
  9714. // Edges
  9715. if (this._edgesRenderer) {
  9716. this._edgesRenderer.dispose();
  9717. this._edgesRenderer = null;
  9718. }
  9719. // SubMeshes
  9720. this.releaseSubMeshes();
  9721. // Remove from scene
  9722. this.getScene().removeMesh(this);
  9723. if (!doNotRecurse) {
  9724. // Particles
  9725. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9726. if (this.getScene().particleSystems[index].emitter === this) {
  9727. this.getScene().particleSystems[index].dispose();
  9728. index--;
  9729. }
  9730. }
  9731. // Children
  9732. var objects = this.getDescendants(true);
  9733. for (index = 0; index < objects.length; index++) {
  9734. objects[index].dispose();
  9735. }
  9736. }
  9737. else {
  9738. var childMeshes = this.getChildMeshes(true);
  9739. for (index = 0; index < childMeshes.length; index++) {
  9740. var child = childMeshes[index];
  9741. child.parent = null;
  9742. child.computeWorldMatrix(true);
  9743. }
  9744. }
  9745. _super.prototype.dispose.call(this);
  9746. this.onAfterWorldMatrixUpdateObservable.clear();
  9747. this.onCollideObservable.clear();
  9748. this.onCollisionPositionChangeObservable.clear();
  9749. this._isDisposed = true;
  9750. // Callback
  9751. this.onDisposeObservable.notifyObservers(this);
  9752. this.onDisposeObservable.clear();
  9753. };
  9754. // Statics
  9755. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9756. AbstractMesh._BILLBOARDMODE_X = 1;
  9757. AbstractMesh._BILLBOARDMODE_Y = 2;
  9758. AbstractMesh._BILLBOARDMODE_Z = 4;
  9759. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9760. return AbstractMesh;
  9761. })(BABYLON.Node);
  9762. BABYLON.AbstractMesh = AbstractMesh;
  9763. })(BABYLON || (BABYLON = {}));
  9764. var BABYLON;
  9765. (function (BABYLON) {
  9766. var Light = (function (_super) {
  9767. __extends(Light, _super);
  9768. function Light(name, scene) {
  9769. _super.call(this, name, scene);
  9770. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9771. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9772. this.intensity = 1.0;
  9773. this.range = Number.MAX_VALUE;
  9774. this.includeOnlyWithLayerMask = 0;
  9775. this.includedOnlyMeshes = new Array();
  9776. this.excludedMeshes = new Array();
  9777. this.excludeWithLayerMask = 0;
  9778. // PBR Properties.
  9779. this.radius = 0.00001;
  9780. this._excludedMeshesIds = new Array();
  9781. this._includedOnlyMeshesIds = new Array();
  9782. scene.addLight(this);
  9783. }
  9784. /**
  9785. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9786. */
  9787. Light.prototype.toString = function (fullDetails) {
  9788. var ret = "Name: " + this.name;
  9789. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9790. if (this.animations) {
  9791. for (var i = 0; i < this.animations.length; i++) {
  9792. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9793. }
  9794. }
  9795. if (fullDetails) {
  9796. }
  9797. return ret;
  9798. };
  9799. Light.prototype.getShadowGenerator = function () {
  9800. return this._shadowGenerator;
  9801. };
  9802. Light.prototype.getAbsolutePosition = function () {
  9803. return BABYLON.Vector3.Zero();
  9804. };
  9805. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9806. };
  9807. Light.prototype._getWorldMatrix = function () {
  9808. return BABYLON.Matrix.Identity();
  9809. };
  9810. Light.prototype.canAffectMesh = function (mesh) {
  9811. if (!mesh) {
  9812. return true;
  9813. }
  9814. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9815. return false;
  9816. }
  9817. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9818. return false;
  9819. }
  9820. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9821. return false;
  9822. }
  9823. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9824. return false;
  9825. }
  9826. return true;
  9827. };
  9828. Light.prototype.getWorldMatrix = function () {
  9829. this._currentRenderId = this.getScene().getRenderId();
  9830. var worldMatrix = this._getWorldMatrix();
  9831. if (this.parent && this.parent.getWorldMatrix) {
  9832. if (!this._parentedWorldMatrix) {
  9833. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9834. }
  9835. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9836. this._markSyncedWithParent();
  9837. return this._parentedWorldMatrix;
  9838. }
  9839. return worldMatrix;
  9840. };
  9841. Light.prototype.dispose = function () {
  9842. if (this._shadowGenerator) {
  9843. this._shadowGenerator.dispose();
  9844. this._shadowGenerator = null;
  9845. }
  9846. // Animations
  9847. this.getScene().stopAnimation(this);
  9848. // Remove from scene
  9849. this.getScene().removeLight(this);
  9850. _super.prototype.dispose.call(this);
  9851. };
  9852. Light.prototype.getTypeID = function () {
  9853. return 0;
  9854. };
  9855. Light.prototype.clone = function (name) {
  9856. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9857. };
  9858. Light.prototype.serialize = function () {
  9859. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9860. // Type
  9861. serializationObject.type = this.getTypeID();
  9862. // Parent
  9863. if (this.parent) {
  9864. serializationObject.parentId = this.parent.id;
  9865. }
  9866. // Inclusion / exclusions
  9867. if (this.excludedMeshes.length > 0) {
  9868. serializationObject.excludedMeshesIds = [];
  9869. this.excludedMeshes.forEach(function (mesh) {
  9870. serializationObject.excludedMeshesIds.push(mesh.id);
  9871. });
  9872. }
  9873. if (this.includedOnlyMeshes.length > 0) {
  9874. serializationObject.includedOnlyMeshesIds = [];
  9875. this.includedOnlyMeshes.forEach(function (mesh) {
  9876. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9877. });
  9878. }
  9879. // Animations
  9880. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9881. serializationObject.ranges = this.serializeAnimationRanges();
  9882. return serializationObject;
  9883. };
  9884. Light.GetConstructorFromName = function (type, name, scene) {
  9885. switch (type) {
  9886. case 0:
  9887. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9888. case 1:
  9889. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9890. case 2:
  9891. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9892. case 3:
  9893. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9894. }
  9895. };
  9896. Light.Parse = function (parsedLight, scene) {
  9897. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9898. // Inclusion / exclusions
  9899. if (parsedLight.excludedMeshesIds) {
  9900. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9901. }
  9902. if (parsedLight.includedOnlyMeshesIds) {
  9903. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9904. }
  9905. // Parent
  9906. if (parsedLight.parentId) {
  9907. light._waitingParentId = parsedLight.parentId;
  9908. }
  9909. // Animations
  9910. if (parsedLight.animations) {
  9911. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9912. var parsedAnimation = parsedLight.animations[animationIndex];
  9913. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9914. }
  9915. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9916. }
  9917. if (parsedLight.autoAnimate) {
  9918. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9919. }
  9920. return light;
  9921. };
  9922. __decorate([
  9923. BABYLON.serializeAsColor3()
  9924. ], Light.prototype, "diffuse", void 0);
  9925. __decorate([
  9926. BABYLON.serializeAsColor3()
  9927. ], Light.prototype, "specular", void 0);
  9928. __decorate([
  9929. BABYLON.serialize()
  9930. ], Light.prototype, "intensity", void 0);
  9931. __decorate([
  9932. BABYLON.serialize()
  9933. ], Light.prototype, "range", void 0);
  9934. __decorate([
  9935. BABYLON.serialize()
  9936. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9937. __decorate([
  9938. BABYLON.serialize()
  9939. ], Light.prototype, "excludeWithLayerMask", void 0);
  9940. __decorate([
  9941. BABYLON.serialize()
  9942. ], Light.prototype, "radius", void 0);
  9943. return Light;
  9944. })(BABYLON.Node);
  9945. BABYLON.Light = Light;
  9946. })(BABYLON || (BABYLON = {}));
  9947. var BABYLON;
  9948. (function (BABYLON) {
  9949. var PointLight = (function (_super) {
  9950. __extends(PointLight, _super);
  9951. function PointLight(name, position, scene) {
  9952. _super.call(this, name, scene);
  9953. this.position = position;
  9954. }
  9955. PointLight.prototype.getAbsolutePosition = function () {
  9956. return this.transformedPosition ? this.transformedPosition : this.position;
  9957. };
  9958. PointLight.prototype.computeTransformedPosition = function () {
  9959. if (this.parent && this.parent.getWorldMatrix) {
  9960. if (!this.transformedPosition) {
  9961. this.transformedPosition = BABYLON.Vector3.Zero();
  9962. }
  9963. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9964. return true;
  9965. }
  9966. return false;
  9967. };
  9968. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9969. if (this.parent && this.parent.getWorldMatrix) {
  9970. this.computeTransformedPosition();
  9971. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9972. return;
  9973. }
  9974. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9975. };
  9976. PointLight.prototype.needCube = function () {
  9977. return true;
  9978. };
  9979. PointLight.prototype.supportsVSM = function () {
  9980. return false;
  9981. };
  9982. PointLight.prototype.needRefreshPerFrame = function () {
  9983. return false;
  9984. };
  9985. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9986. switch (faceIndex) {
  9987. case 0:
  9988. return new BABYLON.Vector3(1, 0, 0);
  9989. case 1:
  9990. return new BABYLON.Vector3(-1, 0, 0);
  9991. case 2:
  9992. return new BABYLON.Vector3(0, -1, 0);
  9993. case 3:
  9994. return new BABYLON.Vector3(0, 1, 0);
  9995. case 4:
  9996. return new BABYLON.Vector3(0, 0, 1);
  9997. case 5:
  9998. return new BABYLON.Vector3(0, 0, -1);
  9999. }
  10000. return BABYLON.Vector3.Zero();
  10001. };
  10002. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10003. var activeCamera = this.getScene().activeCamera;
  10004. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10005. };
  10006. PointLight.prototype._getWorldMatrix = function () {
  10007. if (!this._worldMatrix) {
  10008. this._worldMatrix = BABYLON.Matrix.Identity();
  10009. }
  10010. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10011. return this._worldMatrix;
  10012. };
  10013. PointLight.prototype.getTypeID = function () {
  10014. return 0;
  10015. };
  10016. __decorate([
  10017. BABYLON.serializeAsVector3()
  10018. ], PointLight.prototype, "position", void 0);
  10019. return PointLight;
  10020. })(BABYLON.Light);
  10021. BABYLON.PointLight = PointLight;
  10022. })(BABYLON || (BABYLON = {}));
  10023. var BABYLON;
  10024. (function (BABYLON) {
  10025. var SpotLight = (function (_super) {
  10026. __extends(SpotLight, _super);
  10027. function SpotLight(name, position, direction, angle, exponent, scene) {
  10028. _super.call(this, name, scene);
  10029. this.position = position;
  10030. this.direction = direction;
  10031. this.angle = angle;
  10032. this.exponent = exponent;
  10033. }
  10034. SpotLight.prototype.getAbsolutePosition = function () {
  10035. return this.transformedPosition ? this.transformedPosition : this.position;
  10036. };
  10037. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10038. var activeCamera = this.getScene().activeCamera;
  10039. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10040. };
  10041. SpotLight.prototype.needCube = function () {
  10042. return false;
  10043. };
  10044. SpotLight.prototype.supportsVSM = function () {
  10045. return true;
  10046. };
  10047. SpotLight.prototype.needRefreshPerFrame = function () {
  10048. return false;
  10049. };
  10050. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10051. return this.direction;
  10052. };
  10053. SpotLight.prototype.setDirectionToTarget = function (target) {
  10054. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10055. return this.direction;
  10056. };
  10057. SpotLight.prototype.computeTransformedPosition = function () {
  10058. if (this.parent && this.parent.getWorldMatrix) {
  10059. if (!this.transformedPosition) {
  10060. this.transformedPosition = BABYLON.Vector3.Zero();
  10061. }
  10062. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10063. return true;
  10064. }
  10065. return false;
  10066. };
  10067. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10068. var normalizeDirection;
  10069. if (this.parent && this.parent.getWorldMatrix) {
  10070. if (!this._transformedDirection) {
  10071. this._transformedDirection = BABYLON.Vector3.Zero();
  10072. }
  10073. this.computeTransformedPosition();
  10074. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10075. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10076. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10077. }
  10078. else {
  10079. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10080. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10081. }
  10082. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10083. };
  10084. SpotLight.prototype._getWorldMatrix = function () {
  10085. if (!this._worldMatrix) {
  10086. this._worldMatrix = BABYLON.Matrix.Identity();
  10087. }
  10088. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10089. return this._worldMatrix;
  10090. };
  10091. SpotLight.prototype.getTypeID = function () {
  10092. return 2;
  10093. };
  10094. __decorate([
  10095. BABYLON.serializeAsVector3()
  10096. ], SpotLight.prototype, "position", void 0);
  10097. __decorate([
  10098. BABYLON.serializeAsVector3()
  10099. ], SpotLight.prototype, "direction", void 0);
  10100. __decorate([
  10101. BABYLON.serialize()
  10102. ], SpotLight.prototype, "angle", void 0);
  10103. __decorate([
  10104. BABYLON.serialize()
  10105. ], SpotLight.prototype, "exponent", void 0);
  10106. return SpotLight;
  10107. })(BABYLON.Light);
  10108. BABYLON.SpotLight = SpotLight;
  10109. })(BABYLON || (BABYLON = {}));
  10110. var BABYLON;
  10111. (function (BABYLON) {
  10112. var HemisphericLight = (function (_super) {
  10113. __extends(HemisphericLight, _super);
  10114. function HemisphericLight(name, direction, scene) {
  10115. _super.call(this, name, scene);
  10116. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10117. this.direction = direction;
  10118. }
  10119. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10120. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10121. return this.direction;
  10122. };
  10123. HemisphericLight.prototype.getShadowGenerator = function () {
  10124. return null;
  10125. };
  10126. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10127. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10128. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10129. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10130. };
  10131. HemisphericLight.prototype._getWorldMatrix = function () {
  10132. if (!this._worldMatrix) {
  10133. this._worldMatrix = BABYLON.Matrix.Identity();
  10134. }
  10135. return this._worldMatrix;
  10136. };
  10137. HemisphericLight.prototype.getTypeID = function () {
  10138. return 3;
  10139. };
  10140. __decorate([
  10141. BABYLON.serializeAsColor3()
  10142. ], HemisphericLight.prototype, "groundColor", void 0);
  10143. __decorate([
  10144. BABYLON.serializeAsVector3()
  10145. ], HemisphericLight.prototype, "direction", void 0);
  10146. return HemisphericLight;
  10147. })(BABYLON.Light);
  10148. BABYLON.HemisphericLight = HemisphericLight;
  10149. })(BABYLON || (BABYLON = {}));
  10150. var BABYLON;
  10151. (function (BABYLON) {
  10152. var DirectionalLight = (function (_super) {
  10153. __extends(DirectionalLight, _super);
  10154. function DirectionalLight(name, direction, scene) {
  10155. _super.call(this, name, scene);
  10156. this.shadowOrthoScale = 0.5;
  10157. this.autoUpdateExtends = true;
  10158. // Cache
  10159. this._orthoLeft = Number.MAX_VALUE;
  10160. this._orthoRight = Number.MIN_VALUE;
  10161. this._orthoTop = Number.MIN_VALUE;
  10162. this._orthoBottom = Number.MAX_VALUE;
  10163. this.position = direction.scale(-1);
  10164. this.direction = direction;
  10165. }
  10166. DirectionalLight.prototype.getAbsolutePosition = function () {
  10167. return this.transformedPosition ? this.transformedPosition : this.position;
  10168. };
  10169. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10170. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10171. return this.direction;
  10172. };
  10173. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10174. var activeCamera = this.getScene().activeCamera;
  10175. // Check extends
  10176. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10177. var tempVector3 = BABYLON.Vector3.Zero();
  10178. this._orthoLeft = Number.MAX_VALUE;
  10179. this._orthoRight = Number.MIN_VALUE;
  10180. this._orthoTop = Number.MIN_VALUE;
  10181. this._orthoBottom = Number.MAX_VALUE;
  10182. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10183. var mesh = renderList[meshIndex];
  10184. if (!mesh) {
  10185. continue;
  10186. }
  10187. var boundingInfo = mesh.getBoundingInfo();
  10188. if (!boundingInfo) {
  10189. continue;
  10190. }
  10191. var boundingBox = boundingInfo.boundingBox;
  10192. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10193. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10194. if (tempVector3.x < this._orthoLeft)
  10195. this._orthoLeft = tempVector3.x;
  10196. if (tempVector3.y < this._orthoBottom)
  10197. this._orthoBottom = tempVector3.y;
  10198. if (tempVector3.x > this._orthoRight)
  10199. this._orthoRight = tempVector3.x;
  10200. if (tempVector3.y > this._orthoTop)
  10201. this._orthoTop = tempVector3.y;
  10202. }
  10203. }
  10204. }
  10205. var xOffset = this._orthoRight - this._orthoLeft;
  10206. var yOffset = this._orthoTop - this._orthoBottom;
  10207. 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);
  10208. };
  10209. DirectionalLight.prototype.supportsVSM = function () {
  10210. return true;
  10211. };
  10212. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10213. return true;
  10214. };
  10215. DirectionalLight.prototype.needCube = function () {
  10216. return false;
  10217. };
  10218. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10219. return this.direction;
  10220. };
  10221. DirectionalLight.prototype.computeTransformedPosition = function () {
  10222. if (this.parent && this.parent.getWorldMatrix) {
  10223. if (!this.transformedPosition) {
  10224. this.transformedPosition = BABYLON.Vector3.Zero();
  10225. }
  10226. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10227. return true;
  10228. }
  10229. return false;
  10230. };
  10231. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10232. if (this.parent && this.parent.getWorldMatrix) {
  10233. if (!this._transformedDirection) {
  10234. this._transformedDirection = BABYLON.Vector3.Zero();
  10235. }
  10236. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10237. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10238. return;
  10239. }
  10240. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10241. };
  10242. DirectionalLight.prototype._getWorldMatrix = function () {
  10243. if (!this._worldMatrix) {
  10244. this._worldMatrix = BABYLON.Matrix.Identity();
  10245. }
  10246. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10247. return this._worldMatrix;
  10248. };
  10249. DirectionalLight.prototype.getTypeID = function () {
  10250. return 1;
  10251. };
  10252. __decorate([
  10253. BABYLON.serializeAsVector3()
  10254. ], DirectionalLight.prototype, "position", void 0);
  10255. __decorate([
  10256. BABYLON.serializeAsVector3()
  10257. ], DirectionalLight.prototype, "direction", void 0);
  10258. __decorate([
  10259. BABYLON.serialize()
  10260. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10261. __decorate([
  10262. BABYLON.serialize()
  10263. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10264. return DirectionalLight;
  10265. })(BABYLON.Light);
  10266. BABYLON.DirectionalLight = DirectionalLight;
  10267. })(BABYLON || (BABYLON = {}));
  10268. var BABYLON;
  10269. (function (BABYLON) {
  10270. var ShadowGenerator = (function () {
  10271. function ShadowGenerator(mapSize, light) {
  10272. var _this = this;
  10273. // Members
  10274. this._filter = ShadowGenerator.FILTER_NONE;
  10275. this.blurScale = 2;
  10276. this._blurBoxOffset = 0;
  10277. this._bias = 0.00005;
  10278. this._lightDirection = BABYLON.Vector3.Zero();
  10279. this.forceBackFacesOnly = false;
  10280. this._darkness = 0;
  10281. this._transparencyShadow = false;
  10282. this._viewMatrix = BABYLON.Matrix.Zero();
  10283. this._projectionMatrix = BABYLON.Matrix.Zero();
  10284. this._transformMatrix = BABYLON.Matrix.Zero();
  10285. this._worldViewProjection = BABYLON.Matrix.Zero();
  10286. this._currentFaceIndex = 0;
  10287. this._currentFaceIndexCache = 0;
  10288. this._light = light;
  10289. this._scene = light.getScene();
  10290. this._mapSize = mapSize;
  10291. light._shadowGenerator = this;
  10292. // Render target
  10293. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  10294. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10295. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10296. this._shadowMap.anisotropicFilteringLevel = 1;
  10297. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10298. this._shadowMap.renderParticles = false;
  10299. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10300. _this._currentFaceIndex = faceIndex;
  10301. });
  10302. this._shadowMap.onAfterUnbindObservable.add(function () {
  10303. if (!_this.useBlurVarianceShadowMap) {
  10304. return;
  10305. }
  10306. if (!_this._shadowMap2) {
  10307. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10308. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10309. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10310. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10311. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10312. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10313. effect.setTexture("textureSampler", _this._shadowMap);
  10314. });
  10315. _this.blurBoxOffset = 1;
  10316. }
  10317. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10318. });
  10319. // Custom render function
  10320. var renderSubMesh = function (subMesh) {
  10321. var mesh = subMesh.getRenderingMesh();
  10322. var scene = _this._scene;
  10323. var engine = scene.getEngine();
  10324. // Culling
  10325. engine.setState(subMesh.getMaterial().backFaceCulling);
  10326. // Managing instances
  10327. var batch = mesh._getInstancesRenderList(subMesh._id);
  10328. if (batch.mustReturn) {
  10329. return;
  10330. }
  10331. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10332. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10333. engine.enableEffect(_this._effect);
  10334. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10335. var material = subMesh.getMaterial();
  10336. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10337. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10338. if (_this.getLight().needCube()) {
  10339. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10340. }
  10341. // Alpha test
  10342. if (material && material.needAlphaTesting()) {
  10343. var alphaTexture = material.getAlphaTestTexture();
  10344. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10345. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10346. }
  10347. // Bones
  10348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10349. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10350. }
  10351. if (_this.forceBackFacesOnly) {
  10352. engine.setState(true, 0, false, true);
  10353. }
  10354. // Draw
  10355. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10356. if (_this.forceBackFacesOnly) {
  10357. engine.setState(true, 0, false, false);
  10358. }
  10359. }
  10360. else {
  10361. // Need to reset refresh rate of the shadowMap
  10362. _this._shadowMap.resetRefreshCounter();
  10363. }
  10364. };
  10365. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10366. var index;
  10367. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10368. renderSubMesh(opaqueSubMeshes.data[index]);
  10369. }
  10370. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10371. renderSubMesh(alphaTestSubMeshes.data[index]);
  10372. }
  10373. if (_this._transparencyShadow) {
  10374. for (index = 0; index < transparentSubMeshes.length; index++) {
  10375. renderSubMesh(transparentSubMeshes.data[index]);
  10376. }
  10377. }
  10378. };
  10379. this._shadowMap.onClearObservable.add(function (engine) {
  10380. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10381. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10382. }
  10383. else {
  10384. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10385. }
  10386. });
  10387. }
  10388. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10389. // Static
  10390. get: function () {
  10391. return ShadowGenerator._FILTER_NONE;
  10392. },
  10393. enumerable: true,
  10394. configurable: true
  10395. });
  10396. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10397. get: function () {
  10398. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10399. },
  10400. enumerable: true,
  10401. configurable: true
  10402. });
  10403. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10404. get: function () {
  10405. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10411. get: function () {
  10412. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10418. get: function () {
  10419. return this._bias;
  10420. },
  10421. set: function (bias) {
  10422. this._bias = bias;
  10423. },
  10424. enumerable: true,
  10425. configurable: true
  10426. });
  10427. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10428. get: function () {
  10429. return this._blurBoxOffset;
  10430. },
  10431. set: function (value) {
  10432. var _this = this;
  10433. if (this._blurBoxOffset === value) {
  10434. return;
  10435. }
  10436. this._blurBoxOffset = value;
  10437. if (this._boxBlurPostprocess) {
  10438. this._boxBlurPostprocess.dispose();
  10439. }
  10440. 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);
  10441. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  10442. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10443. });
  10444. },
  10445. enumerable: true,
  10446. configurable: true
  10447. });
  10448. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10449. get: function () {
  10450. return this._filter;
  10451. },
  10452. set: function (value) {
  10453. if (this._filter === value) {
  10454. return;
  10455. }
  10456. this._filter = value;
  10457. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10458. this._shadowMap.anisotropicFilteringLevel = 16;
  10459. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10460. }
  10461. else {
  10462. this._shadowMap.anisotropicFilteringLevel = 1;
  10463. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10464. }
  10465. },
  10466. enumerable: true,
  10467. configurable: true
  10468. });
  10469. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10470. get: function () {
  10471. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10472. },
  10473. set: function (value) {
  10474. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10475. },
  10476. enumerable: true,
  10477. configurable: true
  10478. });
  10479. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10480. get: function () {
  10481. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10482. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10483. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10484. },
  10485. set: function (value) {
  10486. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10487. },
  10488. enumerable: true,
  10489. configurable: true
  10490. });
  10491. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10492. get: function () {
  10493. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10494. },
  10495. set: function (value) {
  10496. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10497. },
  10498. enumerable: true,
  10499. configurable: true
  10500. });
  10501. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10502. var defines = [];
  10503. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10504. defines.push("#define VSM");
  10505. }
  10506. if (this.getLight().needCube()) {
  10507. defines.push("#define CUBEMAP");
  10508. }
  10509. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10510. var mesh = subMesh.getMesh();
  10511. var material = subMesh.getMaterial();
  10512. // Alpha test
  10513. if (material && material.needAlphaTesting()) {
  10514. defines.push("#define ALPHATEST");
  10515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10516. attribs.push(BABYLON.VertexBuffer.UVKind);
  10517. defines.push("#define UV1");
  10518. }
  10519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10520. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10521. defines.push("#define UV2");
  10522. }
  10523. }
  10524. // Bones
  10525. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10526. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10527. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10528. if (mesh.numBoneInfluencers > 4) {
  10529. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10530. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10531. }
  10532. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10533. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10534. }
  10535. else {
  10536. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10537. }
  10538. // Instances
  10539. if (useInstances) {
  10540. defines.push("#define INSTANCES");
  10541. attribs.push("world0");
  10542. attribs.push("world1");
  10543. attribs.push("world2");
  10544. attribs.push("world3");
  10545. }
  10546. // Get correct effect
  10547. var join = defines.join("\n");
  10548. if (this._cachedDefines !== join) {
  10549. this._cachedDefines = join;
  10550. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10551. }
  10552. return this._effect.isReady();
  10553. };
  10554. ShadowGenerator.prototype.getShadowMap = function () {
  10555. return this._shadowMap;
  10556. };
  10557. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10558. if (this._shadowMap2) {
  10559. return this._shadowMap2;
  10560. }
  10561. return this._shadowMap;
  10562. };
  10563. ShadowGenerator.prototype.getLight = function () {
  10564. return this._light;
  10565. };
  10566. // Methods
  10567. ShadowGenerator.prototype.getTransformMatrix = function () {
  10568. var scene = this._scene;
  10569. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10570. return this._transformMatrix;
  10571. }
  10572. this._currentRenderID = scene.getRenderId();
  10573. this._currentFaceIndexCache = this._currentFaceIndex;
  10574. var lightPosition = this._light.position;
  10575. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10576. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10577. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10578. }
  10579. if (this._light.computeTransformedPosition()) {
  10580. lightPosition = this._light.transformedPosition;
  10581. }
  10582. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10583. this._cachedPosition = lightPosition.clone();
  10584. this._cachedDirection = this._lightDirection.clone();
  10585. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10586. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10587. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10588. }
  10589. return this._transformMatrix;
  10590. };
  10591. ShadowGenerator.prototype.getDarkness = function () {
  10592. return this._darkness;
  10593. };
  10594. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10595. if (darkness >= 1.0)
  10596. this._darkness = 1.0;
  10597. else if (darkness <= 0.0)
  10598. this._darkness = 0.0;
  10599. else
  10600. this._darkness = darkness;
  10601. };
  10602. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10603. this._transparencyShadow = hasShadow;
  10604. };
  10605. ShadowGenerator.prototype._packHalf = function (depth) {
  10606. var scale = depth * 255.0;
  10607. var fract = scale - Math.floor(scale);
  10608. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10609. };
  10610. ShadowGenerator.prototype.dispose = function () {
  10611. this._shadowMap.dispose();
  10612. if (this._shadowMap2) {
  10613. this._shadowMap2.dispose();
  10614. }
  10615. if (this._downSamplePostprocess) {
  10616. this._downSamplePostprocess.dispose();
  10617. }
  10618. if (this._boxBlurPostprocess) {
  10619. this._boxBlurPostprocess.dispose();
  10620. }
  10621. };
  10622. ShadowGenerator.prototype.serialize = function () {
  10623. var serializationObject = {};
  10624. serializationObject.lightId = this._light.id;
  10625. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10626. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10627. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10628. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10629. serializationObject.renderList = [];
  10630. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10631. var mesh = this.getShadowMap().renderList[meshIndex];
  10632. serializationObject.renderList.push(mesh.id);
  10633. }
  10634. return serializationObject;
  10635. };
  10636. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10637. //casting to point light, as light is missing the position attr and typescript complains.
  10638. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10639. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10640. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10641. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10642. meshes.forEach(function (mesh) {
  10643. shadowGenerator.getShadowMap().renderList.push(mesh);
  10644. });
  10645. }
  10646. if (parsedShadowGenerator.usePoissonSampling) {
  10647. shadowGenerator.usePoissonSampling = true;
  10648. }
  10649. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10650. shadowGenerator.useVarianceShadowMap = true;
  10651. }
  10652. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10653. shadowGenerator.useBlurVarianceShadowMap = true;
  10654. if (parsedShadowGenerator.blurScale) {
  10655. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10656. }
  10657. if (parsedShadowGenerator.blurBoxOffset) {
  10658. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10659. }
  10660. }
  10661. if (parsedShadowGenerator.bias !== undefined) {
  10662. shadowGenerator.bias = parsedShadowGenerator.bias;
  10663. }
  10664. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10665. return shadowGenerator;
  10666. };
  10667. ShadowGenerator._FILTER_NONE = 0;
  10668. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10669. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10670. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10671. return ShadowGenerator;
  10672. })();
  10673. BABYLON.ShadowGenerator = ShadowGenerator;
  10674. })(BABYLON || (BABYLON = {}));
  10675. var BABYLON;
  10676. (function (BABYLON) {
  10677. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10678. if (boxMin.x > sphereCenter.x + sphereRadius)
  10679. return false;
  10680. if (sphereCenter.x - sphereRadius > boxMax.x)
  10681. return false;
  10682. if (boxMin.y > sphereCenter.y + sphereRadius)
  10683. return false;
  10684. if (sphereCenter.y - sphereRadius > boxMax.y)
  10685. return false;
  10686. if (boxMin.z > sphereCenter.z + sphereRadius)
  10687. return false;
  10688. if (sphereCenter.z - sphereRadius > boxMax.z)
  10689. return false;
  10690. return true;
  10691. };
  10692. var getLowestRoot = function (a, b, c, maxR) {
  10693. var determinant = b * b - 4.0 * a * c;
  10694. var result = { root: 0, found: false };
  10695. if (determinant < 0)
  10696. return result;
  10697. var sqrtD = Math.sqrt(determinant);
  10698. var r1 = (-b - sqrtD) / (2.0 * a);
  10699. var r2 = (-b + sqrtD) / (2.0 * a);
  10700. if (r1 > r2) {
  10701. var temp = r2;
  10702. r2 = r1;
  10703. r1 = temp;
  10704. }
  10705. if (r1 > 0 && r1 < maxR) {
  10706. result.root = r1;
  10707. result.found = true;
  10708. return result;
  10709. }
  10710. if (r2 > 0 && r2 < maxR) {
  10711. result.root = r2;
  10712. result.found = true;
  10713. return result;
  10714. }
  10715. return result;
  10716. };
  10717. var Collider = (function () {
  10718. function Collider() {
  10719. this.radius = new BABYLON.Vector3(1, 1, 1);
  10720. this.retry = 0;
  10721. this.basePointWorld = BABYLON.Vector3.Zero();
  10722. this.velocityWorld = BABYLON.Vector3.Zero();
  10723. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10724. this._collisionPoint = BABYLON.Vector3.Zero();
  10725. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10726. this._tempVector = BABYLON.Vector3.Zero();
  10727. this._tempVector2 = BABYLON.Vector3.Zero();
  10728. this._tempVector3 = BABYLON.Vector3.Zero();
  10729. this._tempVector4 = BABYLON.Vector3.Zero();
  10730. this._edge = BABYLON.Vector3.Zero();
  10731. this._baseToVertex = BABYLON.Vector3.Zero();
  10732. this._destinationPoint = BABYLON.Vector3.Zero();
  10733. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10734. this._displacementVector = BABYLON.Vector3.Zero();
  10735. }
  10736. // Methods
  10737. Collider.prototype._initialize = function (source, dir, e) {
  10738. this.velocity = dir;
  10739. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10740. this.basePoint = source;
  10741. source.multiplyToRef(this.radius, this.basePointWorld);
  10742. dir.multiplyToRef(this.radius, this.velocityWorld);
  10743. this.velocityWorldLength = this.velocityWorld.length();
  10744. this.epsilon = e;
  10745. this.collisionFound = false;
  10746. };
  10747. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10748. pa.subtractToRef(point, this._tempVector);
  10749. pb.subtractToRef(point, this._tempVector2);
  10750. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10751. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10752. if (d < 0)
  10753. return false;
  10754. pc.subtractToRef(point, this._tempVector3);
  10755. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10756. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10757. if (d < 0)
  10758. return false;
  10759. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10760. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10761. return d >= 0;
  10762. };
  10763. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10764. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10765. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10766. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10767. return false;
  10768. }
  10769. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10770. return false;
  10771. return true;
  10772. };
  10773. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10774. var t0;
  10775. var embeddedInPlane = false;
  10776. //defensive programming, actually not needed.
  10777. if (!trianglePlaneArray) {
  10778. trianglePlaneArray = [];
  10779. }
  10780. if (!trianglePlaneArray[faceIndex]) {
  10781. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10782. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10783. }
  10784. var trianglePlane = trianglePlaneArray[faceIndex];
  10785. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10786. return;
  10787. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10788. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10789. if (normalDotVelocity == 0) {
  10790. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10791. return;
  10792. embeddedInPlane = true;
  10793. t0 = 0;
  10794. }
  10795. else {
  10796. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10797. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10798. if (t0 > t1) {
  10799. var temp = t1;
  10800. t1 = t0;
  10801. t0 = temp;
  10802. }
  10803. if (t0 > 1.0 || t1 < 0.0)
  10804. return;
  10805. if (t0 < 0)
  10806. t0 = 0;
  10807. if (t0 > 1.0)
  10808. t0 = 1.0;
  10809. }
  10810. this._collisionPoint.copyFromFloats(0, 0, 0);
  10811. var found = false;
  10812. var t = 1.0;
  10813. if (!embeddedInPlane) {
  10814. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10815. this.velocity.scaleToRef(t0, this._tempVector);
  10816. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10817. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10818. found = true;
  10819. t = t0;
  10820. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10821. }
  10822. }
  10823. if (!found) {
  10824. var velocitySquaredLength = this.velocity.lengthSquared();
  10825. var a = velocitySquaredLength;
  10826. this.basePoint.subtractToRef(p1, this._tempVector);
  10827. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10828. var c = this._tempVector.lengthSquared() - 1.0;
  10829. var lowestRoot = getLowestRoot(a, b, c, t);
  10830. if (lowestRoot.found) {
  10831. t = lowestRoot.root;
  10832. found = true;
  10833. this._collisionPoint.copyFrom(p1);
  10834. }
  10835. this.basePoint.subtractToRef(p2, this._tempVector);
  10836. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10837. c = this._tempVector.lengthSquared() - 1.0;
  10838. lowestRoot = getLowestRoot(a, b, c, t);
  10839. if (lowestRoot.found) {
  10840. t = lowestRoot.root;
  10841. found = true;
  10842. this._collisionPoint.copyFrom(p2);
  10843. }
  10844. this.basePoint.subtractToRef(p3, this._tempVector);
  10845. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10846. c = this._tempVector.lengthSquared() - 1.0;
  10847. lowestRoot = getLowestRoot(a, b, c, t);
  10848. if (lowestRoot.found) {
  10849. t = lowestRoot.root;
  10850. found = true;
  10851. this._collisionPoint.copyFrom(p3);
  10852. }
  10853. p2.subtractToRef(p1, this._edge);
  10854. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10855. var edgeSquaredLength = this._edge.lengthSquared();
  10856. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10857. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10858. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10859. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10860. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10861. lowestRoot = getLowestRoot(a, b, c, t);
  10862. if (lowestRoot.found) {
  10863. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10864. if (f >= 0.0 && f <= 1.0) {
  10865. t = lowestRoot.root;
  10866. found = true;
  10867. this._edge.scaleInPlace(f);
  10868. p1.addToRef(this._edge, this._collisionPoint);
  10869. }
  10870. }
  10871. p3.subtractToRef(p2, this._edge);
  10872. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10873. edgeSquaredLength = this._edge.lengthSquared();
  10874. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10875. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10876. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10877. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10878. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10879. lowestRoot = getLowestRoot(a, b, c, t);
  10880. if (lowestRoot.found) {
  10881. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10882. if (f >= 0.0 && f <= 1.0) {
  10883. t = lowestRoot.root;
  10884. found = true;
  10885. this._edge.scaleInPlace(f);
  10886. p2.addToRef(this._edge, this._collisionPoint);
  10887. }
  10888. }
  10889. p1.subtractToRef(p3, this._edge);
  10890. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10891. edgeSquaredLength = this._edge.lengthSquared();
  10892. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10893. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10894. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10895. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10896. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10897. lowestRoot = getLowestRoot(a, b, c, t);
  10898. if (lowestRoot.found) {
  10899. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10900. if (f >= 0.0 && f <= 1.0) {
  10901. t = lowestRoot.root;
  10902. found = true;
  10903. this._edge.scaleInPlace(f);
  10904. p3.addToRef(this._edge, this._collisionPoint);
  10905. }
  10906. }
  10907. }
  10908. if (found) {
  10909. var distToCollision = t * this.velocity.length();
  10910. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10911. if (!this.intersectionPoint) {
  10912. this.intersectionPoint = this._collisionPoint.clone();
  10913. }
  10914. else {
  10915. this.intersectionPoint.copyFrom(this._collisionPoint);
  10916. }
  10917. this.nearestDistance = distToCollision;
  10918. this.collisionFound = true;
  10919. }
  10920. }
  10921. };
  10922. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10923. for (var i = indexStart; i < indexEnd; i += 3) {
  10924. var p1 = pts[indices[i] - decal];
  10925. var p2 = pts[indices[i + 1] - decal];
  10926. var p3 = pts[indices[i + 2] - decal];
  10927. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10928. }
  10929. };
  10930. Collider.prototype._getResponse = function (pos, vel) {
  10931. pos.addToRef(vel, this._destinationPoint);
  10932. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10933. this.basePoint.addToRef(vel, pos);
  10934. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10935. this._slidePlaneNormal.normalize();
  10936. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10937. pos.addInPlace(this._displacementVector);
  10938. this.intersectionPoint.addInPlace(this._displacementVector);
  10939. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10940. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10941. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10942. };
  10943. return Collider;
  10944. })();
  10945. BABYLON.Collider = Collider;
  10946. })(BABYLON || (BABYLON = {}));
  10947. var BABYLON;
  10948. (function (BABYLON) {
  10949. //WebWorker code will be inserted to this variable.
  10950. BABYLON.CollisionWorker = "";
  10951. (function (WorkerTaskType) {
  10952. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10953. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10954. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10955. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10956. var WorkerTaskType = BABYLON.WorkerTaskType;
  10957. (function (WorkerReplyType) {
  10958. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10959. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10960. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10961. var WorkerReplyType = BABYLON.WorkerReplyType;
  10962. var CollisionCoordinatorWorker = (function () {
  10963. function CollisionCoordinatorWorker() {
  10964. var _this = this;
  10965. this._scaledPosition = BABYLON.Vector3.Zero();
  10966. this._scaledVelocity = BABYLON.Vector3.Zero();
  10967. this.onMeshUpdated = function (mesh) {
  10968. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10969. };
  10970. this.onGeometryUpdated = function (geometry) {
  10971. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10972. };
  10973. this._afterRender = function () {
  10974. if (!_this._init)
  10975. return;
  10976. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10977. return;
  10978. }
  10979. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10980. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10981. if (_this._runningUpdated > 4) {
  10982. return;
  10983. }
  10984. ++_this._runningUpdated;
  10985. var payload = {
  10986. updatedMeshes: _this._addUpdateMeshesList,
  10987. updatedGeometries: _this._addUpdateGeometriesList,
  10988. removedGeometries: _this._toRemoveGeometryArray,
  10989. removedMeshes: _this._toRemoveMeshesArray
  10990. };
  10991. var message = {
  10992. payload: payload,
  10993. taskType: WorkerTaskType.UPDATE
  10994. };
  10995. var serializable = [];
  10996. for (var id in payload.updatedGeometries) {
  10997. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10998. //prepare transferables
  10999. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11000. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11001. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11002. }
  11003. }
  11004. _this._worker.postMessage(message, serializable);
  11005. _this._addUpdateMeshesList = {};
  11006. _this._addUpdateGeometriesList = {};
  11007. _this._toRemoveGeometryArray = [];
  11008. _this._toRemoveMeshesArray = [];
  11009. };
  11010. this._onMessageFromWorker = function (e) {
  11011. var returnData = e.data;
  11012. if (returnData.error != WorkerReplyType.SUCCESS) {
  11013. //TODO what errors can be returned from the worker?
  11014. BABYLON.Tools.Warn("error returned from worker!");
  11015. return;
  11016. }
  11017. switch (returnData.taskType) {
  11018. case WorkerTaskType.INIT:
  11019. _this._init = true;
  11020. //Update the worked with ALL of the scene's current state
  11021. _this._scene.meshes.forEach(function (mesh) {
  11022. _this.onMeshAdded(mesh);
  11023. });
  11024. _this._scene.getGeometries().forEach(function (geometry) {
  11025. _this.onGeometryAdded(geometry);
  11026. });
  11027. break;
  11028. case WorkerTaskType.UPDATE:
  11029. _this._runningUpdated--;
  11030. break;
  11031. case WorkerTaskType.COLLIDE:
  11032. _this._runningCollisionTask = false;
  11033. var returnPayload = returnData.payload;
  11034. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11035. return;
  11036. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11037. //cleanup
  11038. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11039. break;
  11040. }
  11041. };
  11042. this._collisionsCallbackArray = [];
  11043. this._init = false;
  11044. this._runningUpdated = 0;
  11045. this._runningCollisionTask = false;
  11046. this._addUpdateMeshesList = {};
  11047. this._addUpdateGeometriesList = {};
  11048. this._toRemoveGeometryArray = [];
  11049. this._toRemoveMeshesArray = [];
  11050. }
  11051. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11052. if (!this._init)
  11053. return;
  11054. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11055. return;
  11056. position.divideToRef(collider.radius, this._scaledPosition);
  11057. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11058. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11059. var payload = {
  11060. collider: {
  11061. position: this._scaledPosition.asArray(),
  11062. velocity: this._scaledVelocity.asArray(),
  11063. radius: collider.radius.asArray()
  11064. },
  11065. collisionId: collisionIndex,
  11066. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11067. maximumRetry: maximumRetry
  11068. };
  11069. var message = {
  11070. payload: payload,
  11071. taskType: WorkerTaskType.COLLIDE
  11072. };
  11073. this._worker.postMessage(message);
  11074. };
  11075. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11076. this._scene = scene;
  11077. this._scene.registerAfterRender(this._afterRender);
  11078. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11079. this._worker = new Worker(workerUrl);
  11080. this._worker.onmessage = this._onMessageFromWorker;
  11081. var message = {
  11082. payload: {},
  11083. taskType: WorkerTaskType.INIT
  11084. };
  11085. this._worker.postMessage(message);
  11086. };
  11087. CollisionCoordinatorWorker.prototype.destroy = function () {
  11088. this._scene.unregisterAfterRender(this._afterRender);
  11089. this._worker.terminate();
  11090. };
  11091. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11092. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11093. this.onMeshUpdated(mesh);
  11094. };
  11095. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11096. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11097. };
  11098. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11099. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11100. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11101. this.onGeometryUpdated(geometry);
  11102. };
  11103. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11104. this._toRemoveGeometryArray.push(geometry.id);
  11105. };
  11106. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11107. var submeshes = [];
  11108. if (mesh.subMeshes) {
  11109. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11110. return {
  11111. position: idx,
  11112. verticesStart: sm.verticesStart,
  11113. verticesCount: sm.verticesCount,
  11114. indexStart: sm.indexStart,
  11115. indexCount: sm.indexCount,
  11116. hasMaterial: !!sm.getMaterial(),
  11117. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11118. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11119. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11120. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11121. };
  11122. });
  11123. }
  11124. var geometryId = null;
  11125. if (mesh instanceof BABYLON.Mesh) {
  11126. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11127. }
  11128. else if (mesh instanceof BABYLON.InstancedMesh) {
  11129. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11130. }
  11131. return {
  11132. uniqueId: mesh.uniqueId,
  11133. id: mesh.id,
  11134. name: mesh.name,
  11135. geometryId: geometryId,
  11136. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11137. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11138. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11139. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11140. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11141. subMeshes: submeshes,
  11142. checkCollisions: mesh.checkCollisions
  11143. };
  11144. };
  11145. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11146. return {
  11147. id: geometry.id,
  11148. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11149. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11150. indices: new Int32Array(geometry.getIndices() || []),
  11151. };
  11152. };
  11153. return CollisionCoordinatorWorker;
  11154. })();
  11155. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11156. var CollisionCoordinatorLegacy = (function () {
  11157. function CollisionCoordinatorLegacy() {
  11158. this._scaledPosition = BABYLON.Vector3.Zero();
  11159. this._scaledVelocity = BABYLON.Vector3.Zero();
  11160. this._finalPosition = BABYLON.Vector3.Zero();
  11161. }
  11162. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11163. position.divideToRef(collider.radius, this._scaledPosition);
  11164. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11165. collider.collidedMesh = null;
  11166. collider.retry = 0;
  11167. collider.initialVelocity = this._scaledVelocity;
  11168. collider.initialPosition = this._scaledPosition;
  11169. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11170. this._finalPosition.multiplyInPlace(collider.radius);
  11171. //run the callback
  11172. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11173. };
  11174. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11175. this._scene = scene;
  11176. };
  11177. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11178. //Legacy need no destruction method.
  11179. };
  11180. //No update in legacy mode
  11181. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11182. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11183. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11184. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11185. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11186. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11187. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11188. if (excludedMesh === void 0) { excludedMesh = null; }
  11189. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11190. if (collider.retry >= maximumRetry) {
  11191. finalPosition.copyFrom(position);
  11192. return;
  11193. }
  11194. collider._initialize(position, velocity, closeDistance);
  11195. // Check all meshes
  11196. for (var index = 0; index < this._scene.meshes.length; index++) {
  11197. var mesh = this._scene.meshes[index];
  11198. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11199. mesh._checkCollision(collider);
  11200. }
  11201. }
  11202. if (!collider.collisionFound) {
  11203. position.addToRef(velocity, finalPosition);
  11204. return;
  11205. }
  11206. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11207. collider._getResponse(position, velocity);
  11208. }
  11209. if (velocity.length() <= closeDistance) {
  11210. finalPosition.copyFrom(position);
  11211. return;
  11212. }
  11213. collider.retry++;
  11214. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11215. };
  11216. return CollisionCoordinatorLegacy;
  11217. })();
  11218. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11219. })(BABYLON || (BABYLON = {}));
  11220. var BABYLON;
  11221. (function (BABYLON) {
  11222. var Camera = (function (_super) {
  11223. __extends(Camera, _super);
  11224. function Camera(name, position, scene) {
  11225. _super.call(this, name, scene);
  11226. this.upVector = BABYLON.Vector3.Up();
  11227. this.orthoLeft = null;
  11228. this.orthoRight = null;
  11229. this.orthoBottom = null;
  11230. this.orthoTop = null;
  11231. this.fov = 0.8;
  11232. this.minZ = 1.0;
  11233. this.maxZ = 10000.0;
  11234. this.inertia = 0.9;
  11235. this.mode = Camera.PERSPECTIVE_CAMERA;
  11236. this.isIntermediate = false;
  11237. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11238. this.layerMask = 0x0FFFFFFF;
  11239. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11240. // Camera rig members
  11241. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11242. this._rigCameras = new Array();
  11243. // Cache
  11244. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11245. this._projectionMatrix = new BABYLON.Matrix();
  11246. this._postProcesses = new Array();
  11247. this._activeMeshes = new BABYLON.SmartArray(256);
  11248. this._globalPosition = BABYLON.Vector3.Zero();
  11249. scene.addCamera(this);
  11250. if (!scene.activeCamera) {
  11251. scene.activeCamera = this;
  11252. }
  11253. this.position = position;
  11254. }
  11255. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11256. get: function () {
  11257. return Camera._PERSPECTIVE_CAMERA;
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11263. get: function () {
  11264. return Camera._ORTHOGRAPHIC_CAMERA;
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11270. get: function () {
  11271. return Camera._FOVMODE_VERTICAL_FIXED;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11277. get: function () {
  11278. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11279. },
  11280. enumerable: true,
  11281. configurable: true
  11282. });
  11283. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11284. get: function () {
  11285. return Camera._RIG_MODE_NONE;
  11286. },
  11287. enumerable: true,
  11288. configurable: true
  11289. });
  11290. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11291. get: function () {
  11292. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11293. },
  11294. enumerable: true,
  11295. configurable: true
  11296. });
  11297. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11298. get: function () {
  11299. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11300. },
  11301. enumerable: true,
  11302. configurable: true
  11303. });
  11304. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11305. get: function () {
  11306. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11307. },
  11308. enumerable: true,
  11309. configurable: true
  11310. });
  11311. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11312. get: function () {
  11313. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11314. },
  11315. enumerable: true,
  11316. configurable: true
  11317. });
  11318. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11319. get: function () {
  11320. return Camera._RIG_MODE_VR;
  11321. },
  11322. enumerable: true,
  11323. configurable: true
  11324. });
  11325. /**
  11326. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11327. */
  11328. Camera.prototype.toString = function (fullDetails) {
  11329. var ret = "Name: " + this.name;
  11330. ret += ", type: " + this.getTypeName();
  11331. if (this.animations) {
  11332. for (var i = 0; i < this.animations.length; i++) {
  11333. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11334. }
  11335. }
  11336. if (fullDetails) {
  11337. }
  11338. return ret;
  11339. };
  11340. Object.defineProperty(Camera.prototype, "globalPosition", {
  11341. get: function () {
  11342. return this._globalPosition;
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Camera.prototype.getActiveMeshes = function () {
  11348. return this._activeMeshes;
  11349. };
  11350. Camera.prototype.isActiveMesh = function (mesh) {
  11351. return (this._activeMeshes.indexOf(mesh) !== -1);
  11352. };
  11353. //Cache
  11354. Camera.prototype._initCache = function () {
  11355. _super.prototype._initCache.call(this);
  11356. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11357. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11358. this._cache.mode = undefined;
  11359. this._cache.minZ = undefined;
  11360. this._cache.maxZ = undefined;
  11361. this._cache.fov = undefined;
  11362. this._cache.aspectRatio = undefined;
  11363. this._cache.orthoLeft = undefined;
  11364. this._cache.orthoRight = undefined;
  11365. this._cache.orthoBottom = undefined;
  11366. this._cache.orthoTop = undefined;
  11367. this._cache.renderWidth = undefined;
  11368. this._cache.renderHeight = undefined;
  11369. };
  11370. Camera.prototype._updateCache = function (ignoreParentClass) {
  11371. if (!ignoreParentClass) {
  11372. _super.prototype._updateCache.call(this);
  11373. }
  11374. var engine = this.getEngine();
  11375. this._cache.position.copyFrom(this.position);
  11376. this._cache.upVector.copyFrom(this.upVector);
  11377. this._cache.mode = this.mode;
  11378. this._cache.minZ = this.minZ;
  11379. this._cache.maxZ = this.maxZ;
  11380. this._cache.fov = this.fov;
  11381. this._cache.aspectRatio = engine.getAspectRatio(this);
  11382. this._cache.orthoLeft = this.orthoLeft;
  11383. this._cache.orthoRight = this.orthoRight;
  11384. this._cache.orthoBottom = this.orthoBottom;
  11385. this._cache.orthoTop = this.orthoTop;
  11386. this._cache.renderWidth = engine.getRenderWidth();
  11387. this._cache.renderHeight = engine.getRenderHeight();
  11388. };
  11389. Camera.prototype._updateFromScene = function () {
  11390. this.updateCache();
  11391. this._update();
  11392. };
  11393. // Synchronized
  11394. Camera.prototype._isSynchronized = function () {
  11395. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11396. };
  11397. Camera.prototype._isSynchronizedViewMatrix = function () {
  11398. if (!_super.prototype._isSynchronized.call(this))
  11399. return false;
  11400. return this._cache.position.equals(this.position)
  11401. && this._cache.upVector.equals(this.upVector)
  11402. && this.isSynchronizedWithParent();
  11403. };
  11404. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11405. var check = this._cache.mode === this.mode
  11406. && this._cache.minZ === this.minZ
  11407. && this._cache.maxZ === this.maxZ;
  11408. if (!check) {
  11409. return false;
  11410. }
  11411. var engine = this.getEngine();
  11412. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11413. check = this._cache.fov === this.fov
  11414. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11415. }
  11416. else {
  11417. check = this._cache.orthoLeft === this.orthoLeft
  11418. && this._cache.orthoRight === this.orthoRight
  11419. && this._cache.orthoBottom === this.orthoBottom
  11420. && this._cache.orthoTop === this.orthoTop
  11421. && this._cache.renderWidth === engine.getRenderWidth()
  11422. && this._cache.renderHeight === engine.getRenderHeight();
  11423. }
  11424. return check;
  11425. };
  11426. // Controls
  11427. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11428. };
  11429. Camera.prototype.detachControl = function (element) {
  11430. };
  11431. Camera.prototype._update = function () {
  11432. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11433. this._updateRigCameras();
  11434. }
  11435. this._checkInputs();
  11436. };
  11437. Camera.prototype._checkInputs = function () {
  11438. };
  11439. Camera.prototype._cascadePostProcessesToRigCams = function () {
  11440. // invalidate framebuffer
  11441. if (this._postProcesses.length > 0) {
  11442. this._postProcesses[0].markTextureDirty();
  11443. }
  11444. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  11445. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  11446. var cam = this._rigCameras[i];
  11447. var rigPostProcess = cam._rigPostProcess;
  11448. // for VR rig, there does not have to be a post process
  11449. if (rigPostProcess) {
  11450. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  11451. if (isPass) {
  11452. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  11453. cam.isIntermediate = this._postProcesses.length === 0;
  11454. }
  11455. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  11456. rigPostProcess.markTextureDirty();
  11457. }
  11458. }
  11459. };
  11460. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11461. if (insertAt === void 0) { insertAt = null; }
  11462. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11463. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11464. return 0;
  11465. }
  11466. if (insertAt == null || insertAt < 0) {
  11467. this._postProcesses.push(postProcess);
  11468. }
  11469. else {
  11470. this._postProcesses.splice(insertAt, 0, postProcess);
  11471. }
  11472. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11473. return this._postProcesses.indexOf(postProcess);
  11474. };
  11475. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11476. if (atIndices === void 0) { atIndices = null; }
  11477. var result = [];
  11478. var i;
  11479. var index;
  11480. if (!atIndices) {
  11481. var idx = this._postProcesses.indexOf(postProcess);
  11482. if (idx !== -1) {
  11483. this._postProcesses.splice(idx, 1);
  11484. }
  11485. }
  11486. else {
  11487. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11488. // iterate descending, so can just splice as we go
  11489. for (i = atIndices.length - 1; i >= 0; i--) {
  11490. if (this._postProcesses[atIndices[i]] !== postProcess) {
  11491. result.push(i);
  11492. continue;
  11493. }
  11494. this._postProcesses.splice(index, 1);
  11495. }
  11496. }
  11497. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  11498. return result;
  11499. };
  11500. Camera.prototype.getWorldMatrix = function () {
  11501. if (!this._worldMatrix) {
  11502. this._worldMatrix = BABYLON.Matrix.Identity();
  11503. }
  11504. var viewMatrix = this.getViewMatrix();
  11505. viewMatrix.invertToRef(this._worldMatrix);
  11506. return this._worldMatrix;
  11507. };
  11508. Camera.prototype._getViewMatrix = function () {
  11509. return BABYLON.Matrix.Identity();
  11510. };
  11511. Camera.prototype.getViewMatrix = function (force) {
  11512. this._computedViewMatrix = this._computeViewMatrix(force);
  11513. if (!force && this._isSynchronizedViewMatrix()) {
  11514. return this._computedViewMatrix;
  11515. }
  11516. if (!this.parent || !this.parent.getWorldMatrix) {
  11517. this._globalPosition.copyFrom(this.position);
  11518. }
  11519. else {
  11520. if (!this._worldMatrix) {
  11521. this._worldMatrix = BABYLON.Matrix.Identity();
  11522. }
  11523. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11524. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11525. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11526. this._computedViewMatrix.invert();
  11527. this._markSyncedWithParent();
  11528. }
  11529. this._currentRenderId = this.getScene().getRenderId();
  11530. return this._computedViewMatrix;
  11531. };
  11532. Camera.prototype._computeViewMatrix = function (force) {
  11533. if (!force && this._isSynchronizedViewMatrix()) {
  11534. return this._computedViewMatrix;
  11535. }
  11536. this._computedViewMatrix = this._getViewMatrix();
  11537. this._currentRenderId = this.getScene().getRenderId();
  11538. return this._computedViewMatrix;
  11539. };
  11540. Camera.prototype.getProjectionMatrix = function (force) {
  11541. if (!force && this._isSynchronizedProjectionMatrix()) {
  11542. return this._projectionMatrix;
  11543. }
  11544. var engine = this.getEngine();
  11545. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11546. if (this.minZ <= 0) {
  11547. this.minZ = 0.1;
  11548. }
  11549. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11550. return this._projectionMatrix;
  11551. }
  11552. var halfWidth = engine.getRenderWidth() / 2.0;
  11553. var halfHeight = engine.getRenderHeight() / 2.0;
  11554. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11555. return this._projectionMatrix;
  11556. };
  11557. Camera.prototype.dispose = function () {
  11558. // Animations
  11559. this.getScene().stopAnimation(this);
  11560. // Remove from scene
  11561. this.getScene().removeCamera(this);
  11562. while (this._rigCameras.length > 0) {
  11563. this._rigCameras.pop().dispose();
  11564. }
  11565. // Postprocesses
  11566. for (var i = 0; i < this._postProcesses.length; ++i) {
  11567. this._postProcesses[i].dispose(this);
  11568. }
  11569. _super.prototype.dispose.call(this);
  11570. };
  11571. // ---- Camera rigs section ----
  11572. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11573. while (this._rigCameras.length > 0) {
  11574. this._rigCameras.pop().dispose();
  11575. }
  11576. this.cameraRigMode = mode;
  11577. this._cameraRigParams = {};
  11578. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11579. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11580. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11581. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11582. // create the rig cameras, unless none
  11583. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11584. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11585. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11586. }
  11587. switch (this.cameraRigMode) {
  11588. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11589. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11590. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  11591. break;
  11592. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11593. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11594. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11595. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11596. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  11597. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  11598. break;
  11599. case Camera.RIG_MODE_VR:
  11600. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11601. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11602. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11603. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11604. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11605. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11606. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11607. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  11608. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11609. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11610. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11611. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11612. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11613. if (metrics.compensateDistortion) {
  11614. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  11615. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  11616. }
  11617. break;
  11618. }
  11619. this._cascadePostProcessesToRigCams();
  11620. this._update();
  11621. };
  11622. Camera.prototype._getVRProjectionMatrix = function () {
  11623. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11624. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11625. return this._projectionMatrix;
  11626. };
  11627. Camera.prototype.setCameraRigParameter = function (name, value) {
  11628. if (!this._cameraRigParams) {
  11629. this._cameraRigParams = {};
  11630. }
  11631. this._cameraRigParams[name] = value;
  11632. //provisionnally:
  11633. if (name === "interaxialDistance") {
  11634. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11635. }
  11636. };
  11637. /**
  11638. * needs to be overridden by children so sub has required properties to be copied
  11639. */
  11640. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11641. return null;
  11642. };
  11643. /**
  11644. * May need to be overridden by children
  11645. */
  11646. Camera.prototype._updateRigCameras = function () {
  11647. for (var i = 0; i < this._rigCameras.length; i++) {
  11648. this._rigCameras[i].minZ = this.minZ;
  11649. this._rigCameras[i].maxZ = this.maxZ;
  11650. this._rigCameras[i].fov = this.fov;
  11651. }
  11652. // only update viewport when ANAGLYPH
  11653. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11654. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11655. }
  11656. };
  11657. Camera.prototype._setupInputs = function () {
  11658. };
  11659. Camera.prototype.serialize = function () {
  11660. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11661. // Type
  11662. serializationObject.type = this.getTypeName();
  11663. // Parent
  11664. if (this.parent) {
  11665. serializationObject.parentId = this.parent.id;
  11666. }
  11667. if (this.inputs) {
  11668. this.inputs.serialize(serializationObject);
  11669. }
  11670. // Animations
  11671. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11672. serializationObject.ranges = this.serializeAnimationRanges();
  11673. return serializationObject;
  11674. };
  11675. Camera.prototype.getTypeName = function () {
  11676. return "Camera";
  11677. };
  11678. Camera.prototype.clone = function (name) {
  11679. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11680. };
  11681. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11682. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11683. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11684. switch (type) {
  11685. case "ArcRotateCamera":
  11686. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11687. case "DeviceOrientationCamera":
  11688. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11689. case "FollowCamera":
  11690. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11691. case "ArcFollowCamera":
  11692. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11693. case "GamepadCamera":
  11694. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11695. case "TouchCamera":
  11696. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11697. case "VirtualJoysticksCamera":
  11698. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11699. case "WebVRFreeCamera":
  11700. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11701. case "VRDeviceOrientationFreeCamera":
  11702. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11703. case "AnaglyphArcRotateCamera":
  11704. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11705. case "AnaglyphFreeCamera":
  11706. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11707. case "AnaglyphGamepadCamera":
  11708. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11709. case "AnaglyphUniversalCamera":
  11710. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11711. case "StereoscopicArcRotateCamera":
  11712. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11713. case "StereoscopicFreeCamera":
  11714. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11715. case "StereoscopicGamepadCamera":
  11716. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11717. case "StereoscopicUniversalCamera":
  11718. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11719. case "FreeCamera":
  11720. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11721. default:
  11722. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11723. }
  11724. };
  11725. Camera.Parse = function (parsedCamera, scene) {
  11726. var type = parsedCamera.type;
  11727. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11728. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11729. // Parent
  11730. if (parsedCamera.parentId) {
  11731. camera._waitingParentId = parsedCamera.parentId;
  11732. }
  11733. //If camera has an input manager, let it parse inputs settings
  11734. if (camera.inputs) {
  11735. camera.inputs.parse(parsedCamera);
  11736. camera._setupInputs();
  11737. }
  11738. // Target
  11739. if (parsedCamera.target) {
  11740. if (camera.setTarget) {
  11741. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11742. }
  11743. }
  11744. // Apply 3d rig, when found
  11745. if (parsedCamera.cameraRigMode) {
  11746. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11747. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11748. }
  11749. // Animations
  11750. if (parsedCamera.animations) {
  11751. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11752. var parsedAnimation = parsedCamera.animations[animationIndex];
  11753. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11754. }
  11755. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11756. }
  11757. if (parsedCamera.autoAnimate) {
  11758. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11759. }
  11760. return camera;
  11761. };
  11762. // Statics
  11763. Camera._PERSPECTIVE_CAMERA = 0;
  11764. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11765. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11766. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11767. Camera._RIG_MODE_NONE = 0;
  11768. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11769. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11770. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11771. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11772. Camera._RIG_MODE_VR = 20;
  11773. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11774. __decorate([
  11775. BABYLON.serializeAsVector3()
  11776. ], Camera.prototype, "position", void 0);
  11777. __decorate([
  11778. BABYLON.serializeAsVector3()
  11779. ], Camera.prototype, "upVector", void 0);
  11780. __decorate([
  11781. BABYLON.serialize()
  11782. ], Camera.prototype, "orthoLeft", void 0);
  11783. __decorate([
  11784. BABYLON.serialize()
  11785. ], Camera.prototype, "orthoRight", void 0);
  11786. __decorate([
  11787. BABYLON.serialize()
  11788. ], Camera.prototype, "orthoBottom", void 0);
  11789. __decorate([
  11790. BABYLON.serialize()
  11791. ], Camera.prototype, "orthoTop", void 0);
  11792. __decorate([
  11793. BABYLON.serialize()
  11794. ], Camera.prototype, "fov", void 0);
  11795. __decorate([
  11796. BABYLON.serialize()
  11797. ], Camera.prototype, "minZ", void 0);
  11798. __decorate([
  11799. BABYLON.serialize()
  11800. ], Camera.prototype, "maxZ", void 0);
  11801. __decorate([
  11802. BABYLON.serialize()
  11803. ], Camera.prototype, "inertia", void 0);
  11804. __decorate([
  11805. BABYLON.serialize()
  11806. ], Camera.prototype, "mode", void 0);
  11807. __decorate([
  11808. BABYLON.serialize()
  11809. ], Camera.prototype, "layerMask", void 0);
  11810. __decorate([
  11811. BABYLON.serialize()
  11812. ], Camera.prototype, "fovMode", void 0);
  11813. __decorate([
  11814. BABYLON.serialize()
  11815. ], Camera.prototype, "cameraRigMode", void 0);
  11816. __decorate([
  11817. BABYLON.serialize()
  11818. ], Camera.prototype, "interaxialDistance", void 0);
  11819. __decorate([
  11820. BABYLON.serialize()
  11821. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11822. return Camera;
  11823. })(BABYLON.Node);
  11824. BABYLON.Camera = Camera;
  11825. })(BABYLON || (BABYLON = {}));
  11826. var BABYLON;
  11827. (function (BABYLON) {
  11828. BABYLON.CameraInputTypes = {};
  11829. var CameraInputsManager = (function () {
  11830. function CameraInputsManager(camera) {
  11831. this.attached = {};
  11832. this.camera = camera;
  11833. this.checkInputs = function () { };
  11834. }
  11835. CameraInputsManager.prototype.add = function (input) {
  11836. var type = input.getSimpleName();
  11837. if (this.attached[type]) {
  11838. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11839. return;
  11840. }
  11841. this.attached[type] = input;
  11842. input.camera = this.camera;
  11843. //for checkInputs, we are dynamically creating a function
  11844. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11845. if (input.checkInputs) {
  11846. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11847. }
  11848. if (this.attachedElement) {
  11849. input.attachControl(this.attachedElement);
  11850. }
  11851. };
  11852. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11853. for (var cam in this.attached) {
  11854. var input = this.attached[cam];
  11855. if (input === inputToRemove) {
  11856. input.detachControl(this.attachedElement);
  11857. delete this.attached[cam];
  11858. this.rebuildInputCheck();
  11859. }
  11860. }
  11861. };
  11862. CameraInputsManager.prototype.removeByType = function (inputType) {
  11863. for (var cam in this.attached) {
  11864. var input = this.attached[cam];
  11865. if (input.getTypeName() === inputType) {
  11866. input.detachControl(this.attachedElement);
  11867. delete this.attached[cam];
  11868. this.rebuildInputCheck();
  11869. }
  11870. }
  11871. };
  11872. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11873. var current = this.checkInputs;
  11874. return function () {
  11875. current();
  11876. fn();
  11877. };
  11878. };
  11879. CameraInputsManager.prototype.attachInput = function (input) {
  11880. input.attachControl(this.attachedElement, this.noPreventDefault);
  11881. };
  11882. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11883. if (this.attachedElement) {
  11884. return;
  11885. }
  11886. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11887. this.attachedElement = element;
  11888. this.noPreventDefault = noPreventDefault;
  11889. for (var cam in this.attached) {
  11890. var input = this.attached[cam];
  11891. this.attached[cam].attachControl(element, noPreventDefault);
  11892. }
  11893. };
  11894. CameraInputsManager.prototype.detachElement = function (element) {
  11895. if (this.attachedElement !== element) {
  11896. return;
  11897. }
  11898. for (var cam in this.attached) {
  11899. var input = this.attached[cam];
  11900. this.attached[cam].detachControl(element);
  11901. }
  11902. this.attachedElement = null;
  11903. };
  11904. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11905. this.checkInputs = function () { };
  11906. for (var cam in this.attached) {
  11907. var input = this.attached[cam];
  11908. if (input.checkInputs) {
  11909. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11910. }
  11911. }
  11912. };
  11913. CameraInputsManager.prototype.clear = function () {
  11914. if (this.attachedElement) {
  11915. this.detachElement(this.attachedElement);
  11916. }
  11917. this.attached = {};
  11918. this.attachedElement = null;
  11919. this.checkInputs = function () { };
  11920. };
  11921. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11922. var inputs = {};
  11923. for (var cam in this.attached) {
  11924. var input = this.attached[cam];
  11925. var res = BABYLON.SerializationHelper.Serialize(input);
  11926. inputs[input.getTypeName()] = res;
  11927. }
  11928. serializedCamera.inputsmgr = inputs;
  11929. };
  11930. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11931. var parsedInputs = parsedCamera.inputsmgr;
  11932. if (parsedInputs) {
  11933. this.clear();
  11934. for (var n in parsedInputs) {
  11935. var construct = BABYLON.CameraInputTypes[n];
  11936. if (construct) {
  11937. var parsedinput = parsedInputs[n];
  11938. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11939. this.add(input);
  11940. }
  11941. }
  11942. }
  11943. else {
  11944. //2016-03-08 this part is for managing backward compatibility
  11945. for (var n in this.attached) {
  11946. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11947. if (construct) {
  11948. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11949. this.remove(this.attached[n]);
  11950. this.add(input);
  11951. }
  11952. }
  11953. }
  11954. };
  11955. return CameraInputsManager;
  11956. })();
  11957. BABYLON.CameraInputsManager = CameraInputsManager;
  11958. })(BABYLON || (BABYLON = {}));
  11959. var BABYLON;
  11960. (function (BABYLON) {
  11961. var FreeCameraMouseInput = (function () {
  11962. function FreeCameraMouseInput(touchEnabled) {
  11963. if (touchEnabled === void 0) { touchEnabled = true; }
  11964. this.touchEnabled = touchEnabled;
  11965. this.angularSensibility = 2000.0;
  11966. }
  11967. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11968. var _this = this;
  11969. if (!this._pointerInput) {
  11970. var camera = this.camera;
  11971. var engine = this.camera.getEngine();
  11972. this._pointerInput = function (p, s) {
  11973. var evt = p.event;
  11974. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11975. return;
  11976. }
  11977. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11978. try {
  11979. evt.srcElement.setPointerCapture(evt.pointerId);
  11980. }
  11981. catch (e) {
  11982. }
  11983. _this.previousPosition = {
  11984. x: evt.clientX,
  11985. y: evt.clientY
  11986. };
  11987. if (!noPreventDefault) {
  11988. evt.preventDefault();
  11989. }
  11990. }
  11991. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11992. try {
  11993. evt.srcElement.releasePointerCapture(evt.pointerId);
  11994. }
  11995. catch (e) {
  11996. }
  11997. _this.previousPosition = null;
  11998. if (!noPreventDefault) {
  11999. evt.preventDefault();
  12000. }
  12001. }
  12002. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12003. if (!_this.previousPosition && !engine.isPointerLock) {
  12004. return;
  12005. }
  12006. var offsetX;
  12007. var offsetY;
  12008. if (!engine.isPointerLock) {
  12009. offsetX = evt.clientX - _this.previousPosition.x;
  12010. offsetY = evt.clientY - _this.previousPosition.y;
  12011. }
  12012. else {
  12013. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12014. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12015. }
  12016. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12017. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12018. _this.previousPosition = {
  12019. x: evt.clientX,
  12020. y: evt.clientY
  12021. };
  12022. if (!noPreventDefault) {
  12023. evt.preventDefault();
  12024. }
  12025. }
  12026. };
  12027. }
  12028. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12029. };
  12030. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12031. if (this._observer && element) {
  12032. this.camera.getScene().onPointerObservable.remove(this._observer);
  12033. this._observer = null;
  12034. this.previousPosition = null;
  12035. }
  12036. };
  12037. FreeCameraMouseInput.prototype.getTypeName = function () {
  12038. return "FreeCameraMouseInput";
  12039. };
  12040. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12041. return "mouse";
  12042. };
  12043. __decorate([
  12044. BABYLON.serialize()
  12045. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12046. return FreeCameraMouseInput;
  12047. })();
  12048. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12049. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12050. })(BABYLON || (BABYLON = {}));
  12051. var BABYLON;
  12052. (function (BABYLON) {
  12053. var FreeCameraKeyboardMoveInput = (function () {
  12054. function FreeCameraKeyboardMoveInput() {
  12055. this._keys = [];
  12056. this.keysUp = [38];
  12057. this.keysDown = [40];
  12058. this.keysLeft = [37];
  12059. this.keysRight = [39];
  12060. }
  12061. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12062. var _this = this;
  12063. if (!this._onKeyDown) {
  12064. this._onKeyDown = function (evt) {
  12065. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12066. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12067. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12068. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12069. var index = _this._keys.indexOf(evt.keyCode);
  12070. if (index === -1) {
  12071. _this._keys.push(evt.keyCode);
  12072. }
  12073. if (!noPreventDefault) {
  12074. evt.preventDefault();
  12075. }
  12076. }
  12077. };
  12078. this._onKeyUp = function (evt) {
  12079. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12080. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12081. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12082. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12083. var index = _this._keys.indexOf(evt.keyCode);
  12084. if (index >= 0) {
  12085. _this._keys.splice(index, 1);
  12086. }
  12087. if (!noPreventDefault) {
  12088. evt.preventDefault();
  12089. }
  12090. }
  12091. };
  12092. BABYLON.Tools.RegisterTopRootEvents([
  12093. { name: "keydown", handler: this._onKeyDown },
  12094. { name: "keyup", handler: this._onKeyUp },
  12095. { name: "blur", handler: this._onLostFocus }
  12096. ]);
  12097. }
  12098. };
  12099. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12100. if (this._onKeyDown) {
  12101. BABYLON.Tools.UnregisterTopRootEvents([
  12102. { name: "keydown", handler: this._onKeyDown },
  12103. { name: "keyup", handler: this._onKeyUp },
  12104. { name: "blur", handler: this._onLostFocus }
  12105. ]);
  12106. this._keys = [];
  12107. this._onKeyDown = null;
  12108. this._onKeyUp = null;
  12109. }
  12110. };
  12111. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12112. if (this._onKeyDown) {
  12113. var camera = this.camera;
  12114. // Keyboard
  12115. for (var index = 0; index < this._keys.length; index++) {
  12116. var keyCode = this._keys[index];
  12117. var speed = camera._computeLocalCameraSpeed();
  12118. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12119. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12120. }
  12121. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12122. camera._localDirection.copyFromFloats(0, 0, speed);
  12123. }
  12124. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12125. camera._localDirection.copyFromFloats(speed, 0, 0);
  12126. }
  12127. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12128. camera._localDirection.copyFromFloats(0, 0, -speed);
  12129. }
  12130. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12131. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12132. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12133. }
  12134. }
  12135. };
  12136. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12137. return "FreeCameraKeyboardMoveInput";
  12138. };
  12139. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12140. this._keys = [];
  12141. };
  12142. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12143. return "keyboard";
  12144. };
  12145. __decorate([
  12146. BABYLON.serialize()
  12147. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12148. __decorate([
  12149. BABYLON.serialize()
  12150. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12151. __decorate([
  12152. BABYLON.serialize()
  12153. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12154. __decorate([
  12155. BABYLON.serialize()
  12156. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12157. return FreeCameraKeyboardMoveInput;
  12158. })();
  12159. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12160. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12161. })(BABYLON || (BABYLON = {}));
  12162. var BABYLON;
  12163. (function (BABYLON) {
  12164. var FreeCameraTouchInput = (function () {
  12165. function FreeCameraTouchInput() {
  12166. this._offsetX = null;
  12167. this._offsetY = null;
  12168. this._pointerCount = 0;
  12169. this._pointerPressed = [];
  12170. this.touchAngularSensibility = 200000.0;
  12171. this.touchMoveSensibility = 250.0;
  12172. }
  12173. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12174. var _this = this;
  12175. var previousPosition;
  12176. if (this._pointerInput === undefined) {
  12177. this._onLostFocus = function (evt) {
  12178. _this._offsetX = null;
  12179. _this._offsetY = null;
  12180. };
  12181. this._pointerInput = function (p, s) {
  12182. var evt = p.event;
  12183. if (evt.pointerType === "mouse") {
  12184. return;
  12185. }
  12186. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12187. if (!noPreventDefault) {
  12188. evt.preventDefault();
  12189. }
  12190. _this._pointerPressed.push(evt.pointerId);
  12191. if (_this._pointerPressed.length !== 1) {
  12192. return;
  12193. }
  12194. previousPosition = {
  12195. x: evt.clientX,
  12196. y: evt.clientY
  12197. };
  12198. }
  12199. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12200. if (!noPreventDefault) {
  12201. evt.preventDefault();
  12202. }
  12203. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12204. if (index === -1) {
  12205. return;
  12206. }
  12207. _this._pointerPressed.splice(index, 1);
  12208. if (index != 0) {
  12209. return;
  12210. }
  12211. previousPosition = null;
  12212. _this._offsetX = null;
  12213. _this._offsetY = null;
  12214. }
  12215. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12216. if (!noPreventDefault) {
  12217. evt.preventDefault();
  12218. }
  12219. if (!previousPosition) {
  12220. return;
  12221. }
  12222. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12223. if (index != 0) {
  12224. return;
  12225. }
  12226. _this._offsetX = evt.clientX - previousPosition.x;
  12227. _this._offsetY = -(evt.clientY - previousPosition.y);
  12228. }
  12229. };
  12230. }
  12231. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12232. element.addEventListener("blur", this._onLostFocus);
  12233. };
  12234. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12235. if (this._pointerInput && element) {
  12236. this.camera.getScene().onPointerObservable.remove(this._observer);
  12237. this._observer = null;
  12238. element.removeEventListener("blur", this._onLostFocus);
  12239. this._onLostFocus = null;
  12240. this._pointerPressed = [];
  12241. this._offsetX = null;
  12242. this._offsetY = null;
  12243. this._pointerCount = 0;
  12244. }
  12245. };
  12246. FreeCameraTouchInput.prototype.checkInputs = function () {
  12247. if (this._offsetX) {
  12248. var camera = this.camera;
  12249. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12250. if (this._pointerPressed.length > 1) {
  12251. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12252. }
  12253. else {
  12254. var speed = camera._computeLocalCameraSpeed();
  12255. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12256. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12257. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12258. }
  12259. }
  12260. };
  12261. FreeCameraTouchInput.prototype.getTypeName = function () {
  12262. return "FreeCameraTouchInput";
  12263. };
  12264. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12265. return "touch";
  12266. };
  12267. __decorate([
  12268. BABYLON.serialize()
  12269. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12270. __decorate([
  12271. BABYLON.serialize()
  12272. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12273. return FreeCameraTouchInput;
  12274. })();
  12275. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12276. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12277. })(BABYLON || (BABYLON = {}));
  12278. var BABYLON;
  12279. (function (BABYLON) {
  12280. var FreeCameraDeviceOrientationInput = (function () {
  12281. function FreeCameraDeviceOrientationInput() {
  12282. var _this = this;
  12283. this._screenOrientationAngle = 0;
  12284. this._screenQuaternion = new BABYLON.Quaternion();
  12285. this._alpha = 0;
  12286. this._beta = 0;
  12287. this._gamma = 0;
  12288. this._orientationChanged = function () {
  12289. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12290. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12291. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12292. };
  12293. this._deviceOrientation = function (evt) {
  12294. _this._alpha = evt.alpha;
  12295. _this._beta = evt.beta;
  12296. _this._gamma = evt.gamma;
  12297. };
  12298. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12299. this._orientationChanged();
  12300. }
  12301. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12302. get: function () {
  12303. return this._camera;
  12304. },
  12305. set: function (camera) {
  12306. this._camera = camera;
  12307. if (!this._camera.rotationQuaternion)
  12308. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12314. window.addEventListener("orientationchange", this._orientationChanged);
  12315. window.addEventListener("deviceorientation", this._deviceOrientation);
  12316. };
  12317. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12318. window.removeEventListener("orientationchange", this._orientationChanged);
  12319. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12320. };
  12321. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12322. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12323. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12324. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12325. //Mirror on XY Plane
  12326. this._camera.rotationQuaternion.z *= -1;
  12327. this._camera.rotationQuaternion.w *= -1;
  12328. };
  12329. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12330. return "FreeCameraDeviceOrientationInput";
  12331. };
  12332. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12333. return "deviceOrientation";
  12334. };
  12335. return FreeCameraDeviceOrientationInput;
  12336. })();
  12337. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12338. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12339. })(BABYLON || (BABYLON = {}));
  12340. var BABYLON;
  12341. (function (BABYLON) {
  12342. var FreeCameraVRDeviceOrientationInput = (function () {
  12343. function FreeCameraVRDeviceOrientationInput() {
  12344. this.alphaCorrection = 1;
  12345. this.betaCorrection = 1;
  12346. this.gammaCorrection = 1;
  12347. this._alpha = 0;
  12348. this._beta = 0;
  12349. this._gamma = 0;
  12350. this._dirty = false;
  12351. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12352. }
  12353. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12354. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12355. };
  12356. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12357. var camera = this.camera;
  12358. this._alpha = evt.alpha;
  12359. this._beta = evt.beta;
  12360. this._gamma = evt.gamma;
  12361. this._dirty = true;
  12362. };
  12363. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12364. if (this._dirty) {
  12365. this._dirty = false;
  12366. var rotationX = this._gamma;
  12367. if (rotationX < 0) {
  12368. rotationX = 90 + rotationX;
  12369. }
  12370. else {
  12371. // Incline it in the correct angle.
  12372. rotationX = 270 - rotationX;
  12373. }
  12374. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12375. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12376. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12377. }
  12378. };
  12379. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12380. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12381. };
  12382. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12383. return "FreeCameraVRDeviceOrientationInput";
  12384. };
  12385. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12386. return "VRDeviceOrientation";
  12387. };
  12388. return FreeCameraVRDeviceOrientationInput;
  12389. })();
  12390. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12391. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12392. })(BABYLON || (BABYLON = {}));
  12393. var BABYLON;
  12394. (function (BABYLON) {
  12395. var FreeCameraGamepadInput = (function () {
  12396. function FreeCameraGamepadInput() {
  12397. this.gamepadAngularSensibility = 200;
  12398. this.gamepadMoveSensibility = 40;
  12399. }
  12400. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12401. var _this = this;
  12402. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12403. };
  12404. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12405. if (this._gamepads) {
  12406. this._gamepads.dispose();
  12407. }
  12408. this.gamepad = null;
  12409. };
  12410. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12411. if (this.gamepad) {
  12412. var camera = this.camera;
  12413. var LSValues = this.gamepad.leftStick;
  12414. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12415. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12416. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12417. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12418. var RSValues = this.gamepad.rightStick;
  12419. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12420. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12421. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12422. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12423. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12424. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12425. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12426. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12427. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12428. }
  12429. };
  12430. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12431. // Only the first gamepad can control the camera
  12432. if (gamepad.index === 0) {
  12433. this.gamepad = gamepad;
  12434. }
  12435. };
  12436. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12437. return "FreeCameraGamepadInput";
  12438. };
  12439. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12440. return "gamepad";
  12441. };
  12442. __decorate([
  12443. BABYLON.serialize()
  12444. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12445. __decorate([
  12446. BABYLON.serialize()
  12447. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12448. return FreeCameraGamepadInput;
  12449. })();
  12450. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12451. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12452. })(BABYLON || (BABYLON = {}));
  12453. var BABYLON;
  12454. (function (BABYLON) {
  12455. var ArcRotateCameraKeyboardMoveInput = (function () {
  12456. function ArcRotateCameraKeyboardMoveInput() {
  12457. this._keys = [];
  12458. this.keysUp = [38];
  12459. this.keysDown = [40];
  12460. this.keysLeft = [37];
  12461. this.keysRight = [39];
  12462. }
  12463. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12464. var _this = this;
  12465. this._onKeyDown = function (evt) {
  12466. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12467. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12468. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12469. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12470. var index = _this._keys.indexOf(evt.keyCode);
  12471. if (index === -1) {
  12472. _this._keys.push(evt.keyCode);
  12473. }
  12474. if (evt.preventDefault) {
  12475. if (!noPreventDefault) {
  12476. evt.preventDefault();
  12477. }
  12478. }
  12479. }
  12480. };
  12481. this._onKeyUp = function (evt) {
  12482. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12483. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12484. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12485. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12486. var index = _this._keys.indexOf(evt.keyCode);
  12487. if (index >= 0) {
  12488. _this._keys.splice(index, 1);
  12489. }
  12490. if (evt.preventDefault) {
  12491. if (!noPreventDefault) {
  12492. evt.preventDefault();
  12493. }
  12494. }
  12495. }
  12496. };
  12497. this._onLostFocus = function () {
  12498. _this._keys = [];
  12499. };
  12500. BABYLON.Tools.RegisterTopRootEvents([
  12501. { name: "keydown", handler: this._onKeyDown },
  12502. { name: "keyup", handler: this._onKeyUp },
  12503. { name: "blur", handler: this._onLostFocus }
  12504. ]);
  12505. };
  12506. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12507. BABYLON.Tools.UnregisterTopRootEvents([
  12508. { name: "keydown", handler: this._onKeyDown },
  12509. { name: "keyup", handler: this._onKeyUp },
  12510. { name: "blur", handler: this._onLostFocus }
  12511. ]);
  12512. this._keys = [];
  12513. this._onKeyDown = null;
  12514. this._onKeyUp = null;
  12515. this._onLostFocus = null;
  12516. };
  12517. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12518. if (this._onKeyDown) {
  12519. var camera = this.camera;
  12520. for (var index = 0; index < this._keys.length; index++) {
  12521. var keyCode = this._keys[index];
  12522. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12523. camera.inertialAlphaOffset -= 0.01;
  12524. }
  12525. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12526. camera.inertialBetaOffset -= 0.01;
  12527. }
  12528. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12529. camera.inertialAlphaOffset += 0.01;
  12530. }
  12531. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12532. camera.inertialBetaOffset += 0.01;
  12533. }
  12534. }
  12535. }
  12536. };
  12537. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12538. return "ArcRotateCameraKeyboardMoveInput";
  12539. };
  12540. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12541. return "keyboard";
  12542. };
  12543. __decorate([
  12544. BABYLON.serialize()
  12545. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12546. __decorate([
  12547. BABYLON.serialize()
  12548. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12549. __decorate([
  12550. BABYLON.serialize()
  12551. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12552. __decorate([
  12553. BABYLON.serialize()
  12554. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12555. return ArcRotateCameraKeyboardMoveInput;
  12556. })();
  12557. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12558. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12559. })(BABYLON || (BABYLON = {}));
  12560. var BABYLON;
  12561. (function (BABYLON) {
  12562. var ArcRotateCameraMouseWheelInput = (function () {
  12563. function ArcRotateCameraMouseWheelInput() {
  12564. this.wheelPrecision = 3.0;
  12565. }
  12566. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12567. var _this = this;
  12568. this._wheel = function (p, s) {
  12569. //sanity check - this should be a PointerWheel event.
  12570. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12571. return;
  12572. var event = p.event;
  12573. var delta = 0;
  12574. if (event.wheelDelta) {
  12575. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12576. }
  12577. else if (event.detail) {
  12578. delta = -event.detail / _this.wheelPrecision;
  12579. }
  12580. if (delta)
  12581. _this.camera.inertialRadiusOffset += delta;
  12582. if (event.preventDefault) {
  12583. if (!noPreventDefault) {
  12584. event.preventDefault();
  12585. }
  12586. }
  12587. };
  12588. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12589. };
  12590. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12591. if (this._observer && element) {
  12592. this.camera.getScene().onPointerObservable.remove(this._observer);
  12593. this._observer = null;
  12594. this._wheel = null;
  12595. }
  12596. };
  12597. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12598. return "ArcRotateCameraMouseWheelInput";
  12599. };
  12600. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12601. return "mousewheel";
  12602. };
  12603. __decorate([
  12604. BABYLON.serialize()
  12605. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12606. return ArcRotateCameraMouseWheelInput;
  12607. })();
  12608. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12609. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12610. })(BABYLON || (BABYLON = {}));
  12611. var BABYLON;
  12612. (function (BABYLON) {
  12613. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12614. var ArcRotateCameraPointersInput = (function () {
  12615. function ArcRotateCameraPointersInput() {
  12616. this.angularSensibilityX = 1000.0;
  12617. this.angularSensibilityY = 1000.0;
  12618. this.pinchPrecision = 6.0;
  12619. this.panningSensibility = 50.0;
  12620. this._isRightClick = false;
  12621. this._isCtrlPushed = false;
  12622. this.pinchInwards = true;
  12623. }
  12624. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12625. var _this = this;
  12626. var engine = this.camera.getEngine();
  12627. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12628. var pointA, pointB;
  12629. var previousPinchDistance = 0;
  12630. this._pointerInput = function (p, s) {
  12631. var evt = p.event;
  12632. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12633. try {
  12634. evt.srcElement.setPointerCapture(evt.pointerId);
  12635. }
  12636. catch (e) {
  12637. }
  12638. // Manage panning with right click
  12639. _this._isRightClick = evt.button === 2;
  12640. // manage pointers
  12641. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12642. if (pointA === undefined) {
  12643. pointA = cacheSoloPointer;
  12644. }
  12645. else if (pointB === undefined) {
  12646. pointB = cacheSoloPointer;
  12647. }
  12648. if (!noPreventDefault) {
  12649. evt.preventDefault();
  12650. }
  12651. }
  12652. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12653. try {
  12654. evt.srcElement.releasePointerCapture(evt.pointerId);
  12655. }
  12656. catch (e) {
  12657. }
  12658. cacheSoloPointer = null;
  12659. previousPinchDistance = 0;
  12660. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12661. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12662. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12663. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12664. pointA = pointB = undefined;
  12665. if (!noPreventDefault) {
  12666. evt.preventDefault();
  12667. }
  12668. }
  12669. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12670. if (!noPreventDefault) {
  12671. evt.preventDefault();
  12672. }
  12673. // One button down
  12674. if (pointA && pointB === undefined) {
  12675. if (_this.panningSensibility !== 0 &&
  12676. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12677. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12678. _this.camera
  12679. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12680. _this.camera
  12681. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12682. }
  12683. else {
  12684. var offsetX = evt.clientX - cacheSoloPointer.x;
  12685. var offsetY = evt.clientY - cacheSoloPointer.y;
  12686. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12687. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12688. }
  12689. cacheSoloPointer.x = evt.clientX;
  12690. cacheSoloPointer.y = evt.clientY;
  12691. }
  12692. else if (pointA && pointB) {
  12693. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12694. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12695. ed.x = evt.clientX;
  12696. ed.y = evt.clientY;
  12697. var direction = _this.pinchInwards ? 1 : -1;
  12698. var distX = pointA.x - pointB.x;
  12699. var distY = pointA.y - pointB.y;
  12700. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12701. if (previousPinchDistance === 0) {
  12702. previousPinchDistance = pinchSquaredDistance;
  12703. return;
  12704. }
  12705. if (pinchSquaredDistance !== previousPinchDistance) {
  12706. _this.camera
  12707. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12708. (_this.pinchPrecision *
  12709. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12710. direction);
  12711. previousPinchDistance = pinchSquaredDistance;
  12712. }
  12713. }
  12714. }
  12715. };
  12716. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12717. this._onContextMenu = function (evt) {
  12718. evt.preventDefault();
  12719. };
  12720. if (!this.camera._useCtrlForPanning) {
  12721. element.addEventListener("contextmenu", this._onContextMenu, false);
  12722. }
  12723. this._onLostFocus = function () {
  12724. //this._keys = [];
  12725. pointA = pointB = undefined;
  12726. previousPinchDistance = 0;
  12727. cacheSoloPointer = null;
  12728. };
  12729. this._onKeyDown = function (evt) {
  12730. _this._isCtrlPushed = evt.ctrlKey;
  12731. };
  12732. this._onKeyUp = function (evt) {
  12733. _this._isCtrlPushed = evt.ctrlKey;
  12734. };
  12735. this._onMouseMove = function (evt) {
  12736. if (!engine.isPointerLock) {
  12737. return;
  12738. }
  12739. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12740. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12741. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12742. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12743. if (!noPreventDefault) {
  12744. evt.preventDefault();
  12745. }
  12746. };
  12747. this._onGestureStart = function (e) {
  12748. if (window.MSGesture === undefined) {
  12749. return;
  12750. }
  12751. if (!_this._MSGestureHandler) {
  12752. _this._MSGestureHandler = new MSGesture();
  12753. _this._MSGestureHandler.target = element;
  12754. }
  12755. _this._MSGestureHandler.addPointer(e.pointerId);
  12756. };
  12757. this._onGesture = function (e) {
  12758. _this.camera.radius *= e.scale;
  12759. if (e.preventDefault) {
  12760. if (!noPreventDefault) {
  12761. e.stopPropagation();
  12762. e.preventDefault();
  12763. }
  12764. }
  12765. };
  12766. element.addEventListener("mousemove", this._onMouseMove, false);
  12767. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12768. element.addEventListener("MSGestureChange", this._onGesture, false);
  12769. BABYLON.Tools.RegisterTopRootEvents([
  12770. { name: "keydown", handler: this._onKeyDown },
  12771. { name: "keyup", handler: this._onKeyUp },
  12772. { name: "blur", handler: this._onLostFocus }
  12773. ]);
  12774. };
  12775. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12776. if (element && this._observer) {
  12777. this.camera.getScene().onPointerObservable.remove(this._observer);
  12778. this._observer = null;
  12779. element.removeEventListener("contextmenu", this._onContextMenu);
  12780. element.removeEventListener("mousemove", this._onMouseMove);
  12781. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12782. element.removeEventListener("MSGestureChange", this._onGesture);
  12783. this._isRightClick = false;
  12784. this._isCtrlPushed = false;
  12785. this.pinchInwards = true;
  12786. this._onKeyDown = null;
  12787. this._onKeyUp = null;
  12788. this._onMouseMove = null;
  12789. this._onGestureStart = null;
  12790. this._onGesture = null;
  12791. this._MSGestureHandler = null;
  12792. this._onLostFocus = null;
  12793. this._onContextMenu = null;
  12794. }
  12795. BABYLON.Tools.UnregisterTopRootEvents([
  12796. { name: "keydown", handler: this._onKeyDown },
  12797. { name: "keyup", handler: this._onKeyUp },
  12798. { name: "blur", handler: this._onLostFocus }
  12799. ]);
  12800. };
  12801. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12802. return "ArcRotateCameraPointersInput";
  12803. };
  12804. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12805. return "pointers";
  12806. };
  12807. __decorate([
  12808. BABYLON.serialize()
  12809. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12810. __decorate([
  12811. BABYLON.serialize()
  12812. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12813. __decorate([
  12814. BABYLON.serialize()
  12815. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12816. __decorate([
  12817. BABYLON.serialize()
  12818. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12819. return ArcRotateCameraPointersInput;
  12820. })();
  12821. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12822. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12823. })(BABYLON || (BABYLON = {}));
  12824. var BABYLON;
  12825. (function (BABYLON) {
  12826. var ArcRotateCameraGamepadInput = (function () {
  12827. function ArcRotateCameraGamepadInput() {
  12828. this.gamepadRotationSensibility = 80;
  12829. this.gamepadMoveSensibility = 40;
  12830. }
  12831. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12832. var _this = this;
  12833. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12834. };
  12835. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12836. if (this._gamepads) {
  12837. this._gamepads.dispose();
  12838. }
  12839. this.gamepad = null;
  12840. };
  12841. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12842. if (this.gamepad) {
  12843. var camera = this.camera;
  12844. var RSValues = this.gamepad.rightStick;
  12845. if (RSValues.x != 0) {
  12846. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12847. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12848. camera.inertialAlphaOffset += normalizedRX;
  12849. }
  12850. }
  12851. if (RSValues.y != 0) {
  12852. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12853. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12854. camera.inertialBetaOffset += normalizedRY;
  12855. }
  12856. }
  12857. var LSValues = this.gamepad.leftStick;
  12858. if (LSValues.y != 0) {
  12859. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12860. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12861. this.camera.inertialRadiusOffset -= normalizedLY;
  12862. }
  12863. }
  12864. }
  12865. };
  12866. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12867. // Only the first gamepad can control the camera
  12868. if (gamepad.index === 0) {
  12869. this.gamepad = gamepad;
  12870. }
  12871. };
  12872. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12873. return "ArcRotateCameraGamepadInput";
  12874. };
  12875. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12876. return "gamepad";
  12877. };
  12878. __decorate([
  12879. BABYLON.serialize()
  12880. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12881. __decorate([
  12882. BABYLON.serialize()
  12883. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12884. return ArcRotateCameraGamepadInput;
  12885. })();
  12886. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12887. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12888. })(BABYLON || (BABYLON = {}));
  12889. var BABYLON;
  12890. (function (BABYLON) {
  12891. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12892. function ArcRotateCameraVRDeviceOrientationInput() {
  12893. this.alphaCorrection = 1;
  12894. this.betaCorrection = 1;
  12895. this.gammaCorrection = 1;
  12896. this._alpha = 0;
  12897. this._beta = 0;
  12898. this._gamma = 0;
  12899. this._dirty = false;
  12900. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12901. }
  12902. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12903. this.camera.attachControl(element, noPreventDefault);
  12904. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12905. };
  12906. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12907. var camera = this.camera;
  12908. this._alpha = +evt.alpha | 0;
  12909. this._beta = +evt.beta | 0;
  12910. this._gamma = +evt.gamma | 0;
  12911. this._dirty = true;
  12912. };
  12913. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12914. if (this._dirty) {
  12915. this._dirty = false;
  12916. if (this._gamma < 0) {
  12917. this._gamma = 180 + this._gamma;
  12918. }
  12919. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12920. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12921. }
  12922. };
  12923. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12924. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12925. };
  12926. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12927. return "ArcRotateCameraVRDeviceOrientationInput";
  12928. };
  12929. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12930. return "VRDeviceOrientation";
  12931. };
  12932. return ArcRotateCameraVRDeviceOrientationInput;
  12933. })();
  12934. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12935. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12936. })(BABYLON || (BABYLON = {}));
  12937. var BABYLON;
  12938. (function (BABYLON) {
  12939. var TargetCamera = (function (_super) {
  12940. __extends(TargetCamera, _super);
  12941. function TargetCamera(name, position, scene) {
  12942. _super.call(this, name, position, scene);
  12943. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12944. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12945. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12946. this.speed = 2.0;
  12947. this.noRotationConstraint = false;
  12948. this.lockedTarget = null;
  12949. this._currentTarget = BABYLON.Vector3.Zero();
  12950. this._viewMatrix = BABYLON.Matrix.Zero();
  12951. this._camMatrix = BABYLON.Matrix.Zero();
  12952. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12953. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12954. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12955. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  12956. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12957. this._lookAtTemp = BABYLON.Matrix.Zero();
  12958. this._tempMatrix = BABYLON.Matrix.Zero();
  12959. }
  12960. TargetCamera.prototype.getFrontPosition = function (distance) {
  12961. var direction = this.getTarget().subtract(this.position);
  12962. direction.normalize();
  12963. direction.scaleInPlace(distance);
  12964. return this.globalPosition.add(direction);
  12965. };
  12966. TargetCamera.prototype._getLockedTargetPosition = function () {
  12967. if (!this.lockedTarget) {
  12968. return null;
  12969. }
  12970. return this.lockedTarget.position || this.lockedTarget;
  12971. };
  12972. // Cache
  12973. TargetCamera.prototype._initCache = function () {
  12974. _super.prototype._initCache.call(this);
  12975. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12976. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12977. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12978. };
  12979. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12980. if (!ignoreParentClass) {
  12981. _super.prototype._updateCache.call(this);
  12982. }
  12983. var lockedTargetPosition = this._getLockedTargetPosition();
  12984. if (!lockedTargetPosition) {
  12985. this._cache.lockedTarget = null;
  12986. }
  12987. else {
  12988. if (!this._cache.lockedTarget) {
  12989. this._cache.lockedTarget = lockedTargetPosition.clone();
  12990. }
  12991. else {
  12992. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12993. }
  12994. }
  12995. this._cache.rotation.copyFrom(this.rotation);
  12996. if (this.rotationQuaternion)
  12997. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12998. };
  12999. // Synchronized
  13000. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13001. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13002. return false;
  13003. }
  13004. var lockedTargetPosition = this._getLockedTargetPosition();
  13005. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13006. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13007. };
  13008. // Methods
  13009. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13010. var engine = this.getEngine();
  13011. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  13012. };
  13013. // Target
  13014. TargetCamera.prototype.setTarget = function (target) {
  13015. this.upVector.normalize();
  13016. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13017. this._camMatrix.invert();
  13018. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13019. var vDir = target.subtract(this.position);
  13020. if (vDir.x >= 0.0) {
  13021. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13022. }
  13023. else {
  13024. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13025. }
  13026. this.rotation.z = 0;
  13027. if (isNaN(this.rotation.x)) {
  13028. this.rotation.x = 0;
  13029. }
  13030. if (isNaN(this.rotation.y)) {
  13031. this.rotation.y = 0;
  13032. }
  13033. if (isNaN(this.rotation.z)) {
  13034. this.rotation.z = 0;
  13035. }
  13036. if (this.rotationQuaternion) {
  13037. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13038. }
  13039. };
  13040. TargetCamera.prototype.getTarget = function () {
  13041. return this._currentTarget;
  13042. };
  13043. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13044. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13045. };
  13046. TargetCamera.prototype._updatePosition = function () {
  13047. this.position.addInPlace(this.cameraDirection);
  13048. };
  13049. TargetCamera.prototype._checkInputs = function () {
  13050. var needToMove = this._decideIfNeedsToMove();
  13051. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13052. // Move
  13053. if (needToMove) {
  13054. this._updatePosition();
  13055. }
  13056. // Rotate
  13057. if (needToRotate) {
  13058. this.rotation.x += this.cameraRotation.x;
  13059. this.rotation.y += this.cameraRotation.y;
  13060. if (!this.noRotationConstraint) {
  13061. var limit = (Math.PI / 2) * 0.95;
  13062. if (this.rotation.x > limit)
  13063. this.rotation.x = limit;
  13064. if (this.rotation.x < -limit)
  13065. this.rotation.x = -limit;
  13066. }
  13067. }
  13068. // Inertia
  13069. if (needToMove) {
  13070. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13071. this.cameraDirection.x = 0;
  13072. }
  13073. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13074. this.cameraDirection.y = 0;
  13075. }
  13076. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13077. this.cameraDirection.z = 0;
  13078. }
  13079. this.cameraDirection.scaleInPlace(this.inertia);
  13080. }
  13081. if (needToRotate) {
  13082. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13083. this.cameraRotation.x = 0;
  13084. }
  13085. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13086. this.cameraRotation.y = 0;
  13087. }
  13088. this.cameraRotation.scaleInPlace(this.inertia);
  13089. }
  13090. _super.prototype._checkInputs.call(this);
  13091. };
  13092. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13093. if (this.rotationQuaternion) {
  13094. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13095. //update the up vector!
  13096. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13097. }
  13098. else {
  13099. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13100. }
  13101. };
  13102. TargetCamera.prototype._getViewMatrix = function () {
  13103. if (!this.lockedTarget) {
  13104. // Compute
  13105. this._updateCameraRotationMatrix();
  13106. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13107. // Computing target and final matrix
  13108. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13109. }
  13110. else {
  13111. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13112. }
  13113. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13114. return this._viewMatrix;
  13115. };
  13116. TargetCamera.prototype._getVRViewMatrix = function () {
  13117. this._updateCameraRotationMatrix();
  13118. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13119. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  13120. // Computing target and final matrix
  13121. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13122. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  13123. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  13124. return this._viewMatrix;
  13125. };
  13126. /**
  13127. * @override
  13128. * Override Camera.createRigCamera
  13129. */
  13130. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13131. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13132. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13133. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13134. if (!this.rotationQuaternion) {
  13135. this.rotationQuaternion = new BABYLON.Quaternion();
  13136. }
  13137. rigCamera._cameraRigParams = {};
  13138. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  13139. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  13140. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13141. }
  13142. return rigCamera;
  13143. }
  13144. return null;
  13145. };
  13146. /**
  13147. * @override
  13148. * Override Camera._updateRigCameras
  13149. */
  13150. TargetCamera.prototype._updateRigCameras = function () {
  13151. var camLeft = this._rigCameras[0];
  13152. var camRight = this._rigCameras[1];
  13153. switch (this.cameraRigMode) {
  13154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13156. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13157. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13158. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13159. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13160. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13161. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13162. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13163. camLeft.setTarget(this.getTarget());
  13164. camRight.setTarget(this.getTarget());
  13165. break;
  13166. case BABYLON.Camera.RIG_MODE_VR:
  13167. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13168. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13169. camLeft.position.copyFrom(this.position);
  13170. camRight.position.copyFrom(this.position);
  13171. break;
  13172. }
  13173. _super.prototype._updateRigCameras.call(this);
  13174. };
  13175. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13176. if (!this._rigCamTransformMatrix) {
  13177. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13178. }
  13179. var target = this.getTarget();
  13180. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13181. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13182. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13183. };
  13184. TargetCamera.prototype.getTypeName = function () {
  13185. return "TargetCamera";
  13186. };
  13187. __decorate([
  13188. BABYLON.serializeAsVector3()
  13189. ], TargetCamera.prototype, "rotation", void 0);
  13190. __decorate([
  13191. BABYLON.serialize()
  13192. ], TargetCamera.prototype, "speed", void 0);
  13193. __decorate([
  13194. BABYLON.serializeAsMeshReference("lockedTargetId")
  13195. ], TargetCamera.prototype, "lockedTarget", void 0);
  13196. return TargetCamera;
  13197. })(BABYLON.Camera);
  13198. BABYLON.TargetCamera = TargetCamera;
  13199. })(BABYLON || (BABYLON = {}));
  13200. var BABYLON;
  13201. (function (BABYLON) {
  13202. var FreeCamera = (function (_super) {
  13203. __extends(FreeCamera, _super);
  13204. function FreeCamera(name, position, scene) {
  13205. var _this = this;
  13206. _super.call(this, name, position, scene);
  13207. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13208. this.checkCollisions = false;
  13209. this.applyGravity = false;
  13210. this._collider = new BABYLON.Collider();
  13211. this._needMoveForGravity = false;
  13212. this._oldPosition = BABYLON.Vector3.Zero();
  13213. this._diffPosition = BABYLON.Vector3.Zero();
  13214. this._newPosition = BABYLON.Vector3.Zero();
  13215. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13216. if (collidedMesh === void 0) { collidedMesh = null; }
  13217. //TODO move this to the collision coordinator!
  13218. if (_this.getScene().workerCollisions)
  13219. newPosition.multiplyInPlace(_this._collider.radius);
  13220. var updatePosition = function (newPos) {
  13221. _this._newPosition.copyFrom(newPos);
  13222. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13223. var oldPosition = _this.position.clone();
  13224. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13225. _this.position.addInPlace(_this._diffPosition);
  13226. if (_this.onCollide && collidedMesh) {
  13227. _this.onCollide(collidedMesh);
  13228. }
  13229. }
  13230. };
  13231. updatePosition(newPosition);
  13232. };
  13233. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13234. this.inputs.addKeyboard().addMouse();
  13235. }
  13236. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13237. //-- begin properties for backward compatibility for inputs
  13238. get: function () {
  13239. var mouse = this.inputs.attached["mouse"];
  13240. if (mouse)
  13241. return mouse.angularSensibility;
  13242. },
  13243. set: function (value) {
  13244. var mouse = this.inputs.attached["mouse"];
  13245. if (mouse)
  13246. mouse.angularSensibility = value;
  13247. },
  13248. enumerable: true,
  13249. configurable: true
  13250. });
  13251. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13252. get: function () {
  13253. var keyboard = this.inputs.attached["keyboard"];
  13254. if (keyboard)
  13255. return keyboard.keysUp;
  13256. },
  13257. set: function (value) {
  13258. var keyboard = this.inputs.attached["keyboard"];
  13259. if (keyboard)
  13260. keyboard.keysUp = value;
  13261. },
  13262. enumerable: true,
  13263. configurable: true
  13264. });
  13265. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13266. get: function () {
  13267. var keyboard = this.inputs.attached["keyboard"];
  13268. if (keyboard)
  13269. return keyboard.keysDown;
  13270. },
  13271. set: function (value) {
  13272. var keyboard = this.inputs.attached["keyboard"];
  13273. if (keyboard)
  13274. keyboard.keysDown = value;
  13275. },
  13276. enumerable: true,
  13277. configurable: true
  13278. });
  13279. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13280. get: function () {
  13281. var keyboard = this.inputs.attached["keyboard"];
  13282. if (keyboard)
  13283. return keyboard.keysLeft;
  13284. },
  13285. set: function (value) {
  13286. var keyboard = this.inputs.attached["keyboard"];
  13287. if (keyboard)
  13288. keyboard.keysLeft = value;
  13289. },
  13290. enumerable: true,
  13291. configurable: true
  13292. });
  13293. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13294. get: function () {
  13295. var keyboard = this.inputs.attached["keyboard"];
  13296. if (keyboard)
  13297. return keyboard.keysRight;
  13298. },
  13299. set: function (value) {
  13300. var keyboard = this.inputs.attached["keyboard"];
  13301. if (keyboard)
  13302. keyboard.keysRight = value;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. // Controls
  13308. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13309. this.inputs.attachElement(element, noPreventDefault);
  13310. };
  13311. FreeCamera.prototype.detachControl = function (element) {
  13312. this.inputs.detachElement(element);
  13313. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13314. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13315. };
  13316. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13317. var globalPosition;
  13318. if (this.parent) {
  13319. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13320. }
  13321. else {
  13322. globalPosition = this.position;
  13323. }
  13324. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13325. this._collider.radius = this.ellipsoid;
  13326. //no need for clone, as long as gravity is not on.
  13327. var actualVelocity = velocity;
  13328. //add gravity to the velocity to prevent the dual-collision checking
  13329. if (this.applyGravity) {
  13330. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13331. actualVelocity = velocity.add(this.getScene().gravity);
  13332. }
  13333. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13334. };
  13335. FreeCamera.prototype._checkInputs = function () {
  13336. if (!this._localDirection) {
  13337. this._localDirection = BABYLON.Vector3.Zero();
  13338. this._transformedDirection = BABYLON.Vector3.Zero();
  13339. }
  13340. this.inputs.checkInputs();
  13341. _super.prototype._checkInputs.call(this);
  13342. };
  13343. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13344. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13345. };
  13346. FreeCamera.prototype._updatePosition = function () {
  13347. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13348. this._collideWithWorld(this.cameraDirection);
  13349. }
  13350. else {
  13351. this.position.addInPlace(this.cameraDirection);
  13352. }
  13353. };
  13354. FreeCamera.prototype.dispose = function () {
  13355. this.inputs.clear();
  13356. _super.prototype.dispose.call(this);
  13357. };
  13358. FreeCamera.prototype.getTypeName = function () {
  13359. return "FreeCamera";
  13360. };
  13361. __decorate([
  13362. BABYLON.serializeAsVector3()
  13363. ], FreeCamera.prototype, "ellipsoid", void 0);
  13364. __decorate([
  13365. BABYLON.serialize()
  13366. ], FreeCamera.prototype, "checkCollisions", void 0);
  13367. __decorate([
  13368. BABYLON.serialize()
  13369. ], FreeCamera.prototype, "applyGravity", void 0);
  13370. return FreeCamera;
  13371. })(BABYLON.TargetCamera);
  13372. BABYLON.FreeCamera = FreeCamera;
  13373. })(BABYLON || (BABYLON = {}));
  13374. var BABYLON;
  13375. (function (BABYLON) {
  13376. var FreeCameraInputsManager = (function (_super) {
  13377. __extends(FreeCameraInputsManager, _super);
  13378. function FreeCameraInputsManager(camera) {
  13379. _super.call(this, camera);
  13380. }
  13381. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13382. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13383. return this;
  13384. };
  13385. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13386. if (touchEnabled === void 0) { touchEnabled = true; }
  13387. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13388. return this;
  13389. };
  13390. FreeCameraInputsManager.prototype.addGamepad = function () {
  13391. this.add(new BABYLON.FreeCameraGamepadInput());
  13392. return this;
  13393. };
  13394. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13395. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13396. return this;
  13397. };
  13398. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13399. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13400. return this;
  13401. };
  13402. FreeCameraInputsManager.prototype.addTouch = function () {
  13403. this.add(new BABYLON.FreeCameraTouchInput());
  13404. return this;
  13405. };
  13406. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13407. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13408. return this;
  13409. };
  13410. return FreeCameraInputsManager;
  13411. })(BABYLON.CameraInputsManager);
  13412. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13413. })(BABYLON || (BABYLON = {}));
  13414. var BABYLON;
  13415. (function (BABYLON) {
  13416. var FollowCamera = (function (_super) {
  13417. __extends(FollowCamera, _super);
  13418. function FollowCamera(name, position, scene, target) {
  13419. _super.call(this, name, position, scene);
  13420. this.radius = 12;
  13421. this.rotationOffset = 0;
  13422. this.heightOffset = 4;
  13423. this.cameraAcceleration = 0.05;
  13424. this.maxCameraSpeed = 20;
  13425. this.target = target;
  13426. }
  13427. FollowCamera.prototype.getRadians = function (degrees) {
  13428. return degrees * Math.PI / 180;
  13429. };
  13430. FollowCamera.prototype.follow = function (cameraTarget) {
  13431. if (!cameraTarget)
  13432. return;
  13433. var yRotation;
  13434. if (cameraTarget.rotationQuaternion) {
  13435. var rotMatrix = new BABYLON.Matrix();
  13436. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13437. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13438. }
  13439. else {
  13440. yRotation = cameraTarget.rotation.y;
  13441. }
  13442. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13443. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13444. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13445. var dx = targetX - this.position.x;
  13446. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13447. var dz = (targetZ) - this.position.z;
  13448. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13449. var vy = dy * this.cameraAcceleration;
  13450. var vz = dz * this.cameraAcceleration * 2;
  13451. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13452. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13453. }
  13454. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13455. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13456. }
  13457. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13458. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13459. }
  13460. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13461. this.setTarget(cameraTarget.position);
  13462. };
  13463. FollowCamera.prototype._checkInputs = function () {
  13464. _super.prototype._checkInputs.call(this);
  13465. this.follow(this.target);
  13466. };
  13467. FollowCamera.prototype.getTypeName = function () {
  13468. return "FollowCamera";
  13469. };
  13470. __decorate([
  13471. BABYLON.serialize()
  13472. ], FollowCamera.prototype, "radius", void 0);
  13473. __decorate([
  13474. BABYLON.serialize()
  13475. ], FollowCamera.prototype, "rotationOffset", void 0);
  13476. __decorate([
  13477. BABYLON.serialize()
  13478. ], FollowCamera.prototype, "heightOffset", void 0);
  13479. __decorate([
  13480. BABYLON.serialize()
  13481. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13482. __decorate([
  13483. BABYLON.serialize()
  13484. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13485. __decorate([
  13486. BABYLON.serializeAsMeshReference("lockedTargetId")
  13487. ], FollowCamera.prototype, "target", void 0);
  13488. return FollowCamera;
  13489. })(BABYLON.TargetCamera);
  13490. BABYLON.FollowCamera = FollowCamera;
  13491. var ArcFollowCamera = (function (_super) {
  13492. __extends(ArcFollowCamera, _super);
  13493. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13494. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13495. this.alpha = alpha;
  13496. this.beta = beta;
  13497. this.radius = radius;
  13498. this.target = target;
  13499. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13500. this.follow();
  13501. }
  13502. ArcFollowCamera.prototype.follow = function () {
  13503. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13504. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13505. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13506. this.position = this.target.position.add(this._cartesianCoordinates);
  13507. this.setTarget(this.target.position);
  13508. };
  13509. ArcFollowCamera.prototype._checkInputs = function () {
  13510. _super.prototype._checkInputs.call(this);
  13511. this.follow();
  13512. };
  13513. ArcFollowCamera.prototype.getTypeName = function () {
  13514. return "ArcFollowCamera";
  13515. };
  13516. return ArcFollowCamera;
  13517. })(BABYLON.TargetCamera);
  13518. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13519. })(BABYLON || (BABYLON = {}));
  13520. var BABYLON;
  13521. (function (BABYLON) {
  13522. // We're mainly based on the logic defined into the FreeCamera code
  13523. var TouchCamera = (function (_super) {
  13524. __extends(TouchCamera, _super);
  13525. //-- end properties for backward compatibility for inputs
  13526. function TouchCamera(name, position, scene) {
  13527. _super.call(this, name, position, scene);
  13528. this.inputs.addTouch();
  13529. this._setupInputs();
  13530. }
  13531. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13532. //-- Begin properties for backward compatibility for inputs
  13533. get: function () {
  13534. var touch = this.inputs.attached["touch"];
  13535. if (touch)
  13536. return touch.touchAngularSensibility;
  13537. },
  13538. set: function (value) {
  13539. var touch = this.inputs.attached["touch"];
  13540. if (touch)
  13541. touch.touchAngularSensibility = value;
  13542. },
  13543. enumerable: true,
  13544. configurable: true
  13545. });
  13546. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13547. get: function () {
  13548. var touch = this.inputs.attached["touch"];
  13549. if (touch)
  13550. return touch.touchMoveSensibility;
  13551. },
  13552. set: function (value) {
  13553. var touch = this.inputs.attached["touch"];
  13554. if (touch)
  13555. touch.touchMoveSensibility = value;
  13556. },
  13557. enumerable: true,
  13558. configurable: true
  13559. });
  13560. TouchCamera.prototype.getTypeName = function () {
  13561. return "TouchCamera";
  13562. };
  13563. TouchCamera.prototype._setupInputs = function () {
  13564. var mouse = this.inputs.attached["mouse"];
  13565. if (mouse) {
  13566. mouse.touchEnabled = false;
  13567. }
  13568. };
  13569. return TouchCamera;
  13570. })(BABYLON.FreeCamera);
  13571. BABYLON.TouchCamera = TouchCamera;
  13572. })(BABYLON || (BABYLON = {}));
  13573. var BABYLON;
  13574. (function (BABYLON) {
  13575. var ArcRotateCamera = (function (_super) {
  13576. __extends(ArcRotateCamera, _super);
  13577. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13578. var _this = this;
  13579. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13580. this.inertialAlphaOffset = 0;
  13581. this.inertialBetaOffset = 0;
  13582. this.inertialRadiusOffset = 0;
  13583. this.lowerAlphaLimit = null;
  13584. this.upperAlphaLimit = null;
  13585. this.lowerBetaLimit = 0.01;
  13586. this.upperBetaLimit = Math.PI;
  13587. this.lowerRadiusLimit = null;
  13588. this.upperRadiusLimit = null;
  13589. this.inertialPanningX = 0;
  13590. this.inertialPanningY = 0;
  13591. //-- end properties for backward compatibility for inputs
  13592. this.zoomOnFactor = 1;
  13593. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13594. this.allowUpsideDown = true;
  13595. this._viewMatrix = new BABYLON.Matrix();
  13596. // Panning
  13597. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13598. this.checkCollisions = false;
  13599. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13600. this._collider = new BABYLON.Collider();
  13601. this._previousPosition = BABYLON.Vector3.Zero();
  13602. this._collisionVelocity = BABYLON.Vector3.Zero();
  13603. this._newPosition = BABYLON.Vector3.Zero();
  13604. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13605. if (collidedMesh === void 0) { collidedMesh = null; }
  13606. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13607. newPosition.multiplyInPlace(_this._collider.radius);
  13608. }
  13609. if (!collidedMesh) {
  13610. _this._previousPosition.copyFrom(_this.position);
  13611. }
  13612. else {
  13613. _this.setPosition(newPosition);
  13614. if (_this.onCollide) {
  13615. _this.onCollide(collidedMesh);
  13616. }
  13617. }
  13618. // Recompute because of constraints
  13619. var cosa = Math.cos(_this.alpha);
  13620. var sina = Math.sin(_this.alpha);
  13621. var cosb = Math.cos(_this.beta);
  13622. var sinb = Math.sin(_this.beta);
  13623. if (sinb === 0) {
  13624. sinb = 0.0001;
  13625. }
  13626. var target = _this._getTargetPosition();
  13627. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13628. _this.position.copyFrom(_this._newPosition);
  13629. var up = _this.upVector;
  13630. if (_this.allowUpsideDown && _this.beta < 0) {
  13631. up = up.clone();
  13632. up = up.negate();
  13633. }
  13634. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13635. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13636. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13637. _this._collisionTriggered = false;
  13638. };
  13639. if (!target) {
  13640. this.target = BABYLON.Vector3.Zero();
  13641. }
  13642. else {
  13643. this.target = target;
  13644. }
  13645. this.alpha = alpha;
  13646. this.beta = beta;
  13647. this.radius = radius;
  13648. this.getViewMatrix();
  13649. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13650. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13651. }
  13652. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13653. //-- begin properties for backward compatibility for inputs
  13654. get: function () {
  13655. var pointers = this.inputs.attached["pointers"];
  13656. if (pointers)
  13657. return pointers.angularSensibilityX;
  13658. },
  13659. set: function (value) {
  13660. var pointers = this.inputs.attached["pointers"];
  13661. if (pointers) {
  13662. pointers.angularSensibilityX = value;
  13663. }
  13664. },
  13665. enumerable: true,
  13666. configurable: true
  13667. });
  13668. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13669. get: function () {
  13670. var pointers = this.inputs.attached["pointers"];
  13671. if (pointers)
  13672. return pointers.angularSensibilityY;
  13673. },
  13674. set: function (value) {
  13675. var pointers = this.inputs.attached["pointers"];
  13676. if (pointers) {
  13677. pointers.angularSensibilityY = value;
  13678. }
  13679. },
  13680. enumerable: true,
  13681. configurable: true
  13682. });
  13683. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13684. get: function () {
  13685. var pointers = this.inputs.attached["pointers"];
  13686. if (pointers)
  13687. return pointers.pinchPrecision;
  13688. },
  13689. set: function (value) {
  13690. var pointers = this.inputs.attached["pointers"];
  13691. if (pointers) {
  13692. pointers.pinchPrecision = value;
  13693. }
  13694. },
  13695. enumerable: true,
  13696. configurable: true
  13697. });
  13698. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13699. get: function () {
  13700. var pointers = this.inputs.attached["pointers"];
  13701. if (pointers)
  13702. return pointers.panningSensibility;
  13703. },
  13704. set: function (value) {
  13705. var pointers = this.inputs.attached["pointers"];
  13706. if (pointers) {
  13707. pointers.panningSensibility = value;
  13708. }
  13709. },
  13710. enumerable: true,
  13711. configurable: true
  13712. });
  13713. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13714. get: function () {
  13715. var keyboard = this.inputs.attached["keyboard"];
  13716. if (keyboard)
  13717. return keyboard.keysUp;
  13718. },
  13719. set: function (value) {
  13720. var keyboard = this.inputs.attached["keyboard"];
  13721. if (keyboard)
  13722. keyboard.keysUp = value;
  13723. },
  13724. enumerable: true,
  13725. configurable: true
  13726. });
  13727. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13728. get: function () {
  13729. var keyboard = this.inputs.attached["keyboard"];
  13730. if (keyboard)
  13731. return keyboard.keysDown;
  13732. },
  13733. set: function (value) {
  13734. var keyboard = this.inputs.attached["keyboard"];
  13735. if (keyboard)
  13736. keyboard.keysDown = value;
  13737. },
  13738. enumerable: true,
  13739. configurable: true
  13740. });
  13741. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13742. get: function () {
  13743. var keyboard = this.inputs.attached["keyboard"];
  13744. if (keyboard)
  13745. return keyboard.keysLeft;
  13746. },
  13747. set: function (value) {
  13748. var keyboard = this.inputs.attached["keyboard"];
  13749. if (keyboard)
  13750. keyboard.keysLeft = value;
  13751. },
  13752. enumerable: true,
  13753. configurable: true
  13754. });
  13755. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13756. get: function () {
  13757. var keyboard = this.inputs.attached["keyboard"];
  13758. if (keyboard)
  13759. return keyboard.keysRight;
  13760. },
  13761. set: function (value) {
  13762. var keyboard = this.inputs.attached["keyboard"];
  13763. if (keyboard)
  13764. keyboard.keysRight = value;
  13765. },
  13766. enumerable: true,
  13767. configurable: true
  13768. });
  13769. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13770. get: function () {
  13771. var mousewheel = this.inputs.attached["mousewheel"];
  13772. if (mousewheel)
  13773. return mousewheel.wheelPrecision;
  13774. },
  13775. set: function (value) {
  13776. var mousewheel = this.inputs.attached["mousewheel"];
  13777. if (mousewheel)
  13778. mousewheel.wheelPrecision = value;
  13779. },
  13780. enumerable: true,
  13781. configurable: true
  13782. });
  13783. // Cache
  13784. ArcRotateCamera.prototype._initCache = function () {
  13785. _super.prototype._initCache.call(this);
  13786. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13787. this._cache.alpha = undefined;
  13788. this._cache.beta = undefined;
  13789. this._cache.radius = undefined;
  13790. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13791. };
  13792. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13793. if (!ignoreParentClass) {
  13794. _super.prototype._updateCache.call(this);
  13795. }
  13796. this._cache.target.copyFrom(this._getTargetPosition());
  13797. this._cache.alpha = this.alpha;
  13798. this._cache.beta = this.beta;
  13799. this._cache.radius = this.radius;
  13800. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13801. };
  13802. ArcRotateCamera.prototype._getTargetPosition = function () {
  13803. if (this.target.getAbsolutePosition) {
  13804. return this.target.getAbsolutePosition();
  13805. }
  13806. return this.target;
  13807. };
  13808. // Synchronized
  13809. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13810. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13811. return false;
  13812. return this._cache.target.equals(this.target)
  13813. && this._cache.alpha === this.alpha
  13814. && this._cache.beta === this.beta
  13815. && this._cache.radius === this.radius
  13816. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13817. };
  13818. // Methods
  13819. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13820. var _this = this;
  13821. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13822. this._useCtrlForPanning = useCtrlForPanning;
  13823. this.inputs.attachElement(element, noPreventDefault);
  13824. this._reset = function () {
  13825. _this.inertialAlphaOffset = 0;
  13826. _this.inertialBetaOffset = 0;
  13827. _this.inertialRadiusOffset = 0;
  13828. };
  13829. };
  13830. ArcRotateCamera.prototype.detachControl = function (element) {
  13831. this.inputs.detachElement(element);
  13832. if (this._reset) {
  13833. this._reset();
  13834. }
  13835. };
  13836. ArcRotateCamera.prototype._checkInputs = function () {
  13837. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13838. if (this._collisionTriggered) {
  13839. return;
  13840. }
  13841. this.inputs.checkInputs();
  13842. // Inertia
  13843. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13844. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13845. this.beta += this.inertialBetaOffset;
  13846. this.radius -= this.inertialRadiusOffset;
  13847. this.inertialAlphaOffset *= this.inertia;
  13848. this.inertialBetaOffset *= this.inertia;
  13849. this.inertialRadiusOffset *= this.inertia;
  13850. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13851. this.inertialAlphaOffset = 0;
  13852. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13853. this.inertialBetaOffset = 0;
  13854. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13855. this.inertialRadiusOffset = 0;
  13856. }
  13857. // Panning inertia
  13858. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13859. if (!this._localDirection) {
  13860. this._localDirection = BABYLON.Vector3.Zero();
  13861. this._transformedDirection = BABYLON.Vector3.Zero();
  13862. }
  13863. this.inertialPanningX *= this.inertia;
  13864. this.inertialPanningY *= this.inertia;
  13865. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13866. this.inertialPanningX = 0;
  13867. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13868. this.inertialPanningY = 0;
  13869. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13870. this._localDirection.multiplyInPlace(this.panningAxis);
  13871. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13872. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13873. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13874. if (!this.panningAxis.y) {
  13875. this._transformedDirection.y = 0;
  13876. }
  13877. if (!this.target.getAbsolutePosition) {
  13878. this.target.addInPlace(this._transformedDirection);
  13879. }
  13880. }
  13881. // Limits
  13882. this._checkLimits();
  13883. _super.prototype._checkInputs.call(this);
  13884. };
  13885. ArcRotateCamera.prototype._checkLimits = function () {
  13886. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13887. if (this.allowUpsideDown && this.beta > Math.PI) {
  13888. this.beta = this.beta - (2 * Math.PI);
  13889. }
  13890. }
  13891. else {
  13892. if (this.beta < this.lowerBetaLimit) {
  13893. this.beta = this.lowerBetaLimit;
  13894. }
  13895. }
  13896. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13897. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13898. this.beta = this.beta + (2 * Math.PI);
  13899. }
  13900. }
  13901. else {
  13902. if (this.beta > this.upperBetaLimit) {
  13903. this.beta = this.upperBetaLimit;
  13904. }
  13905. }
  13906. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13907. this.alpha = this.lowerAlphaLimit;
  13908. }
  13909. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13910. this.alpha = this.upperAlphaLimit;
  13911. }
  13912. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13913. this.radius = this.lowerRadiusLimit;
  13914. }
  13915. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13916. this.radius = this.upperRadiusLimit;
  13917. }
  13918. };
  13919. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13920. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13921. this.radius = radiusv3.length();
  13922. // Alpha
  13923. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13924. if (radiusv3.z < 0) {
  13925. this.alpha = 2 * Math.PI - this.alpha;
  13926. }
  13927. // Beta
  13928. this.beta = Math.acos(radiusv3.y / this.radius);
  13929. this._checkLimits();
  13930. };
  13931. ArcRotateCamera.prototype.setPosition = function (position) {
  13932. if (this.position.equals(position)) {
  13933. return;
  13934. }
  13935. this.position = position;
  13936. this.rebuildAnglesAndRadius();
  13937. };
  13938. ArcRotateCamera.prototype.setTarget = function (target) {
  13939. if (this._getTargetPosition().equals(target)) {
  13940. return;
  13941. }
  13942. this.target = target;
  13943. this.rebuildAnglesAndRadius();
  13944. };
  13945. ArcRotateCamera.prototype._getViewMatrix = function () {
  13946. // Compute
  13947. var cosa = Math.cos(this.alpha);
  13948. var sina = Math.sin(this.alpha);
  13949. var cosb = Math.cos(this.beta);
  13950. var sinb = Math.sin(this.beta);
  13951. if (sinb === 0) {
  13952. sinb = 0.0001;
  13953. }
  13954. var target = this._getTargetPosition();
  13955. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13956. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13957. this._collider.radius = this.collisionRadius;
  13958. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13959. this._collisionTriggered = true;
  13960. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13961. }
  13962. else {
  13963. this.position.copyFrom(this._newPosition);
  13964. var up = this.upVector;
  13965. if (this.allowUpsideDown && this.beta < 0) {
  13966. up = up.clone();
  13967. up = up.negate();
  13968. }
  13969. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13970. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13971. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13972. }
  13973. return this._viewMatrix;
  13974. };
  13975. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13976. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13977. meshes = meshes || this.getScene().meshes;
  13978. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13979. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13980. this.radius = distance * this.zoomOnFactor;
  13981. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13982. };
  13983. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13984. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13985. var meshesOrMinMaxVector;
  13986. var distance;
  13987. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13988. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13989. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13990. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13991. }
  13992. else {
  13993. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13994. distance = meshesOrMinMaxVectorAndDistance.distance;
  13995. }
  13996. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13997. if (!doNotUpdateMaxZ) {
  13998. this.maxZ = distance * 2;
  13999. }
  14000. };
  14001. /**
  14002. * @override
  14003. * Override Camera.createRigCamera
  14004. */
  14005. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14006. var alphaShift;
  14007. switch (this.cameraRigMode) {
  14008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14011. case BABYLON.Camera.RIG_MODE_VR:
  14012. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14013. break;
  14014. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14015. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14016. break;
  14017. }
  14018. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14019. rigCam._cameraRigParams = {};
  14020. return rigCam;
  14021. };
  14022. /**
  14023. * @override
  14024. * Override Camera._updateRigCameras
  14025. */
  14026. ArcRotateCamera.prototype._updateRigCameras = function () {
  14027. var camLeft = this._rigCameras[0];
  14028. var camRight = this._rigCameras[1];
  14029. camLeft.beta = camRight.beta = this.beta;
  14030. camLeft.radius = camRight.radius = this.radius;
  14031. switch (this.cameraRigMode) {
  14032. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14033. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14034. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14035. case BABYLON.Camera.RIG_MODE_VR:
  14036. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14037. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14038. break;
  14039. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14040. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14041. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14042. break;
  14043. }
  14044. _super.prototype._updateRigCameras.call(this);
  14045. };
  14046. ArcRotateCamera.prototype.dispose = function () {
  14047. this.inputs.clear();
  14048. _super.prototype.dispose.call(this);
  14049. };
  14050. ArcRotateCamera.prototype.getTypeName = function () {
  14051. return "ArcRotateCamera";
  14052. };
  14053. __decorate([
  14054. BABYLON.serialize()
  14055. ], ArcRotateCamera.prototype, "alpha", void 0);
  14056. __decorate([
  14057. BABYLON.serialize()
  14058. ], ArcRotateCamera.prototype, "beta", void 0);
  14059. __decorate([
  14060. BABYLON.serialize()
  14061. ], ArcRotateCamera.prototype, "radius", void 0);
  14062. __decorate([
  14063. BABYLON.serializeAsVector3()
  14064. ], ArcRotateCamera.prototype, "target", void 0);
  14065. __decorate([
  14066. BABYLON.serialize()
  14067. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14068. __decorate([
  14069. BABYLON.serialize()
  14070. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14071. __decorate([
  14072. BABYLON.serialize()
  14073. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14074. __decorate([
  14075. BABYLON.serialize()
  14076. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14077. __decorate([
  14078. BABYLON.serialize()
  14079. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14080. __decorate([
  14081. BABYLON.serialize()
  14082. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14083. __decorate([
  14084. BABYLON.serialize()
  14085. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14086. __decorate([
  14087. BABYLON.serialize()
  14088. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14089. __decorate([
  14090. BABYLON.serialize()
  14091. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14092. __decorate([
  14093. BABYLON.serialize()
  14094. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14095. __decorate([
  14096. BABYLON.serialize()
  14097. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14098. __decorate([
  14099. BABYLON.serialize()
  14100. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14101. __decorate([
  14102. BABYLON.serialize()
  14103. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14104. return ArcRotateCamera;
  14105. })(BABYLON.TargetCamera);
  14106. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14107. })(BABYLON || (BABYLON = {}));
  14108. var BABYLON;
  14109. (function (BABYLON) {
  14110. var ArcRotateCameraInputsManager = (function (_super) {
  14111. __extends(ArcRotateCameraInputsManager, _super);
  14112. function ArcRotateCameraInputsManager(camera) {
  14113. _super.call(this, camera);
  14114. }
  14115. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14116. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14117. return this;
  14118. };
  14119. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14120. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14121. return this;
  14122. };
  14123. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14124. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14125. return this;
  14126. };
  14127. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14128. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14129. return this;
  14130. };
  14131. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14132. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14133. return this;
  14134. };
  14135. return ArcRotateCameraInputsManager;
  14136. })(BABYLON.CameraInputsManager);
  14137. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14138. })(BABYLON || (BABYLON = {}));
  14139. var BABYLON;
  14140. (function (BABYLON) {
  14141. var RenderingManager = (function () {
  14142. function RenderingManager(scene) {
  14143. this._renderingGroups = new Array();
  14144. this._scene = scene;
  14145. }
  14146. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14147. if (this._scene._activeParticleSystems.length === 0) {
  14148. return;
  14149. }
  14150. // Particles
  14151. var activeCamera = this._scene.activeCamera;
  14152. var beforeParticlesDate = BABYLON.Tools.Now;
  14153. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14154. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14155. if (particleSystem.renderingGroupId !== index) {
  14156. continue;
  14157. }
  14158. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14159. continue;
  14160. }
  14161. this._clearDepthBuffer();
  14162. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14163. this._scene._activeParticles += particleSystem.render();
  14164. }
  14165. }
  14166. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  14167. };
  14168. RenderingManager.prototype._renderSprites = function (index) {
  14169. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14170. return;
  14171. }
  14172. // Sprites
  14173. var activeCamera = this._scene.activeCamera;
  14174. var beforeSpritessDate = BABYLON.Tools.Now;
  14175. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14176. var spriteManager = this._scene.spriteManagers[id];
  14177. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14178. this._clearDepthBuffer();
  14179. spriteManager.render();
  14180. }
  14181. }
  14182. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  14183. };
  14184. RenderingManager.prototype._clearDepthBuffer = function () {
  14185. if (this._depthBufferAlreadyCleaned) {
  14186. return;
  14187. }
  14188. this._scene.getEngine().clear(0, false, true);
  14189. this._depthBufferAlreadyCleaned = true;
  14190. };
  14191. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14192. if (this._currentRenderSprites) {
  14193. this._renderSprites(this._currentIndex);
  14194. }
  14195. if (this._currentRenderParticles) {
  14196. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14197. }
  14198. };
  14199. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14200. this._currentActiveMeshes = activeMeshes;
  14201. this._currentRenderParticles = renderParticles;
  14202. this._currentRenderSprites = renderSprites;
  14203. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14204. this._depthBufferAlreadyCleaned = index == 0;
  14205. var renderingGroup = this._renderingGroups[index];
  14206. var needToStepBack = false;
  14207. this._currentIndex = index;
  14208. if (renderingGroup) {
  14209. this._clearDepthBuffer();
  14210. if (!renderingGroup.onBeforeTransparentRendering) {
  14211. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14212. }
  14213. if (!renderingGroup.render(customRenderFunction)) {
  14214. this._renderingGroups.splice(index, 1);
  14215. needToStepBack = true;
  14216. this._renderSpritesAndParticles();
  14217. }
  14218. }
  14219. else {
  14220. this._renderSpritesAndParticles();
  14221. }
  14222. if (needToStepBack) {
  14223. index--;
  14224. }
  14225. }
  14226. };
  14227. RenderingManager.prototype.reset = function () {
  14228. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14229. if (renderingGroup) {
  14230. renderingGroup.prepare();
  14231. }
  14232. });
  14233. };
  14234. RenderingManager.prototype.dispatch = function (subMesh) {
  14235. var mesh = subMesh.getMesh();
  14236. var renderingGroupId = mesh.renderingGroupId || 0;
  14237. if (!this._renderingGroups[renderingGroupId]) {
  14238. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14239. }
  14240. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14241. };
  14242. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14243. return RenderingManager;
  14244. })();
  14245. BABYLON.RenderingManager = RenderingManager;
  14246. })(BABYLON || (BABYLON = {}));
  14247. var BABYLON;
  14248. (function (BABYLON) {
  14249. var RenderingGroup = (function () {
  14250. function RenderingGroup(index, scene) {
  14251. this.index = index;
  14252. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14253. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14254. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14255. this._scene = scene;
  14256. }
  14257. RenderingGroup.prototype.render = function (customRenderFunction) {
  14258. if (customRenderFunction) {
  14259. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14260. return true;
  14261. }
  14262. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14263. if (this.onBeforeTransparentRendering) {
  14264. this.onBeforeTransparentRendering();
  14265. }
  14266. return false;
  14267. }
  14268. var engine = this._scene.getEngine();
  14269. // Opaque
  14270. var subIndex;
  14271. var submesh;
  14272. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14273. submesh = this._opaqueSubMeshes.data[subIndex];
  14274. submesh.render(false);
  14275. }
  14276. // Alpha test
  14277. engine.setAlphaTesting(true);
  14278. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14279. submesh = this._alphaTestSubMeshes.data[subIndex];
  14280. submesh.render(false);
  14281. }
  14282. engine.setAlphaTesting(false);
  14283. if (this.onBeforeTransparentRendering) {
  14284. this.onBeforeTransparentRendering();
  14285. }
  14286. // Transparent
  14287. if (this._transparentSubMeshes.length) {
  14288. // Sorting
  14289. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14290. submesh = this._transparentSubMeshes.data[subIndex];
  14291. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14292. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14293. }
  14294. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14295. sortedArray.sort(function (a, b) {
  14296. // Alpha index first
  14297. if (a._alphaIndex > b._alphaIndex) {
  14298. return 1;
  14299. }
  14300. if (a._alphaIndex < b._alphaIndex) {
  14301. return -1;
  14302. }
  14303. // Then distance to camera
  14304. if (a._distanceToCamera < b._distanceToCamera) {
  14305. return 1;
  14306. }
  14307. if (a._distanceToCamera > b._distanceToCamera) {
  14308. return -1;
  14309. }
  14310. return 0;
  14311. });
  14312. // Rendering
  14313. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14314. submesh = sortedArray[subIndex];
  14315. submesh.render(true);
  14316. }
  14317. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14318. }
  14319. return true;
  14320. };
  14321. RenderingGroup.prototype.prepare = function () {
  14322. this._opaqueSubMeshes.reset();
  14323. this._transparentSubMeshes.reset();
  14324. this._alphaTestSubMeshes.reset();
  14325. };
  14326. RenderingGroup.prototype.dispatch = function (subMesh) {
  14327. var material = subMesh.getMaterial();
  14328. var mesh = subMesh.getMesh();
  14329. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14330. this._transparentSubMeshes.push(subMesh);
  14331. }
  14332. else if (material.needAlphaTesting()) {
  14333. this._alphaTestSubMeshes.push(subMesh);
  14334. }
  14335. else {
  14336. this._opaqueSubMeshes.push(subMesh); // Opaque
  14337. }
  14338. };
  14339. return RenderingGroup;
  14340. })();
  14341. BABYLON.RenderingGroup = RenderingGroup;
  14342. })(BABYLON || (BABYLON = {}));
  14343. var BABYLON;
  14344. (function (BABYLON) {
  14345. var PointerEventTypes = (function () {
  14346. function PointerEventTypes() {
  14347. }
  14348. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14349. get: function () {
  14350. return PointerEventTypes._POINTERDOWN;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14356. get: function () {
  14357. return PointerEventTypes._POINTERUP;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14363. get: function () {
  14364. return PointerEventTypes._POINTERMOVE;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14370. get: function () {
  14371. return PointerEventTypes._POINTERWHEEL;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14377. get: function () {
  14378. return PointerEventTypes._POINTERPICK;
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. PointerEventTypes._POINTERDOWN = 0x01;
  14384. PointerEventTypes._POINTERUP = 0x02;
  14385. PointerEventTypes._POINTERMOVE = 0x04;
  14386. PointerEventTypes._POINTERWHEEL = 0x08;
  14387. PointerEventTypes._POINTERPICK = 0x10;
  14388. return PointerEventTypes;
  14389. })();
  14390. BABYLON.PointerEventTypes = PointerEventTypes;
  14391. /**
  14392. * This class is used to store pointer related info for the onPrePointerObservable event.
  14393. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14394. */
  14395. var PointerInfoPre = (function () {
  14396. function PointerInfoPre(type, event, localX, localY) {
  14397. this.type = type;
  14398. this.event = event;
  14399. this.skipOnPointerObservable = false;
  14400. this.localPosition = new BABYLON.Vector2(localX, localY);
  14401. }
  14402. return PointerInfoPre;
  14403. })();
  14404. BABYLON.PointerInfoPre = PointerInfoPre;
  14405. /**
  14406. * This type contains all the data related to a pointer event in Babylon.js.
  14407. * 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.
  14408. */
  14409. var PointerInfo = (function () {
  14410. function PointerInfo(type, event, pickInfo) {
  14411. this.type = type;
  14412. this.event = event;
  14413. this.pickInfo = pickInfo;
  14414. }
  14415. return PointerInfo;
  14416. })();
  14417. BABYLON.PointerInfo = PointerInfo;
  14418. /**
  14419. * Represents a scene to be rendered by the engine.
  14420. * @see http://doc.babylonjs.com/page.php?p=21911
  14421. */
  14422. var Scene = (function () {
  14423. /**
  14424. * @constructor
  14425. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14426. */
  14427. function Scene(engine) {
  14428. // Members
  14429. this.autoClear = true;
  14430. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14431. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14432. this.forceWireframe = false;
  14433. this.forcePointsCloud = false;
  14434. this.forceShowBoundingBoxes = false;
  14435. this.animationsEnabled = true;
  14436. this.constantlyUpdateMeshUnderPointer = false;
  14437. // Events
  14438. /**
  14439. * An event triggered when the scene is disposed.
  14440. * @type {BABYLON.Observable}
  14441. */
  14442. this.onDisposeObservable = new BABYLON.Observable();
  14443. /**
  14444. * An event triggered before rendering the scene
  14445. * @type {BABYLON.Observable}
  14446. */
  14447. this.onBeforeRenderObservable = new BABYLON.Observable();
  14448. /**
  14449. * An event triggered after rendering the scene
  14450. * @type {BABYLON.Observable}
  14451. */
  14452. this.onAfterRenderObservable = new BABYLON.Observable();
  14453. /**
  14454. * An event triggered when the scene is ready
  14455. * @type {BABYLON.Observable}
  14456. */
  14457. this.onReadyObservable = new BABYLON.Observable();
  14458. /**
  14459. * An event triggered before rendering a camera
  14460. * @type {BABYLON.Observable}
  14461. */
  14462. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14463. /**
  14464. * An event triggered after rendering a camera
  14465. * @type {BABYLON.Observable}
  14466. */
  14467. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14468. /**
  14469. * An event triggered when a camera is created
  14470. * @type {BABYLON.Observable}
  14471. */
  14472. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14473. /**
  14474. * An event triggered when a camera is removed
  14475. * @type {BABYLON.Observable}
  14476. */
  14477. this.onCameraRemovedObservable = new BABYLON.Observable();
  14478. /**
  14479. * An event triggered when a light is created
  14480. * @type {BABYLON.Observable}
  14481. */
  14482. this.onNewLightAddedObservable = new BABYLON.Observable();
  14483. /**
  14484. * An event triggered when a light is removed
  14485. * @type {BABYLON.Observable}
  14486. */
  14487. this.onLightRemovedObservable = new BABYLON.Observable();
  14488. /**
  14489. * An event triggered when a geometry is created
  14490. * @type {BABYLON.Observable}
  14491. */
  14492. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14493. /**
  14494. * An event triggered when a geometry is removed
  14495. * @type {BABYLON.Observable}
  14496. */
  14497. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14498. /**
  14499. * An event triggered when a mesh is created
  14500. * @type {BABYLON.Observable}
  14501. */
  14502. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14503. /**
  14504. * An event triggered when a mesh is removed
  14505. * @type {BABYLON.Observable}
  14506. */
  14507. this.onMeshRemovedObservable = new BABYLON.Observable();
  14508. // Animations
  14509. this.animations = [];
  14510. /**
  14511. * 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).
  14512. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14513. */
  14514. this.onPrePointerObservable = new BABYLON.Observable();
  14515. /**
  14516. * Observable event triggered each time an input event is received from the rendering canvas
  14517. */
  14518. this.onPointerObservable = new BABYLON.Observable();
  14519. 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
  14520. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14521. this._startingPointerTime = 0;
  14522. // Fog
  14523. /**
  14524. * is fog enabled on this scene.
  14525. * @type {boolean}
  14526. */
  14527. this.fogEnabled = true;
  14528. this.fogMode = Scene.FOGMODE_NONE;
  14529. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14530. this.fogDensity = 0.1;
  14531. this.fogStart = 0;
  14532. this.fogEnd = 1000.0;
  14533. // Lights
  14534. /**
  14535. * is shadow enabled on this scene.
  14536. * @type {boolean}
  14537. */
  14538. this.shadowsEnabled = true;
  14539. /**
  14540. * is light enabled on this scene.
  14541. * @type {boolean}
  14542. */
  14543. this.lightsEnabled = true;
  14544. /**
  14545. * All of the lights added to this scene.
  14546. * @see BABYLON.Light
  14547. * @type {BABYLON.Light[]}
  14548. */
  14549. this.lights = new Array();
  14550. // Cameras
  14551. /**
  14552. * All of the cameras added to this scene.
  14553. * @see BABYLON.Camera
  14554. * @type {BABYLON.Camera[]}
  14555. */
  14556. this.cameras = new Array();
  14557. this.activeCameras = new Array();
  14558. // Meshes
  14559. /**
  14560. * All of the (abstract) meshes added to this scene.
  14561. * @see BABYLON.AbstractMesh
  14562. * @type {BABYLON.AbstractMesh[]}
  14563. */
  14564. this.meshes = new Array();
  14565. // Geometries
  14566. this._geometries = new Array();
  14567. this.materials = new Array();
  14568. this.multiMaterials = new Array();
  14569. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14570. // Textures
  14571. this.texturesEnabled = true;
  14572. this.textures = new Array();
  14573. // Particles
  14574. this.particlesEnabled = true;
  14575. this.particleSystems = new Array();
  14576. // Sprites
  14577. this.spritesEnabled = true;
  14578. this.spriteManagers = new Array();
  14579. // Layers
  14580. this.layers = new Array();
  14581. // Skeletons
  14582. this.skeletonsEnabled = true;
  14583. this.skeletons = new Array();
  14584. // Lens flares
  14585. this.lensFlaresEnabled = true;
  14586. this.lensFlareSystems = new Array();
  14587. // Collisions
  14588. this.collisionsEnabled = true;
  14589. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14590. // Postprocesses
  14591. this.postProcessesEnabled = true;
  14592. // Customs render targets
  14593. this.renderTargetsEnabled = true;
  14594. this.dumpNextRenderTargets = false;
  14595. this.customRenderTargets = new Array();
  14596. // Imported meshes
  14597. this.importedMeshesFiles = new Array();
  14598. // Probes
  14599. this.probesEnabled = true;
  14600. this.reflectionProbes = new Array();
  14601. this._actionManagers = new Array();
  14602. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14603. // Procedural textures
  14604. this.proceduralTexturesEnabled = true;
  14605. this._proceduralTextures = new Array();
  14606. this.soundTracks = new Array();
  14607. this._audioEnabled = true;
  14608. this._headphone = false;
  14609. this._totalVertices = 0;
  14610. this._activeIndices = 0;
  14611. this._activeParticles = 0;
  14612. this._lastFrameDuration = 0;
  14613. this._evaluateActiveMeshesDuration = 0;
  14614. this._renderTargetsDuration = 0;
  14615. this._particlesDuration = 0;
  14616. this._renderDuration = 0;
  14617. this._spritesDuration = 0;
  14618. this._animationRatio = 0;
  14619. this._renderId = 0;
  14620. this._executeWhenReadyTimeoutId = -1;
  14621. this._intermediateRendering = false;
  14622. this._toBeDisposed = new BABYLON.SmartArray(256);
  14623. this._pendingData = []; //ANY
  14624. this._activeMeshes = new BABYLON.SmartArray(256);
  14625. this._processedMaterials = new BABYLON.SmartArray(256);
  14626. this._renderTargets = new BABYLON.SmartArray(256);
  14627. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14628. this._activeSkeletons = new BABYLON.SmartArray(32);
  14629. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14630. this._activeBones = 0;
  14631. this._activeAnimatables = new Array();
  14632. this._transformMatrix = BABYLON.Matrix.Zero();
  14633. this._edgesRenderers = new BABYLON.SmartArray(16);
  14634. this._uniqueIdCounter = 0;
  14635. this._engine = engine;
  14636. engine.scenes.push(this);
  14637. this._renderingManager = new BABYLON.RenderingManager(this);
  14638. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14639. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14640. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14641. if (BABYLON.OutlineRenderer) {
  14642. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14643. }
  14644. this.attachControl();
  14645. if (BABYLON.SoundTrack) {
  14646. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14647. }
  14648. //simplification queue
  14649. if (BABYLON.SimplificationQueue) {
  14650. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14651. }
  14652. //collision coordinator initialization. For now legacy per default.
  14653. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14654. }
  14655. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14656. get: function () {
  14657. return Scene._FOGMODE_NONE;
  14658. },
  14659. enumerable: true,
  14660. configurable: true
  14661. });
  14662. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14663. get: function () {
  14664. return Scene._FOGMODE_EXP;
  14665. },
  14666. enumerable: true,
  14667. configurable: true
  14668. });
  14669. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14670. get: function () {
  14671. return Scene._FOGMODE_EXP2;
  14672. },
  14673. enumerable: true,
  14674. configurable: true
  14675. });
  14676. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14677. get: function () {
  14678. return Scene._FOGMODE_LINEAR;
  14679. },
  14680. enumerable: true,
  14681. configurable: true
  14682. });
  14683. Object.defineProperty(Scene.prototype, "onDispose", {
  14684. set: function (callback) {
  14685. if (this._onDisposeObserver) {
  14686. this.onDisposeObservable.remove(this._onDisposeObserver);
  14687. }
  14688. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14689. },
  14690. enumerable: true,
  14691. configurable: true
  14692. });
  14693. Object.defineProperty(Scene.prototype, "beforeRender", {
  14694. set: function (callback) {
  14695. if (this._onBeforeRenderObserver) {
  14696. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14697. }
  14698. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14699. },
  14700. enumerable: true,
  14701. configurable: true
  14702. });
  14703. Object.defineProperty(Scene.prototype, "afterRender", {
  14704. set: function (callback) {
  14705. if (this._onAfterRenderObserver) {
  14706. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14707. }
  14708. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14709. },
  14710. enumerable: true,
  14711. configurable: true
  14712. });
  14713. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14714. set: function (callback) {
  14715. if (this._onBeforeCameraRenderObserver) {
  14716. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14717. }
  14718. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14719. },
  14720. enumerable: true,
  14721. configurable: true
  14722. });
  14723. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14724. set: function (callback) {
  14725. if (this._onAfterCameraRenderObserver) {
  14726. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14727. }
  14728. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14729. },
  14730. enumerable: true,
  14731. configurable: true
  14732. });
  14733. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14734. get: function () {
  14735. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(Scene.prototype, "debugLayer", {
  14741. // Properties
  14742. get: function () {
  14743. if (!this._debugLayer) {
  14744. this._debugLayer = new BABYLON.DebugLayer(this);
  14745. }
  14746. return this._debugLayer;
  14747. },
  14748. enumerable: true,
  14749. configurable: true
  14750. });
  14751. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14752. get: function () {
  14753. return this._workerCollisions;
  14754. },
  14755. set: function (enabled) {
  14756. enabled = (enabled && !!Worker);
  14757. this._workerCollisions = enabled;
  14758. if (this.collisionCoordinator) {
  14759. this.collisionCoordinator.destroy();
  14760. }
  14761. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14762. this.collisionCoordinator.init(this);
  14763. },
  14764. enumerable: true,
  14765. configurable: true
  14766. });
  14767. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14768. get: function () {
  14769. return this._selectionOctree;
  14770. },
  14771. enumerable: true,
  14772. configurable: true
  14773. });
  14774. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14775. /**
  14776. * The mesh that is currently under the pointer.
  14777. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14778. */
  14779. get: function () {
  14780. return this._pointerOverMesh;
  14781. },
  14782. enumerable: true,
  14783. configurable: true
  14784. });
  14785. Object.defineProperty(Scene.prototype, "pointerX", {
  14786. /**
  14787. * Current on-screen X position of the pointer
  14788. * @return {number} X position of the pointer
  14789. */
  14790. get: function () {
  14791. return this._pointerX;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. Object.defineProperty(Scene.prototype, "pointerY", {
  14797. /**
  14798. * Current on-screen Y position of the pointer
  14799. * @return {number} Y position of the pointer
  14800. */
  14801. get: function () {
  14802. return this._pointerY;
  14803. },
  14804. enumerable: true,
  14805. configurable: true
  14806. });
  14807. Scene.prototype.getCachedMaterial = function () {
  14808. return this._cachedMaterial;
  14809. };
  14810. Scene.prototype.getBoundingBoxRenderer = function () {
  14811. return this._boundingBoxRenderer;
  14812. };
  14813. Scene.prototype.getOutlineRenderer = function () {
  14814. return this._outlineRenderer;
  14815. };
  14816. Scene.prototype.getEngine = function () {
  14817. return this._engine;
  14818. };
  14819. Scene.prototype.getTotalVertices = function () {
  14820. return this._totalVertices;
  14821. };
  14822. Scene.prototype.getActiveIndices = function () {
  14823. return this._activeIndices;
  14824. };
  14825. Scene.prototype.getActiveParticles = function () {
  14826. return this._activeParticles;
  14827. };
  14828. Scene.prototype.getActiveBones = function () {
  14829. return this._activeBones;
  14830. };
  14831. // Stats
  14832. Scene.prototype.getLastFrameDuration = function () {
  14833. return this._lastFrameDuration;
  14834. };
  14835. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14836. return this._evaluateActiveMeshesDuration;
  14837. };
  14838. Scene.prototype.getActiveMeshes = function () {
  14839. return this._activeMeshes;
  14840. };
  14841. Scene.prototype.getRenderTargetsDuration = function () {
  14842. return this._renderTargetsDuration;
  14843. };
  14844. Scene.prototype.getRenderDuration = function () {
  14845. return this._renderDuration;
  14846. };
  14847. Scene.prototype.getParticlesDuration = function () {
  14848. return this._particlesDuration;
  14849. };
  14850. Scene.prototype.getSpritesDuration = function () {
  14851. return this._spritesDuration;
  14852. };
  14853. Scene.prototype.getAnimationRatio = function () {
  14854. return this._animationRatio;
  14855. };
  14856. Scene.prototype.getRenderId = function () {
  14857. return this._renderId;
  14858. };
  14859. Scene.prototype.incrementRenderId = function () {
  14860. this._renderId++;
  14861. };
  14862. Scene.prototype._updatePointerPosition = function (evt) {
  14863. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14864. this._pointerX = evt.clientX - canvasRect.left;
  14865. this._pointerY = evt.clientY - canvasRect.top;
  14866. this._unTranslatedPointerX = this._pointerX;
  14867. this._unTranslatedPointerY = this._pointerY;
  14868. if (this.cameraToUseForPointers) {
  14869. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14870. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14871. }
  14872. };
  14873. // Pointers handling
  14874. /**
  14875. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14876. * @param attachUp defines if you want to attach events to pointerup
  14877. * @param attachDown defines if you want to attach events to pointerdown
  14878. * @param attachMove defines if you want to attach events to pointermove
  14879. */
  14880. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14881. var _this = this;
  14882. if (attachUp === void 0) { attachUp = true; }
  14883. if (attachDown === void 0) { attachDown = true; }
  14884. if (attachMove === void 0) { attachMove = true; }
  14885. var spritePredicate = function (sprite) {
  14886. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14887. };
  14888. this._onPointerMove = function (evt) {
  14889. _this._updatePointerPosition(evt);
  14890. // PreObservable support
  14891. if (_this.onPrePointerObservable.hasObservers()) {
  14892. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14893. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  14894. _this.onPrePointerObservable.notifyObservers(pi, type);
  14895. if (pi.skipOnPointerObservable) {
  14896. return;
  14897. }
  14898. }
  14899. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14900. return;
  14901. }
  14902. var canvas = _this._engine.getRenderingCanvas();
  14903. if (!_this.pointerMovePredicate) {
  14904. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14905. }
  14906. // Meshes
  14907. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14908. if (pickResult.hit && pickResult.pickedMesh) {
  14909. _this.setPointerOverSprite(null);
  14910. _this.setPointerOverMesh(pickResult.pickedMesh);
  14911. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14912. canvas.style.cursor = "pointer";
  14913. }
  14914. else {
  14915. canvas.style.cursor = "";
  14916. }
  14917. }
  14918. else {
  14919. _this.setPointerOverMesh(null);
  14920. // Sprites
  14921. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14922. if (pickResult.hit && pickResult.pickedSprite) {
  14923. canvas.style.cursor = "pointer";
  14924. _this.setPointerOverSprite(pickResult.pickedSprite);
  14925. }
  14926. else {
  14927. _this.setPointerOverSprite(null);
  14928. // Restore pointer
  14929. canvas.style.cursor = "";
  14930. }
  14931. }
  14932. if (_this.onPointerMove) {
  14933. _this.onPointerMove(evt, pickResult);
  14934. }
  14935. if (_this.onPointerObservable.hasObservers()) {
  14936. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14937. var pi = new PointerInfo(type, evt, pickResult);
  14938. _this.onPointerObservable.notifyObservers(pi, type);
  14939. }
  14940. };
  14941. this._onPointerDown = function (evt) {
  14942. _this._updatePointerPosition(evt);
  14943. // PreObservable support
  14944. if (_this.onPrePointerObservable.hasObservers()) {
  14945. var type = PointerEventTypes.POINTERDOWN;
  14946. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  14947. _this.onPrePointerObservable.notifyObservers(pi, type);
  14948. if (pi.skipOnPointerObservable) {
  14949. return;
  14950. }
  14951. }
  14952. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14953. return;
  14954. }
  14955. _this._startingPointerPosition.x = _this._pointerX;
  14956. _this._startingPointerPosition.y = _this._pointerY;
  14957. _this._startingPointerTime = new Date().getTime();
  14958. if (!_this.pointerDownPredicate) {
  14959. _this.pointerDownPredicate = function (mesh) {
  14960. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14961. };
  14962. }
  14963. // Meshes
  14964. _this._pickedDownMesh = null;
  14965. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14966. if (pickResult.hit && pickResult.pickedMesh) {
  14967. if (pickResult.pickedMesh.actionManager) {
  14968. _this._pickedDownMesh = pickResult.pickedMesh;
  14969. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14970. switch (evt.button) {
  14971. case 0:
  14972. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14973. break;
  14974. case 1:
  14975. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14976. break;
  14977. case 2:
  14978. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14979. break;
  14980. }
  14981. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14982. }
  14983. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14984. var that = _this;
  14985. window.setTimeout(function () {
  14986. 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);
  14987. if (pickResult.hit && pickResult.pickedMesh) {
  14988. if (pickResult.pickedMesh.actionManager) {
  14989. 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)) {
  14990. that._startingPointerTime = 0;
  14991. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14992. }
  14993. }
  14994. }
  14995. }, BABYLON.ActionManager.LongPressDelay);
  14996. }
  14997. }
  14998. }
  14999. if (_this.onPointerDown) {
  15000. _this.onPointerDown(evt, pickResult);
  15001. }
  15002. if (_this.onPointerObservable.hasObservers()) {
  15003. var type = PointerEventTypes.POINTERDOWN;
  15004. var pi = new PointerInfo(type, evt, pickResult);
  15005. _this.onPointerObservable.notifyObservers(pi, type);
  15006. }
  15007. // Sprites
  15008. _this._pickedDownSprite = null;
  15009. if (_this.spriteManagers.length > 0) {
  15010. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15011. if (pickResult.hit && pickResult.pickedSprite) {
  15012. if (pickResult.pickedSprite.actionManager) {
  15013. _this._pickedDownSprite = pickResult.pickedSprite;
  15014. switch (evt.button) {
  15015. case 0:
  15016. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15017. break;
  15018. case 1:
  15019. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15020. break;
  15021. case 2:
  15022. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15023. break;
  15024. }
  15025. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15026. }
  15027. }
  15028. }
  15029. };
  15030. this._onPointerUp = function (evt) {
  15031. _this._updatePointerPosition(evt);
  15032. // PreObservable support
  15033. if (_this.onPrePointerObservable.hasObservers()) {
  15034. var type = PointerEventTypes.POINTERUP;
  15035. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15036. _this.onPrePointerObservable.notifyObservers(pi, type);
  15037. if (pi.skipOnPointerObservable) {
  15038. return;
  15039. }
  15040. }
  15041. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15042. return;
  15043. }
  15044. if (!_this.pointerUpPredicate) {
  15045. _this.pointerUpPredicate = function (mesh) {
  15046. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15047. };
  15048. }
  15049. // Meshes
  15050. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15051. if (pickResult.hit && pickResult.pickedMesh) {
  15052. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15053. if (_this.onPointerPick) {
  15054. _this.onPointerPick(evt, pickResult);
  15055. }
  15056. if (_this.onPointerObservable.hasObservers()) {
  15057. var type = PointerEventTypes.POINTERPICK;
  15058. var pi = new PointerInfo(type, evt, pickResult);
  15059. _this.onPointerObservable.notifyObservers(pi, type);
  15060. }
  15061. }
  15062. if (pickResult.pickedMesh.actionManager) {
  15063. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15064. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15065. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15066. }
  15067. }
  15068. }
  15069. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15070. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15071. }
  15072. if (_this.onPointerUp) {
  15073. _this.onPointerUp(evt, pickResult);
  15074. }
  15075. if (_this.onPointerObservable.hasObservers()) {
  15076. var type = PointerEventTypes.POINTERUP;
  15077. var pi = new PointerInfo(type, evt, pickResult);
  15078. _this.onPointerObservable.notifyObservers(pi, type);
  15079. }
  15080. _this._startingPointerTime = 0;
  15081. // Sprites
  15082. if (_this.spriteManagers.length > 0) {
  15083. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15084. if (pickResult.hit && pickResult.pickedSprite) {
  15085. if (pickResult.pickedSprite.actionManager) {
  15086. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15087. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15088. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15089. }
  15090. }
  15091. }
  15092. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15093. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15094. }
  15095. }
  15096. };
  15097. this._onKeyDown = function (evt) {
  15098. if (_this.actionManager) {
  15099. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15100. }
  15101. };
  15102. this._onKeyUp = function (evt) {
  15103. if (_this.actionManager) {
  15104. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15105. }
  15106. };
  15107. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15108. if (attachMove) {
  15109. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15110. // Wheel
  15111. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  15112. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15113. }
  15114. if (attachDown) {
  15115. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15116. }
  15117. if (attachUp) {
  15118. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15119. }
  15120. BABYLON.Tools.RegisterTopRootEvents([
  15121. { name: "keydown", handler: this._onKeyDown },
  15122. { name: "keyup", handler: this._onKeyUp }
  15123. ]);
  15124. };
  15125. Scene.prototype.detachControl = function () {
  15126. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15127. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  15128. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  15129. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  15130. // Wheel
  15131. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  15132. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  15133. BABYLON.Tools.UnregisterTopRootEvents([
  15134. { name: "keydown", handler: this._onKeyDown },
  15135. { name: "keyup", handler: this._onKeyUp }
  15136. ]);
  15137. };
  15138. // Ready
  15139. Scene.prototype.isReady = function () {
  15140. if (this._pendingData.length > 0) {
  15141. return false;
  15142. }
  15143. var index;
  15144. for (index = 0; index < this._geometries.length; index++) {
  15145. var geometry = this._geometries[index];
  15146. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15147. return false;
  15148. }
  15149. }
  15150. for (index = 0; index < this.meshes.length; index++) {
  15151. var mesh = this.meshes[index];
  15152. if (!mesh.isReady()) {
  15153. return false;
  15154. }
  15155. var mat = mesh.material;
  15156. if (mat) {
  15157. if (!mat.isReady(mesh)) {
  15158. return false;
  15159. }
  15160. }
  15161. }
  15162. return true;
  15163. };
  15164. Scene.prototype.resetCachedMaterial = function () {
  15165. this._cachedMaterial = null;
  15166. };
  15167. Scene.prototype.registerBeforeRender = function (func) {
  15168. this.onBeforeRenderObservable.add(func);
  15169. };
  15170. Scene.prototype.unregisterBeforeRender = function (func) {
  15171. this.onBeforeRenderObservable.removeCallback(func);
  15172. };
  15173. Scene.prototype.registerAfterRender = function (func) {
  15174. this.onAfterRenderObservable.add(func);
  15175. };
  15176. Scene.prototype.unregisterAfterRender = function (func) {
  15177. this.onAfterRenderObservable.removeCallback(func);
  15178. };
  15179. Scene.prototype._addPendingData = function (data) {
  15180. this._pendingData.push(data);
  15181. };
  15182. Scene.prototype._removePendingData = function (data) {
  15183. var index = this._pendingData.indexOf(data);
  15184. if (index !== -1) {
  15185. this._pendingData.splice(index, 1);
  15186. }
  15187. };
  15188. Scene.prototype.getWaitingItemsCount = function () {
  15189. return this._pendingData.length;
  15190. };
  15191. /**
  15192. * Registers a function to be executed when the scene is ready.
  15193. * @param {Function} func - the function to be executed.
  15194. */
  15195. Scene.prototype.executeWhenReady = function (func) {
  15196. var _this = this;
  15197. this.onReadyObservable.add(func);
  15198. if (this._executeWhenReadyTimeoutId !== -1) {
  15199. return;
  15200. }
  15201. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15202. _this._checkIsReady();
  15203. }, 150);
  15204. };
  15205. Scene.prototype._checkIsReady = function () {
  15206. var _this = this;
  15207. if (this.isReady()) {
  15208. this.onReadyObservable.notifyObservers(this);
  15209. this.onReadyObservable.clear();
  15210. this._executeWhenReadyTimeoutId = -1;
  15211. return;
  15212. }
  15213. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15214. _this._checkIsReady();
  15215. }, 150);
  15216. };
  15217. // Animations
  15218. /**
  15219. * Will start the animation sequence of a given target
  15220. * @param target - the target
  15221. * @param {number} from - from which frame should animation start
  15222. * @param {number} to - till which frame should animation run.
  15223. * @param {boolean} [loop] - should the animation loop
  15224. * @param {number} [speedRatio] - the speed in which to run the animation
  15225. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15226. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15227. * @return {BABYLON.Animatable} the animatable object created for this animation
  15228. * @see BABYLON.Animatable
  15229. * @see http://doc.babylonjs.com/page.php?p=22081
  15230. */
  15231. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15232. if (speedRatio === void 0) { speedRatio = 1.0; }
  15233. this.stopAnimation(target);
  15234. if (!animatable) {
  15235. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15236. }
  15237. // Local animations
  15238. if (target.animations) {
  15239. animatable.appendAnimations(target, target.animations);
  15240. }
  15241. // Children animations
  15242. if (target.getAnimatables) {
  15243. var animatables = target.getAnimatables();
  15244. for (var index = 0; index < animatables.length; index++) {
  15245. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15246. }
  15247. }
  15248. animatable.reset();
  15249. return animatable;
  15250. };
  15251. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15252. if (speedRatio === undefined) {
  15253. speedRatio = 1.0;
  15254. }
  15255. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15256. return animatable;
  15257. };
  15258. Scene.prototype.getAnimatableByTarget = function (target) {
  15259. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15260. if (this._activeAnimatables[index].target === target) {
  15261. return this._activeAnimatables[index];
  15262. }
  15263. }
  15264. return null;
  15265. };
  15266. Object.defineProperty(Scene.prototype, "Animatables", {
  15267. get: function () {
  15268. return this._activeAnimatables;
  15269. },
  15270. enumerable: true,
  15271. configurable: true
  15272. });
  15273. /**
  15274. * Will stop the animation of the given target
  15275. * @param target - the target
  15276. * @see beginAnimation
  15277. */
  15278. Scene.prototype.stopAnimation = function (target) {
  15279. var animatable = this.getAnimatableByTarget(target);
  15280. if (animatable) {
  15281. animatable.stop();
  15282. }
  15283. };
  15284. Scene.prototype._animate = function () {
  15285. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15286. return;
  15287. }
  15288. if (!this._animationStartDate) {
  15289. if (this._pendingData.length > 0) {
  15290. return;
  15291. }
  15292. this._animationStartDate = BABYLON.Tools.Now;
  15293. }
  15294. // Getting time
  15295. var now = BABYLON.Tools.Now;
  15296. var delay = now - this._animationStartDate;
  15297. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15298. this._activeAnimatables[index]._animate(delay);
  15299. }
  15300. };
  15301. // Matrix
  15302. Scene.prototype.getViewMatrix = function () {
  15303. return this._viewMatrix;
  15304. };
  15305. Scene.prototype.getProjectionMatrix = function () {
  15306. return this._projectionMatrix;
  15307. };
  15308. Scene.prototype.getTransformMatrix = function () {
  15309. return this._transformMatrix;
  15310. };
  15311. Scene.prototype.setTransformMatrix = function (view, projection) {
  15312. this._viewMatrix = view;
  15313. this._projectionMatrix = projection;
  15314. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15315. };
  15316. // Methods
  15317. Scene.prototype.addMesh = function (newMesh) {
  15318. newMesh.uniqueId = this._uniqueIdCounter++;
  15319. var position = this.meshes.push(newMesh);
  15320. //notify the collision coordinator
  15321. this.collisionCoordinator.onMeshAdded(newMesh);
  15322. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15323. };
  15324. Scene.prototype.removeMesh = function (toRemove) {
  15325. var index = this.meshes.indexOf(toRemove);
  15326. if (index !== -1) {
  15327. // Remove from the scene if mesh found
  15328. this.meshes.splice(index, 1);
  15329. }
  15330. //notify the collision coordinator
  15331. this.collisionCoordinator.onMeshRemoved(toRemove);
  15332. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15333. return index;
  15334. };
  15335. Scene.prototype.removeSkeleton = function (toRemove) {
  15336. var index = this.skeletons.indexOf(toRemove);
  15337. if (index !== -1) {
  15338. // Remove from the scene if mesh found
  15339. this.skeletons.splice(index, 1);
  15340. }
  15341. return index;
  15342. };
  15343. Scene.prototype.removeLight = function (toRemove) {
  15344. var index = this.lights.indexOf(toRemove);
  15345. if (index !== -1) {
  15346. // Remove from the scene if mesh found
  15347. this.lights.splice(index, 1);
  15348. }
  15349. this.onLightRemovedObservable.notifyObservers(toRemove);
  15350. return index;
  15351. };
  15352. Scene.prototype.removeCamera = function (toRemove) {
  15353. var index = this.cameras.indexOf(toRemove);
  15354. if (index !== -1) {
  15355. // Remove from the scene if mesh found
  15356. this.cameras.splice(index, 1);
  15357. }
  15358. // Remove from activeCameras
  15359. var index2 = this.activeCameras.indexOf(toRemove);
  15360. if (index2 !== -1) {
  15361. // Remove from the scene if mesh found
  15362. this.activeCameras.splice(index2, 1);
  15363. }
  15364. // Reset the activeCamera
  15365. if (this.activeCamera === toRemove) {
  15366. if (this.cameras.length > 0) {
  15367. this.activeCamera = this.cameras[0];
  15368. }
  15369. else {
  15370. this.activeCamera = null;
  15371. }
  15372. }
  15373. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15374. return index;
  15375. };
  15376. Scene.prototype.addLight = function (newLight) {
  15377. newLight.uniqueId = this._uniqueIdCounter++;
  15378. var position = this.lights.push(newLight);
  15379. this.onNewLightAddedObservable.notifyObservers(newLight);
  15380. };
  15381. Scene.prototype.addCamera = function (newCamera) {
  15382. newCamera.uniqueId = this._uniqueIdCounter++;
  15383. var position = this.cameras.push(newCamera);
  15384. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15385. };
  15386. /**
  15387. * Switch active camera
  15388. * @param {Camera} newCamera - new active camera
  15389. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15390. */
  15391. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15392. if (attachControl === void 0) { attachControl = true; }
  15393. var canvas = this._engine.getRenderingCanvas();
  15394. this.activeCamera.detachControl(canvas);
  15395. this.activeCamera = newCamera;
  15396. if (attachControl) {
  15397. newCamera.attachControl(canvas);
  15398. }
  15399. };
  15400. /**
  15401. * sets the active camera of the scene using its ID
  15402. * @param {string} id - the camera's ID
  15403. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15404. * @see activeCamera
  15405. */
  15406. Scene.prototype.setActiveCameraByID = function (id) {
  15407. var camera = this.getCameraByID(id);
  15408. if (camera) {
  15409. this.activeCamera = camera;
  15410. return camera;
  15411. }
  15412. return null;
  15413. };
  15414. /**
  15415. * sets the active camera of the scene using its name
  15416. * @param {string} name - the camera's name
  15417. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15418. * @see activeCamera
  15419. */
  15420. Scene.prototype.setActiveCameraByName = function (name) {
  15421. var camera = this.getCameraByName(name);
  15422. if (camera) {
  15423. this.activeCamera = camera;
  15424. return camera;
  15425. }
  15426. return null;
  15427. };
  15428. /**
  15429. * get a material using its id
  15430. * @param {string} the material's ID
  15431. * @return {BABYLON.Material|null} the material or null if none found.
  15432. */
  15433. Scene.prototype.getMaterialByID = function (id) {
  15434. for (var index = 0; index < this.materials.length; index++) {
  15435. if (this.materials[index].id === id) {
  15436. return this.materials[index];
  15437. }
  15438. }
  15439. return null;
  15440. };
  15441. /**
  15442. * get a material using its name
  15443. * @param {string} the material's name
  15444. * @return {BABYLON.Material|null} the material or null if none found.
  15445. */
  15446. Scene.prototype.getMaterialByName = function (name) {
  15447. for (var index = 0; index < this.materials.length; index++) {
  15448. if (this.materials[index].name === name) {
  15449. return this.materials[index];
  15450. }
  15451. }
  15452. return null;
  15453. };
  15454. Scene.prototype.getLensFlareSystemByName = function (name) {
  15455. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15456. if (this.lensFlareSystems[index].name === name) {
  15457. return this.lensFlareSystems[index];
  15458. }
  15459. }
  15460. return null;
  15461. };
  15462. Scene.prototype.getLensFlareSystemByID = function (id) {
  15463. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15464. if (this.lensFlareSystems[index].id === id) {
  15465. return this.lensFlareSystems[index];
  15466. }
  15467. }
  15468. return null;
  15469. };
  15470. Scene.prototype.getCameraByID = function (id) {
  15471. for (var index = 0; index < this.cameras.length; index++) {
  15472. if (this.cameras[index].id === id) {
  15473. return this.cameras[index];
  15474. }
  15475. }
  15476. return null;
  15477. };
  15478. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15479. for (var index = 0; index < this.cameras.length; index++) {
  15480. if (this.cameras[index].uniqueId === uniqueId) {
  15481. return this.cameras[index];
  15482. }
  15483. }
  15484. return null;
  15485. };
  15486. /**
  15487. * get a camera using its name
  15488. * @param {string} the camera's name
  15489. * @return {BABYLON.Camera|null} the camera or null if none found.
  15490. */
  15491. Scene.prototype.getCameraByName = function (name) {
  15492. for (var index = 0; index < this.cameras.length; index++) {
  15493. if (this.cameras[index].name === name) {
  15494. return this.cameras[index];
  15495. }
  15496. }
  15497. return null;
  15498. };
  15499. /**
  15500. * get a bone using its id
  15501. * @param {string} the bone's id
  15502. * @return {BABYLON.Bone|null} the bone or null if not found
  15503. */
  15504. Scene.prototype.getBoneByID = function (id) {
  15505. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15506. var skeleton = this.skeletons[skeletonIndex];
  15507. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15508. if (skeleton.bones[boneIndex].id === id) {
  15509. return skeleton.bones[boneIndex];
  15510. }
  15511. }
  15512. }
  15513. return null;
  15514. };
  15515. /**
  15516. * get a bone using its id
  15517. * @param {string} the bone's name
  15518. * @return {BABYLON.Bone|null} the bone or null if not found
  15519. */
  15520. Scene.prototype.getBoneByName = function (name) {
  15521. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15522. var skeleton = this.skeletons[skeletonIndex];
  15523. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15524. if (skeleton.bones[boneIndex].name === name) {
  15525. return skeleton.bones[boneIndex];
  15526. }
  15527. }
  15528. }
  15529. return null;
  15530. };
  15531. /**
  15532. * get a light node using its name
  15533. * @param {string} the light's name
  15534. * @return {BABYLON.Light|null} the light or null if none found.
  15535. */
  15536. Scene.prototype.getLightByName = function (name) {
  15537. for (var index = 0; index < this.lights.length; index++) {
  15538. if (this.lights[index].name === name) {
  15539. return this.lights[index];
  15540. }
  15541. }
  15542. return null;
  15543. };
  15544. /**
  15545. * get a light node using its ID
  15546. * @param {string} the light's id
  15547. * @return {BABYLON.Light|null} the light or null if none found.
  15548. */
  15549. Scene.prototype.getLightByID = function (id) {
  15550. for (var index = 0; index < this.lights.length; index++) {
  15551. if (this.lights[index].id === id) {
  15552. return this.lights[index];
  15553. }
  15554. }
  15555. return null;
  15556. };
  15557. /**
  15558. * get a light node using its scene-generated unique ID
  15559. * @param {number} the light's unique id
  15560. * @return {BABYLON.Light|null} the light or null if none found.
  15561. */
  15562. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15563. for (var index = 0; index < this.lights.length; index++) {
  15564. if (this.lights[index].uniqueId === uniqueId) {
  15565. return this.lights[index];
  15566. }
  15567. }
  15568. return null;
  15569. };
  15570. /**
  15571. * get a particle system by id
  15572. * @param id {number} the particle system id
  15573. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15574. */
  15575. Scene.prototype.getParticleSystemByID = function (id) {
  15576. for (var index = 0; index < this.particleSystems.length; index++) {
  15577. if (this.particleSystems[index].id === id) {
  15578. return this.particleSystems[index];
  15579. }
  15580. }
  15581. return null;
  15582. };
  15583. /**
  15584. * get a geometry using its ID
  15585. * @param {string} the geometry's id
  15586. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15587. */
  15588. Scene.prototype.getGeometryByID = function (id) {
  15589. for (var index = 0; index < this._geometries.length; index++) {
  15590. if (this._geometries[index].id === id) {
  15591. return this._geometries[index];
  15592. }
  15593. }
  15594. return null;
  15595. };
  15596. /**
  15597. * add a new geometry to this scene.
  15598. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15599. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15600. * @return {boolean} was the geometry added or not
  15601. */
  15602. Scene.prototype.pushGeometry = function (geometry, force) {
  15603. if (!force && this.getGeometryByID(geometry.id)) {
  15604. return false;
  15605. }
  15606. this._geometries.push(geometry);
  15607. //notify the collision coordinator
  15608. this.collisionCoordinator.onGeometryAdded(geometry);
  15609. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15610. return true;
  15611. };
  15612. /**
  15613. * Removes an existing geometry
  15614. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15615. * @return {boolean} was the geometry removed or not
  15616. */
  15617. Scene.prototype.removeGeometry = function (geometry) {
  15618. var index = this._geometries.indexOf(geometry);
  15619. if (index > -1) {
  15620. this._geometries.splice(index, 1);
  15621. //notify the collision coordinator
  15622. this.collisionCoordinator.onGeometryDeleted(geometry);
  15623. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15624. return true;
  15625. }
  15626. return false;
  15627. };
  15628. Scene.prototype.getGeometries = function () {
  15629. return this._geometries;
  15630. };
  15631. /**
  15632. * Get the first added mesh found of a given ID
  15633. * @param {string} id - the id to search for
  15634. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15635. */
  15636. Scene.prototype.getMeshByID = function (id) {
  15637. for (var index = 0; index < this.meshes.length; index++) {
  15638. if (this.meshes[index].id === id) {
  15639. return this.meshes[index];
  15640. }
  15641. }
  15642. return null;
  15643. };
  15644. Scene.prototype.getMeshesByID = function (id) {
  15645. return this.meshes.filter(function (m) {
  15646. return m.id === id;
  15647. });
  15648. };
  15649. /**
  15650. * Get a mesh with its auto-generated unique id
  15651. * @param {number} uniqueId - the unique id to search for
  15652. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15653. */
  15654. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15655. for (var index = 0; index < this.meshes.length; index++) {
  15656. if (this.meshes[index].uniqueId === uniqueId) {
  15657. return this.meshes[index];
  15658. }
  15659. }
  15660. return null;
  15661. };
  15662. /**
  15663. * Get a the last added mesh found of a given ID
  15664. * @param {string} id - the id to search for
  15665. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15666. */
  15667. Scene.prototype.getLastMeshByID = function (id) {
  15668. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15669. if (this.meshes[index].id === id) {
  15670. return this.meshes[index];
  15671. }
  15672. }
  15673. return null;
  15674. };
  15675. /**
  15676. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15677. * @param {string} id - the id to search for
  15678. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15679. */
  15680. Scene.prototype.getLastEntryByID = function (id) {
  15681. var index;
  15682. for (index = this.meshes.length - 1; index >= 0; index--) {
  15683. if (this.meshes[index].id === id) {
  15684. return this.meshes[index];
  15685. }
  15686. }
  15687. for (index = this.cameras.length - 1; index >= 0; index--) {
  15688. if (this.cameras[index].id === id) {
  15689. return this.cameras[index];
  15690. }
  15691. }
  15692. for (index = this.lights.length - 1; index >= 0; index--) {
  15693. if (this.lights[index].id === id) {
  15694. return this.lights[index];
  15695. }
  15696. }
  15697. return null;
  15698. };
  15699. Scene.prototype.getNodeByID = function (id) {
  15700. var mesh = this.getMeshByID(id);
  15701. if (mesh) {
  15702. return mesh;
  15703. }
  15704. var light = this.getLightByID(id);
  15705. if (light) {
  15706. return light;
  15707. }
  15708. var camera = this.getCameraByID(id);
  15709. if (camera) {
  15710. return camera;
  15711. }
  15712. var bone = this.getBoneByID(id);
  15713. return bone;
  15714. };
  15715. Scene.prototype.getNodeByName = function (name) {
  15716. var mesh = this.getMeshByName(name);
  15717. if (mesh) {
  15718. return mesh;
  15719. }
  15720. var light = this.getLightByName(name);
  15721. if (light) {
  15722. return light;
  15723. }
  15724. var camera = this.getCameraByName(name);
  15725. if (camera) {
  15726. return camera;
  15727. }
  15728. var bone = this.getBoneByName(name);
  15729. return bone;
  15730. };
  15731. Scene.prototype.getMeshByName = function (name) {
  15732. for (var index = 0; index < this.meshes.length; index++) {
  15733. if (this.meshes[index].name === name) {
  15734. return this.meshes[index];
  15735. }
  15736. }
  15737. return null;
  15738. };
  15739. Scene.prototype.getSoundByName = function (name) {
  15740. var index;
  15741. if (BABYLON.AudioEngine) {
  15742. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15743. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15744. return this.mainSoundTrack.soundCollection[index];
  15745. }
  15746. }
  15747. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15748. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15749. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15750. return this.soundTracks[sdIndex].soundCollection[index];
  15751. }
  15752. }
  15753. }
  15754. }
  15755. return null;
  15756. };
  15757. Scene.prototype.getLastSkeletonByID = function (id) {
  15758. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15759. if (this.skeletons[index].id === id) {
  15760. return this.skeletons[index];
  15761. }
  15762. }
  15763. return null;
  15764. };
  15765. Scene.prototype.getSkeletonById = function (id) {
  15766. for (var index = 0; index < this.skeletons.length; index++) {
  15767. if (this.skeletons[index].id === id) {
  15768. return this.skeletons[index];
  15769. }
  15770. }
  15771. return null;
  15772. };
  15773. Scene.prototype.getSkeletonByName = function (name) {
  15774. for (var index = 0; index < this.skeletons.length; index++) {
  15775. if (this.skeletons[index].name === name) {
  15776. return this.skeletons[index];
  15777. }
  15778. }
  15779. return null;
  15780. };
  15781. Scene.prototype.isActiveMesh = function (mesh) {
  15782. return (this._activeMeshes.indexOf(mesh) !== -1);
  15783. };
  15784. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15785. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15786. var material = subMesh.getMaterial();
  15787. if (mesh.showSubMeshesBoundingBox) {
  15788. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15789. }
  15790. if (material) {
  15791. // Render targets
  15792. if (material.getRenderTargetTextures) {
  15793. if (this._processedMaterials.indexOf(material) === -1) {
  15794. this._processedMaterials.push(material);
  15795. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15796. }
  15797. }
  15798. // Dispatch
  15799. this._activeIndices += subMesh.indexCount;
  15800. this._renderingManager.dispatch(subMesh);
  15801. }
  15802. }
  15803. };
  15804. Scene.prototype._isInIntermediateRendering = function () {
  15805. return this._intermediateRendering;
  15806. };
  15807. Scene.prototype._evaluateActiveMeshes = function () {
  15808. this.activeCamera._activeMeshes.reset();
  15809. this._activeMeshes.reset();
  15810. this._renderingManager.reset();
  15811. this._processedMaterials.reset();
  15812. this._activeParticleSystems.reset();
  15813. this._activeSkeletons.reset();
  15814. this._softwareSkinnedMeshes.reset();
  15815. this._boundingBoxRenderer.reset();
  15816. this._edgesRenderers.reset();
  15817. if (!this._frustumPlanes) {
  15818. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15819. }
  15820. else {
  15821. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15822. }
  15823. // Meshes
  15824. var meshes;
  15825. var len;
  15826. if (this._selectionOctree) {
  15827. var selection = this._selectionOctree.select(this._frustumPlanes);
  15828. meshes = selection.data;
  15829. len = selection.length;
  15830. }
  15831. else {
  15832. len = this.meshes.length;
  15833. meshes = this.meshes;
  15834. }
  15835. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15836. var mesh = meshes[meshIndex];
  15837. if (mesh.isBlocked) {
  15838. continue;
  15839. }
  15840. this._totalVertices += mesh.getTotalVertices();
  15841. if (!mesh.isReady() || !mesh.isEnabled()) {
  15842. continue;
  15843. }
  15844. mesh.computeWorldMatrix();
  15845. // Intersections
  15846. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15847. this._meshesForIntersections.pushNoDuplicate(mesh);
  15848. }
  15849. // Switch to current LOD
  15850. var meshLOD = mesh.getLOD(this.activeCamera);
  15851. if (!meshLOD) {
  15852. continue;
  15853. }
  15854. mesh._preActivate();
  15855. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15856. this._activeMeshes.push(mesh);
  15857. this.activeCamera._activeMeshes.push(mesh);
  15858. mesh._activate(this._renderId);
  15859. this._activeMesh(meshLOD);
  15860. }
  15861. }
  15862. // Particle systems
  15863. var beforeParticlesDate = BABYLON.Tools.Now;
  15864. if (this.particlesEnabled) {
  15865. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15866. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15867. var particleSystem = this.particleSystems[particleIndex];
  15868. if (!particleSystem.isStarted()) {
  15869. continue;
  15870. }
  15871. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15872. this._activeParticleSystems.push(particleSystem);
  15873. particleSystem.animate();
  15874. }
  15875. }
  15876. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15877. }
  15878. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15879. };
  15880. Scene.prototype._activeMesh = function (mesh) {
  15881. if (mesh.skeleton && this.skeletonsEnabled) {
  15882. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15883. if (!mesh.computeBonesUsingShaders) {
  15884. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15885. }
  15886. }
  15887. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15888. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15889. }
  15890. if (mesh._edgesRenderer) {
  15891. this._edgesRenderers.push(mesh._edgesRenderer);
  15892. }
  15893. if (mesh && mesh.subMeshes) {
  15894. // Submeshes Octrees
  15895. var len;
  15896. var subMeshes;
  15897. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15898. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15899. len = intersections.length;
  15900. subMeshes = intersections.data;
  15901. }
  15902. else {
  15903. subMeshes = mesh.subMeshes;
  15904. len = subMeshes.length;
  15905. }
  15906. for (var subIndex = 0; subIndex < len; subIndex++) {
  15907. var subMesh = subMeshes[subIndex];
  15908. this._evaluateSubMesh(subMesh, mesh);
  15909. }
  15910. }
  15911. };
  15912. Scene.prototype.updateTransformMatrix = function (force) {
  15913. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15914. };
  15915. Scene.prototype._renderForCamera = function (camera) {
  15916. var engine = this._engine;
  15917. this.activeCamera = camera;
  15918. if (!this.activeCamera)
  15919. throw new Error("Active camera not set");
  15920. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15921. // Viewport
  15922. engine.setViewport(this.activeCamera.viewport);
  15923. // Camera
  15924. this.resetCachedMaterial();
  15925. this._renderId++;
  15926. this.updateTransformMatrix();
  15927. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15928. // Meshes
  15929. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15930. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15931. this._evaluateActiveMeshes();
  15932. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15933. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15934. // Skeletons
  15935. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15936. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15937. skeleton.prepare();
  15938. }
  15939. // Software skinning
  15940. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15941. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15942. mesh.applySkeleton(mesh.skeleton);
  15943. }
  15944. // Render targets
  15945. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15946. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15947. this._intermediateRendering = true;
  15948. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15949. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15950. var renderTarget = this._renderTargets.data[renderIndex];
  15951. if (renderTarget._shouldRender()) {
  15952. this._renderId++;
  15953. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15954. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15955. }
  15956. }
  15957. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15958. this._intermediateRendering = false;
  15959. this._renderId++;
  15960. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15961. }
  15962. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15963. // Prepare Frame
  15964. this.postProcessManager._prepareFrame();
  15965. var beforeRenderDate = BABYLON.Tools.Now;
  15966. // Backgrounds
  15967. var layerIndex;
  15968. var layer;
  15969. if (this.layers.length) {
  15970. engine.setDepthBuffer(false);
  15971. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15972. layer = this.layers[layerIndex];
  15973. if (layer.isBackground) {
  15974. layer.render();
  15975. }
  15976. }
  15977. engine.setDepthBuffer(true);
  15978. }
  15979. // Render
  15980. BABYLON.Tools.StartPerformanceCounter("Main render");
  15981. this._renderingManager.render(null, null, true, true);
  15982. BABYLON.Tools.EndPerformanceCounter("Main render");
  15983. // Bounding boxes
  15984. this._boundingBoxRenderer.render();
  15985. // Edges
  15986. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15987. this._edgesRenderers.data[edgesRendererIndex].render();
  15988. }
  15989. // Lens flares
  15990. if (this.lensFlaresEnabled) {
  15991. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15992. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15993. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15994. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15995. lensFlareSystem.render();
  15996. }
  15997. }
  15998. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15999. }
  16000. // Foregrounds
  16001. if (this.layers.length) {
  16002. engine.setDepthBuffer(false);
  16003. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16004. layer = this.layers[layerIndex];
  16005. if (!layer.isBackground) {
  16006. layer.render();
  16007. }
  16008. }
  16009. engine.setDepthBuffer(true);
  16010. }
  16011. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  16012. // Finalize frame
  16013. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16014. // Update camera
  16015. this.activeCamera._updateFromScene();
  16016. // Reset some special arrays
  16017. this._renderTargets.reset();
  16018. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16019. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16020. };
  16021. Scene.prototype._processSubCameras = function (camera) {
  16022. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16023. this._renderForCamera(camera);
  16024. return;
  16025. }
  16026. // rig cameras
  16027. for (var index = 0; index < camera._rigCameras.length; index++) {
  16028. this._renderForCamera(camera._rigCameras[index]);
  16029. }
  16030. this.activeCamera = camera;
  16031. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16032. // Update camera
  16033. this.activeCamera._updateFromScene();
  16034. };
  16035. Scene.prototype._checkIntersections = function () {
  16036. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16037. var sourceMesh = this._meshesForIntersections.data[index];
  16038. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16039. var action = sourceMesh.actionManager.actions[actionIndex];
  16040. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16041. var parameters = action.getTriggerParameter();
  16042. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16043. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16044. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16045. if (areIntersecting && currentIntersectionInProgress === -1) {
  16046. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16047. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16048. sourceMesh._intersectionsInProgress.push(otherMesh);
  16049. }
  16050. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16051. sourceMesh._intersectionsInProgress.push(otherMesh);
  16052. }
  16053. }
  16054. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16055. //They intersected, and now they don't.
  16056. //is this trigger an exit trigger? execute an event.
  16057. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16058. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16059. }
  16060. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16061. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16062. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16063. }
  16064. }
  16065. }
  16066. }
  16067. }
  16068. };
  16069. Scene.prototype.render = function () {
  16070. var startDate = BABYLON.Tools.Now;
  16071. this._particlesDuration = 0;
  16072. this._spritesDuration = 0;
  16073. this._activeParticles = 0;
  16074. this._renderDuration = 0;
  16075. this._renderTargetsDuration = 0;
  16076. this._evaluateActiveMeshesDuration = 0;
  16077. this._totalVertices = 0;
  16078. this._activeIndices = 0;
  16079. this._activeBones = 0;
  16080. this.getEngine().resetDrawCalls();
  16081. this._meshesForIntersections.reset();
  16082. this.resetCachedMaterial();
  16083. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16084. // Actions
  16085. if (this.actionManager) {
  16086. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16087. }
  16088. //Simplification Queue
  16089. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16090. this.simplificationQueue.executeNext();
  16091. }
  16092. // Animations
  16093. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16094. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16095. this._animate();
  16096. // Physics
  16097. if (this._physicsEngine) {
  16098. BABYLON.Tools.StartPerformanceCounter("Physics");
  16099. this._physicsEngine._step(deltaTime / 1000.0);
  16100. BABYLON.Tools.EndPerformanceCounter("Physics");
  16101. }
  16102. // Before render
  16103. this.onBeforeRenderObservable.notifyObservers(this);
  16104. // Customs render targets
  16105. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16106. var engine = this.getEngine();
  16107. var currentActiveCamera = this.activeCamera;
  16108. if (this.renderTargetsEnabled) {
  16109. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16110. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16111. var renderTarget = this.customRenderTargets[customIndex];
  16112. if (renderTarget._shouldRender()) {
  16113. this._renderId++;
  16114. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16115. if (!this.activeCamera)
  16116. throw new Error("Active camera not set");
  16117. // Viewport
  16118. engine.setViewport(this.activeCamera.viewport);
  16119. // Camera
  16120. this.updateTransformMatrix();
  16121. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16122. }
  16123. }
  16124. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16125. this._renderId++;
  16126. }
  16127. if (this.customRenderTargets.length > 0) {
  16128. engine.restoreDefaultFramebuffer();
  16129. }
  16130. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  16131. this.activeCamera = currentActiveCamera;
  16132. // Procedural textures
  16133. if (this.proceduralTexturesEnabled) {
  16134. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16135. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16136. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16137. if (proceduralTexture._shouldRender()) {
  16138. proceduralTexture.render();
  16139. }
  16140. }
  16141. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16142. }
  16143. // Clear
  16144. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16145. // Shadows
  16146. if (this.shadowsEnabled) {
  16147. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16148. var light = this.lights[lightIndex];
  16149. var shadowGenerator = light.getShadowGenerator();
  16150. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16151. this._renderTargets.push(shadowGenerator.getShadowMap());
  16152. }
  16153. }
  16154. }
  16155. // Depth renderer
  16156. if (this._depthRenderer) {
  16157. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16158. }
  16159. // RenderPipeline
  16160. this.postProcessRenderPipelineManager.update();
  16161. // Multi-cameras?
  16162. if (this.activeCameras.length > 0) {
  16163. var currentRenderId = this._renderId;
  16164. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16165. this._renderId = currentRenderId;
  16166. if (cameraIndex > 0) {
  16167. this._engine.clear(0, false, true);
  16168. }
  16169. this._processSubCameras(this.activeCameras[cameraIndex]);
  16170. }
  16171. }
  16172. else {
  16173. if (!this.activeCamera) {
  16174. throw new Error("No camera defined");
  16175. }
  16176. this._processSubCameras(this.activeCamera);
  16177. }
  16178. // Intersection checks
  16179. this._checkIntersections();
  16180. // Update the audio listener attached to the camera
  16181. if (BABYLON.AudioEngine) {
  16182. this._updateAudioParameters();
  16183. }
  16184. // After render
  16185. if (this.afterRender) {
  16186. this.afterRender();
  16187. }
  16188. this.onAfterRenderObservable.notifyObservers(this);
  16189. // Cleaning
  16190. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16191. this._toBeDisposed.data[index].dispose();
  16192. this._toBeDisposed[index] = null;
  16193. }
  16194. this._toBeDisposed.reset();
  16195. if (this.dumpNextRenderTargets) {
  16196. this.dumpNextRenderTargets = false;
  16197. }
  16198. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16199. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  16200. };
  16201. Scene.prototype._updateAudioParameters = function () {
  16202. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16203. return;
  16204. }
  16205. var listeningCamera;
  16206. var audioEngine = BABYLON.Engine.audioEngine;
  16207. if (this.activeCameras.length > 0) {
  16208. listeningCamera = this.activeCameras[0];
  16209. }
  16210. else {
  16211. listeningCamera = this.activeCamera;
  16212. }
  16213. if (listeningCamera && audioEngine.canUseWebAudio) {
  16214. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16215. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16216. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16217. cameraDirection.normalize();
  16218. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16219. var i;
  16220. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16221. var sound = this.mainSoundTrack.soundCollection[i];
  16222. if (sound.useCustomAttenuation) {
  16223. sound.updateDistanceFromListener();
  16224. }
  16225. }
  16226. for (i = 0; i < this.soundTracks.length; i++) {
  16227. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16228. sound = this.soundTracks[i].soundCollection[j];
  16229. if (sound.useCustomAttenuation) {
  16230. sound.updateDistanceFromListener();
  16231. }
  16232. }
  16233. }
  16234. }
  16235. };
  16236. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16237. // Audio
  16238. get: function () {
  16239. return this._audioEnabled;
  16240. },
  16241. set: function (value) {
  16242. this._audioEnabled = value;
  16243. if (BABYLON.AudioEngine) {
  16244. if (this._audioEnabled) {
  16245. this._enableAudio();
  16246. }
  16247. else {
  16248. this._disableAudio();
  16249. }
  16250. }
  16251. },
  16252. enumerable: true,
  16253. configurable: true
  16254. });
  16255. Scene.prototype._disableAudio = function () {
  16256. var i;
  16257. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16258. this.mainSoundTrack.soundCollection[i].pause();
  16259. }
  16260. for (i = 0; i < this.soundTracks.length; i++) {
  16261. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16262. this.soundTracks[i].soundCollection[j].pause();
  16263. }
  16264. }
  16265. };
  16266. Scene.prototype._enableAudio = function () {
  16267. var i;
  16268. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16269. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16270. this.mainSoundTrack.soundCollection[i].play();
  16271. }
  16272. }
  16273. for (i = 0; i < this.soundTracks.length; i++) {
  16274. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16275. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16276. this.soundTracks[i].soundCollection[j].play();
  16277. }
  16278. }
  16279. }
  16280. };
  16281. Object.defineProperty(Scene.prototype, "headphone", {
  16282. get: function () {
  16283. return this._headphone;
  16284. },
  16285. set: function (value) {
  16286. this._headphone = value;
  16287. if (BABYLON.AudioEngine) {
  16288. if (this._headphone) {
  16289. this._switchAudioModeForHeadphones();
  16290. }
  16291. else {
  16292. this._switchAudioModeForNormalSpeakers();
  16293. }
  16294. }
  16295. },
  16296. enumerable: true,
  16297. configurable: true
  16298. });
  16299. Scene.prototype._switchAudioModeForHeadphones = function () {
  16300. this.mainSoundTrack.switchPanningModelToHRTF();
  16301. for (var i = 0; i < this.soundTracks.length; i++) {
  16302. this.soundTracks[i].switchPanningModelToHRTF();
  16303. }
  16304. };
  16305. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16306. this.mainSoundTrack.switchPanningModelToEqualPower();
  16307. for (var i = 0; i < this.soundTracks.length; i++) {
  16308. this.soundTracks[i].switchPanningModelToEqualPower();
  16309. }
  16310. };
  16311. Scene.prototype.enableDepthRenderer = function () {
  16312. if (this._depthRenderer) {
  16313. return this._depthRenderer;
  16314. }
  16315. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16316. return this._depthRenderer;
  16317. };
  16318. Scene.prototype.disableDepthRenderer = function () {
  16319. if (!this._depthRenderer) {
  16320. return;
  16321. }
  16322. this._depthRenderer.dispose();
  16323. this._depthRenderer = null;
  16324. };
  16325. Scene.prototype.freezeMaterials = function () {
  16326. for (var i = 0; i < this.materials.length; i++) {
  16327. this.materials[i].freeze();
  16328. }
  16329. };
  16330. Scene.prototype.unfreezeMaterials = function () {
  16331. for (var i = 0; i < this.materials.length; i++) {
  16332. this.materials[i].unfreeze();
  16333. }
  16334. };
  16335. Scene.prototype.dispose = function () {
  16336. this.beforeRender = null;
  16337. this.afterRender = null;
  16338. this.skeletons = [];
  16339. this._boundingBoxRenderer.dispose();
  16340. if (this._depthRenderer) {
  16341. this._depthRenderer.dispose();
  16342. }
  16343. // Debug layer
  16344. if (this._debugLayer) {
  16345. this._debugLayer.hide();
  16346. }
  16347. // Events
  16348. this.onDisposeObservable.notifyObservers(this);
  16349. this.onDisposeObservable.clear();
  16350. this.onBeforeRenderObservable.clear();
  16351. this.onAfterRenderObservable.clear();
  16352. this.detachControl();
  16353. // Release sounds & sounds tracks
  16354. if (BABYLON.AudioEngine) {
  16355. this.disposeSounds();
  16356. }
  16357. // Detach cameras
  16358. var canvas = this._engine.getRenderingCanvas();
  16359. var index;
  16360. for (index = 0; index < this.cameras.length; index++) {
  16361. this.cameras[index].detachControl(canvas);
  16362. }
  16363. // Release lights
  16364. while (this.lights.length) {
  16365. this.lights[0].dispose();
  16366. }
  16367. // Release meshes
  16368. while (this.meshes.length) {
  16369. this.meshes[0].dispose(true);
  16370. }
  16371. // Release cameras
  16372. while (this.cameras.length) {
  16373. this.cameras[0].dispose();
  16374. }
  16375. // Release materials
  16376. while (this.materials.length) {
  16377. this.materials[0].dispose();
  16378. }
  16379. // Release particles
  16380. while (this.particleSystems.length) {
  16381. this.particleSystems[0].dispose();
  16382. }
  16383. // Release sprites
  16384. while (this.spriteManagers.length) {
  16385. this.spriteManagers[0].dispose();
  16386. }
  16387. // Release layers
  16388. while (this.layers.length) {
  16389. this.layers[0].dispose();
  16390. }
  16391. // Release textures
  16392. while (this.textures.length) {
  16393. this.textures[0].dispose();
  16394. }
  16395. // Post-processes
  16396. this.postProcessManager.dispose();
  16397. // Physics
  16398. if (this._physicsEngine) {
  16399. this.disablePhysicsEngine();
  16400. }
  16401. // Remove from engine
  16402. index = this._engine.scenes.indexOf(this);
  16403. if (index > -1) {
  16404. this._engine.scenes.splice(index, 1);
  16405. }
  16406. this._engine.wipeCaches();
  16407. };
  16408. // Release sounds & sounds tracks
  16409. Scene.prototype.disposeSounds = function () {
  16410. this.mainSoundTrack.dispose();
  16411. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16412. this.soundTracks[scIndex].dispose();
  16413. }
  16414. };
  16415. // Octrees
  16416. Scene.prototype.getWorldExtends = function () {
  16417. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16418. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16419. for (var index = 0; index < this.meshes.length; index++) {
  16420. var mesh = this.meshes[index];
  16421. mesh.computeWorldMatrix(true);
  16422. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16423. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16424. BABYLON.Tools.CheckExtends(minBox, min, max);
  16425. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16426. }
  16427. return {
  16428. min: min,
  16429. max: max
  16430. };
  16431. };
  16432. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16433. if (maxCapacity === void 0) { maxCapacity = 64; }
  16434. if (maxDepth === void 0) { maxDepth = 2; }
  16435. if (!this._selectionOctree) {
  16436. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16437. }
  16438. var worldExtends = this.getWorldExtends();
  16439. // Update octree
  16440. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16441. return this._selectionOctree;
  16442. };
  16443. // Picking
  16444. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16445. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16446. var engine = this._engine;
  16447. if (!camera) {
  16448. if (!this.activeCamera)
  16449. throw new Error("Active camera not set");
  16450. camera = this.activeCamera;
  16451. }
  16452. var cameraViewport = camera.viewport;
  16453. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16454. // Moving coordinates to local viewport world
  16455. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16456. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16457. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16458. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16459. };
  16460. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16461. var engine = this._engine;
  16462. if (!camera) {
  16463. if (!this.activeCamera)
  16464. throw new Error("Active camera not set");
  16465. camera = this.activeCamera;
  16466. }
  16467. var cameraViewport = camera.viewport;
  16468. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16469. var identity = BABYLON.Matrix.Identity();
  16470. // Moving coordinates to local viewport world
  16471. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16472. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16473. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16474. };
  16475. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16476. var pickingInfo = null;
  16477. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16478. var mesh = this.meshes[meshIndex];
  16479. if (predicate) {
  16480. if (!predicate(mesh)) {
  16481. continue;
  16482. }
  16483. }
  16484. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16485. continue;
  16486. }
  16487. var world = mesh.getWorldMatrix();
  16488. var ray = rayFunction(world);
  16489. var result = mesh.intersects(ray, fastCheck);
  16490. if (!result || !result.hit)
  16491. continue;
  16492. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16493. continue;
  16494. pickingInfo = result;
  16495. if (fastCheck) {
  16496. break;
  16497. }
  16498. }
  16499. return pickingInfo || new BABYLON.PickingInfo();
  16500. };
  16501. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16502. var pickingInfo = null;
  16503. camera = camera || this.activeCamera;
  16504. if (this.spriteManagers.length > 0) {
  16505. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16506. var spriteManager = this.spriteManagers[spriteIndex];
  16507. if (!spriteManager.isPickable) {
  16508. continue;
  16509. }
  16510. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16511. if (!result || !result.hit)
  16512. continue;
  16513. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16514. continue;
  16515. pickingInfo = result;
  16516. if (fastCheck) {
  16517. break;
  16518. }
  16519. }
  16520. }
  16521. return pickingInfo || new BABYLON.PickingInfo();
  16522. };
  16523. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16524. var _this = this;
  16525. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16526. /// <param name="x">X position on screen</param>
  16527. /// <param name="y">Y position on screen</param>
  16528. /// <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>
  16529. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16530. /// <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>
  16531. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16532. };
  16533. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16534. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16535. /// <param name="x">X position on screen</param>
  16536. /// <param name="y">Y position on screen</param>
  16537. /// <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>
  16538. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16539. /// <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>
  16540. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16541. };
  16542. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16543. var _this = this;
  16544. return this._internalPick(function (world) {
  16545. if (!_this._pickWithRayInverseMatrix) {
  16546. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16547. }
  16548. world.invertToRef(_this._pickWithRayInverseMatrix);
  16549. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16550. }, predicate, fastCheck);
  16551. };
  16552. Scene.prototype.setPointerOverMesh = function (mesh) {
  16553. if (this._pointerOverMesh === mesh) {
  16554. return;
  16555. }
  16556. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16557. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16558. }
  16559. this._pointerOverMesh = mesh;
  16560. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16561. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16562. }
  16563. };
  16564. Scene.prototype.getPointerOverMesh = function () {
  16565. return this._pointerOverMesh;
  16566. };
  16567. Scene.prototype.setPointerOverSprite = function (sprite) {
  16568. if (this._pointerOverSprite === sprite) {
  16569. return;
  16570. }
  16571. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16572. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16573. }
  16574. this._pointerOverSprite = sprite;
  16575. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16576. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16577. }
  16578. };
  16579. Scene.prototype.getPointerOverSprite = function () {
  16580. return this._pointerOverSprite;
  16581. };
  16582. // Physics
  16583. Scene.prototype.getPhysicsEngine = function () {
  16584. return this._physicsEngine;
  16585. };
  16586. /**
  16587. * Enables physics to the current scene
  16588. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16589. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16590. * @return {boolean} was the physics engine initialized
  16591. */
  16592. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16593. if (this._physicsEngine) {
  16594. return true;
  16595. }
  16596. try {
  16597. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16598. return true;
  16599. }
  16600. catch (e) {
  16601. BABYLON.Tools.Error(e.message);
  16602. return false;
  16603. }
  16604. };
  16605. Scene.prototype.disablePhysicsEngine = function () {
  16606. if (!this._physicsEngine) {
  16607. return;
  16608. }
  16609. this._physicsEngine.dispose();
  16610. this._physicsEngine = undefined;
  16611. };
  16612. Scene.prototype.isPhysicsEnabled = function () {
  16613. return this._physicsEngine !== undefined;
  16614. };
  16615. /**
  16616. *
  16617. * Sets the gravity of the physics engine (and NOT of the scene)
  16618. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16619. */
  16620. Scene.prototype.setGravity = function (gravity) {
  16621. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16622. if (!this._physicsEngine) {
  16623. return;
  16624. }
  16625. this._physicsEngine.setGravity(gravity);
  16626. };
  16627. /**
  16628. * Legacy support, using the new API
  16629. * @Deprecated
  16630. */
  16631. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16632. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16633. if (parts.parts) {
  16634. options = parts;
  16635. parts = parts.parts;
  16636. }
  16637. var mainMesh = parts[0].mesh;
  16638. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16639. for (var index = 1; index < parts.length; index++) {
  16640. var mesh = parts[index].mesh;
  16641. if (mesh.parent !== mainMesh) {
  16642. mesh.position = mesh.position.subtract(mainMesh.position);
  16643. mesh.parent = mainMesh;
  16644. }
  16645. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16646. }
  16647. mainMesh.physicsImpostor.forceUpdate();
  16648. };
  16649. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16650. var mesh = compound.parts[0].mesh;
  16651. mesh.physicsImpostor.dispose();
  16652. mesh.physicsImpostor = null;
  16653. };
  16654. // Misc.
  16655. Scene.prototype.createDefaultCameraOrLight = function () {
  16656. // Light
  16657. if (this.lights.length === 0) {
  16658. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16659. }
  16660. // Camera
  16661. if (!this.activeCamera) {
  16662. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16663. // Compute position
  16664. var worldExtends = this.getWorldExtends();
  16665. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16666. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16667. camera.setTarget(worldCenter);
  16668. this.activeCamera = camera;
  16669. }
  16670. };
  16671. // Tags
  16672. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16673. if (tagsQuery === undefined) {
  16674. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16675. return list;
  16676. }
  16677. var listByTags = [];
  16678. forEach = forEach || (function (item) { return; });
  16679. for (var i in list) {
  16680. var item = list[i];
  16681. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16682. listByTags.push(item);
  16683. forEach(item);
  16684. }
  16685. }
  16686. return listByTags;
  16687. };
  16688. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16689. return this._getByTags(this.meshes, tagsQuery, forEach);
  16690. };
  16691. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16692. return this._getByTags(this.cameras, tagsQuery, forEach);
  16693. };
  16694. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16695. return this._getByTags(this.lights, tagsQuery, forEach);
  16696. };
  16697. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16698. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16699. };
  16700. // Statics
  16701. Scene._FOGMODE_NONE = 0;
  16702. Scene._FOGMODE_EXP = 1;
  16703. Scene._FOGMODE_EXP2 = 2;
  16704. Scene._FOGMODE_LINEAR = 3;
  16705. Scene.MinDeltaTime = 1.0;
  16706. Scene.MaxDeltaTime = 1000.0;
  16707. return Scene;
  16708. })();
  16709. BABYLON.Scene = Scene;
  16710. })(BABYLON || (BABYLON = {}));
  16711. var BABYLON;
  16712. (function (BABYLON) {
  16713. var VertexBuffer = (function () {
  16714. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16715. if (engine instanceof BABYLON.Mesh) {
  16716. this._engine = engine.getScene().getEngine();
  16717. }
  16718. else {
  16719. this._engine = engine;
  16720. }
  16721. this._updatable = updatable;
  16722. this._data = data;
  16723. if (!postponeInternalCreation) {
  16724. this.create();
  16725. }
  16726. this._kind = kind;
  16727. if (stride) {
  16728. this._strideSize = stride;
  16729. return;
  16730. }
  16731. // Deduce stride from kind
  16732. switch (kind) {
  16733. case VertexBuffer.PositionKind:
  16734. this._strideSize = 3;
  16735. break;
  16736. case VertexBuffer.NormalKind:
  16737. this._strideSize = 3;
  16738. break;
  16739. case VertexBuffer.UVKind:
  16740. case VertexBuffer.UV2Kind:
  16741. case VertexBuffer.UV3Kind:
  16742. case VertexBuffer.UV4Kind:
  16743. case VertexBuffer.UV5Kind:
  16744. case VertexBuffer.UV6Kind:
  16745. this._strideSize = 2;
  16746. break;
  16747. case VertexBuffer.ColorKind:
  16748. this._strideSize = 4;
  16749. break;
  16750. case VertexBuffer.MatricesIndicesKind:
  16751. case VertexBuffer.MatricesIndicesExtraKind:
  16752. this._strideSize = 4;
  16753. break;
  16754. case VertexBuffer.MatricesWeightsKind:
  16755. case VertexBuffer.MatricesWeightsExtraKind:
  16756. this._strideSize = 4;
  16757. break;
  16758. }
  16759. }
  16760. // Properties
  16761. VertexBuffer.prototype.isUpdatable = function () {
  16762. return this._updatable;
  16763. };
  16764. VertexBuffer.prototype.getData = function () {
  16765. return this._data;
  16766. };
  16767. VertexBuffer.prototype.getBuffer = function () {
  16768. return this._buffer;
  16769. };
  16770. VertexBuffer.prototype.getStrideSize = function () {
  16771. return this._strideSize;
  16772. };
  16773. // Methods
  16774. VertexBuffer.prototype.create = function (data) {
  16775. if (!data && this._buffer) {
  16776. return; // nothing to do
  16777. }
  16778. data = data || this._data;
  16779. if (!this._buffer) {
  16780. if (this._updatable) {
  16781. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16782. }
  16783. else {
  16784. this._buffer = this._engine.createVertexBuffer(data);
  16785. }
  16786. }
  16787. if (this._updatable) {
  16788. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16789. this._data = data;
  16790. }
  16791. };
  16792. VertexBuffer.prototype.update = function (data) {
  16793. this.create(data);
  16794. };
  16795. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16796. if (!this._buffer) {
  16797. return;
  16798. }
  16799. if (this._updatable) {
  16800. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16801. this._data = null;
  16802. }
  16803. };
  16804. VertexBuffer.prototype.dispose = function () {
  16805. if (!this._buffer) {
  16806. return;
  16807. }
  16808. if (this._engine._releaseBuffer(this._buffer)) {
  16809. this._buffer = null;
  16810. }
  16811. };
  16812. Object.defineProperty(VertexBuffer, "PositionKind", {
  16813. get: function () {
  16814. return VertexBuffer._PositionKind;
  16815. },
  16816. enumerable: true,
  16817. configurable: true
  16818. });
  16819. Object.defineProperty(VertexBuffer, "NormalKind", {
  16820. get: function () {
  16821. return VertexBuffer._NormalKind;
  16822. },
  16823. enumerable: true,
  16824. configurable: true
  16825. });
  16826. Object.defineProperty(VertexBuffer, "UVKind", {
  16827. get: function () {
  16828. return VertexBuffer._UVKind;
  16829. },
  16830. enumerable: true,
  16831. configurable: true
  16832. });
  16833. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16834. get: function () {
  16835. return VertexBuffer._UV2Kind;
  16836. },
  16837. enumerable: true,
  16838. configurable: true
  16839. });
  16840. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16841. get: function () {
  16842. return VertexBuffer._UV3Kind;
  16843. },
  16844. enumerable: true,
  16845. configurable: true
  16846. });
  16847. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16848. get: function () {
  16849. return VertexBuffer._UV4Kind;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16855. get: function () {
  16856. return VertexBuffer._UV5Kind;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16862. get: function () {
  16863. return VertexBuffer._UV6Kind;
  16864. },
  16865. enumerable: true,
  16866. configurable: true
  16867. });
  16868. Object.defineProperty(VertexBuffer, "ColorKind", {
  16869. get: function () {
  16870. return VertexBuffer._ColorKind;
  16871. },
  16872. enumerable: true,
  16873. configurable: true
  16874. });
  16875. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16876. get: function () {
  16877. return VertexBuffer._MatricesIndicesKind;
  16878. },
  16879. enumerable: true,
  16880. configurable: true
  16881. });
  16882. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16883. get: function () {
  16884. return VertexBuffer._MatricesWeightsKind;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16890. get: function () {
  16891. return VertexBuffer._MatricesIndicesExtraKind;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16897. get: function () {
  16898. return VertexBuffer._MatricesWeightsExtraKind;
  16899. },
  16900. enumerable: true,
  16901. configurable: true
  16902. });
  16903. // Enums
  16904. VertexBuffer._PositionKind = "position";
  16905. VertexBuffer._NormalKind = "normal";
  16906. VertexBuffer._UVKind = "uv";
  16907. VertexBuffer._UV2Kind = "uv2";
  16908. VertexBuffer._UV3Kind = "uv3";
  16909. VertexBuffer._UV4Kind = "uv4";
  16910. VertexBuffer._UV5Kind = "uv5";
  16911. VertexBuffer._UV6Kind = "uv6";
  16912. VertexBuffer._ColorKind = "color";
  16913. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16914. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16915. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16916. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16917. return VertexBuffer;
  16918. })();
  16919. BABYLON.VertexBuffer = VertexBuffer;
  16920. })(BABYLON || (BABYLON = {}));
  16921. var BABYLON;
  16922. (function (BABYLON) {
  16923. /**
  16924. * Creates an instance based on a source mesh.
  16925. */
  16926. var InstancedMesh = (function (_super) {
  16927. __extends(InstancedMesh, _super);
  16928. function InstancedMesh(name, source) {
  16929. _super.call(this, name, source.getScene());
  16930. source.instances.push(this);
  16931. this._sourceMesh = source;
  16932. this.position.copyFrom(source.position);
  16933. this.rotation.copyFrom(source.rotation);
  16934. this.scaling.copyFrom(source.scaling);
  16935. if (source.rotationQuaternion) {
  16936. this.rotationQuaternion = source.rotationQuaternion.clone();
  16937. }
  16938. this.infiniteDistance = source.infiniteDistance;
  16939. this.setPivotMatrix(source.getPivotMatrix());
  16940. this.refreshBoundingInfo();
  16941. this._syncSubMeshes();
  16942. }
  16943. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16944. // Methods
  16945. get: function () {
  16946. return this._sourceMesh.receiveShadows;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(InstancedMesh.prototype, "material", {
  16952. get: function () {
  16953. return this._sourceMesh.material;
  16954. },
  16955. enumerable: true,
  16956. configurable: true
  16957. });
  16958. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16959. get: function () {
  16960. return this._sourceMesh.visibility;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16966. get: function () {
  16967. return this._sourceMesh.skeleton;
  16968. },
  16969. enumerable: true,
  16970. configurable: true
  16971. });
  16972. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16973. get: function () {
  16974. return this._sourceMesh.renderingGroupId;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. InstancedMesh.prototype.getTotalVertices = function () {
  16980. return this._sourceMesh.getTotalVertices();
  16981. };
  16982. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16983. get: function () {
  16984. return this._sourceMesh;
  16985. },
  16986. enumerable: true,
  16987. configurable: true
  16988. });
  16989. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16990. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16991. };
  16992. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16993. return this._sourceMesh.isVerticesDataPresent(kind);
  16994. };
  16995. InstancedMesh.prototype.getIndices = function () {
  16996. return this._sourceMesh.getIndices();
  16997. };
  16998. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16999. get: function () {
  17000. return this._sourceMesh._positions;
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17006. var meshBB = this._sourceMesh.getBoundingInfo();
  17007. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17008. this._updateBoundingInfo();
  17009. };
  17010. InstancedMesh.prototype._preActivate = function () {
  17011. if (this._currentLOD) {
  17012. this._currentLOD._preActivate();
  17013. }
  17014. };
  17015. InstancedMesh.prototype._activate = function (renderId) {
  17016. if (this._currentLOD) {
  17017. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17018. }
  17019. };
  17020. InstancedMesh.prototype.getLOD = function (camera) {
  17021. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17022. if (this._currentLOD === this.sourceMesh) {
  17023. return this;
  17024. }
  17025. return this._currentLOD;
  17026. };
  17027. InstancedMesh.prototype._syncSubMeshes = function () {
  17028. this.releaseSubMeshes();
  17029. if (this._sourceMesh.subMeshes) {
  17030. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17031. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17032. }
  17033. }
  17034. };
  17035. InstancedMesh.prototype._generatePointsArray = function () {
  17036. return this._sourceMesh._generatePointsArray();
  17037. };
  17038. // Clone
  17039. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17040. var result = this._sourceMesh.createInstance(name);
  17041. // Deep copy
  17042. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17043. // Bounding info
  17044. this.refreshBoundingInfo();
  17045. // Parent
  17046. if (newParent) {
  17047. result.parent = newParent;
  17048. }
  17049. if (!doNotCloneChildren) {
  17050. // Children
  17051. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17052. var mesh = this.getScene().meshes[index];
  17053. if (mesh.parent === this) {
  17054. mesh.clone(mesh.name, result);
  17055. }
  17056. }
  17057. }
  17058. result.computeWorldMatrix(true);
  17059. return result;
  17060. };
  17061. // Dispoe
  17062. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17063. // Remove from mesh
  17064. var index = this._sourceMesh.instances.indexOf(this);
  17065. this._sourceMesh.instances.splice(index, 1);
  17066. _super.prototype.dispose.call(this, doNotRecurse);
  17067. };
  17068. return InstancedMesh;
  17069. })(BABYLON.AbstractMesh);
  17070. BABYLON.InstancedMesh = InstancedMesh;
  17071. })(BABYLON || (BABYLON = {}));
  17072. var BABYLON;
  17073. (function (BABYLON) {
  17074. var _InstancesBatch = (function () {
  17075. function _InstancesBatch() {
  17076. this.mustReturn = false;
  17077. this.visibleInstances = new Array();
  17078. this.renderSelf = new Array();
  17079. }
  17080. return _InstancesBatch;
  17081. })();
  17082. BABYLON._InstancesBatch = _InstancesBatch;
  17083. var Mesh = (function (_super) {
  17084. __extends(Mesh, _super);
  17085. /**
  17086. * @constructor
  17087. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  17088. * @param {Scene} scene - The scene to add this mesh to.
  17089. * @param {Node} parent - The parent of this mesh, if it has one
  17090. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  17091. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  17092. * When false, achieved by calling a clone(), also passing False.
  17093. * This will make creation of children, recursive.
  17094. */
  17095. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17096. if (parent === void 0) { parent = null; }
  17097. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17098. _super.call(this, name, scene);
  17099. // Events
  17100. /**
  17101. * An event triggered before rendering the mesh
  17102. * @type {BABYLON.Observable}
  17103. */
  17104. this.onBeforeRenderObservable = new BABYLON.Observable();
  17105. /**
  17106. * An event triggered after rendering the mesh
  17107. * @type {BABYLON.Observable}
  17108. */
  17109. this.onAfterRenderObservable = new BABYLON.Observable();
  17110. /**
  17111. * An event triggered before drawing the mesh
  17112. * @type {BABYLON.Observable}
  17113. */
  17114. this.onBeforeDrawObservable = new BABYLON.Observable();
  17115. // Members
  17116. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17117. this.instances = new Array();
  17118. this._LODLevels = new Array();
  17119. this._visibleInstances = {};
  17120. this._renderIdForInstances = new Array();
  17121. this._batchCache = new _InstancesBatch();
  17122. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17123. this._sideOrientation = Mesh._DEFAULTSIDE;
  17124. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17125. if (source) {
  17126. // Geometry
  17127. if (source._geometry) {
  17128. source._geometry.applyToMesh(this);
  17129. }
  17130. // Deep copy
  17131. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17132. // Pivot
  17133. this.setPivotMatrix(source.getPivotMatrix());
  17134. this.id = name + "." + source.id;
  17135. // Material
  17136. this.material = source.material;
  17137. var index;
  17138. if (!doNotCloneChildren) {
  17139. // Children
  17140. for (index = 0; index < scene.meshes.length; index++) {
  17141. var mesh = scene.meshes[index];
  17142. if (mesh.parent === source) {
  17143. // doNotCloneChildren is always going to be False
  17144. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17145. }
  17146. }
  17147. }
  17148. // Physics clone
  17149. var physicsEngine = this.getScene().getPhysicsEngine();
  17150. if (clonePhysicsImpostor && physicsEngine) {
  17151. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17152. if (impostor) {
  17153. this.physicsImpostor = impostor.clone(this);
  17154. }
  17155. }
  17156. // Particles
  17157. for (index = 0; index < scene.particleSystems.length; index++) {
  17158. var system = scene.particleSystems[index];
  17159. if (system.emitter === source) {
  17160. system.clone(system.name, this);
  17161. }
  17162. }
  17163. this.computeWorldMatrix(true);
  17164. }
  17165. // Parent
  17166. if (parent !== null) {
  17167. this.parent = parent;
  17168. }
  17169. }
  17170. Object.defineProperty(Mesh, "FRONTSIDE", {
  17171. /**
  17172. * Mesh side orientation : usually the external or front surface
  17173. */
  17174. get: function () {
  17175. return Mesh._FRONTSIDE;
  17176. },
  17177. enumerable: true,
  17178. configurable: true
  17179. });
  17180. Object.defineProperty(Mesh, "BACKSIDE", {
  17181. /**
  17182. * Mesh side orientation : usually the internal or back surface
  17183. */
  17184. get: function () {
  17185. return Mesh._BACKSIDE;
  17186. },
  17187. enumerable: true,
  17188. configurable: true
  17189. });
  17190. Object.defineProperty(Mesh, "DOUBLESIDE", {
  17191. /**
  17192. * Mesh side orientation : both internal and external or front and back surfaces
  17193. */
  17194. get: function () {
  17195. return Mesh._DOUBLESIDE;
  17196. },
  17197. enumerable: true,
  17198. configurable: true
  17199. });
  17200. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  17201. /**
  17202. * Mesh side orientation : by default, `FRONTSIDE`
  17203. */
  17204. get: function () {
  17205. return Mesh._DEFAULTSIDE;
  17206. },
  17207. enumerable: true,
  17208. configurable: true
  17209. });
  17210. Object.defineProperty(Mesh, "NO_CAP", {
  17211. /**
  17212. * Mesh cap setting : no cap
  17213. */
  17214. get: function () {
  17215. return Mesh._NO_CAP;
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. Object.defineProperty(Mesh, "CAP_START", {
  17221. /**
  17222. * Mesh cap setting : one cap at the beginning of the mesh
  17223. */
  17224. get: function () {
  17225. return Mesh._CAP_START;
  17226. },
  17227. enumerable: true,
  17228. configurable: true
  17229. });
  17230. Object.defineProperty(Mesh, "CAP_END", {
  17231. /**
  17232. * Mesh cap setting : one cap at the end of the mesh
  17233. */
  17234. get: function () {
  17235. return Mesh._CAP_END;
  17236. },
  17237. enumerable: true,
  17238. configurable: true
  17239. });
  17240. Object.defineProperty(Mesh, "CAP_ALL", {
  17241. /**
  17242. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  17243. */
  17244. get: function () {
  17245. return Mesh._CAP_ALL;
  17246. },
  17247. enumerable: true,
  17248. configurable: true
  17249. });
  17250. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  17251. set: function (callback) {
  17252. if (this._onBeforeDrawObserver) {
  17253. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  17254. }
  17255. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  17256. },
  17257. enumerable: true,
  17258. configurable: true
  17259. });
  17260. // Methods
  17261. /**
  17262. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17263. */
  17264. Mesh.prototype.toString = function (fullDetails) {
  17265. var ret = _super.prototype.toString.call(this, fullDetails);
  17266. ret += ", n vertices: " + this.getTotalVertices();
  17267. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  17268. if (this.animations) {
  17269. for (var i = 0; i < this.animations.length; i++) {
  17270. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17271. }
  17272. }
  17273. if (fullDetails) {
  17274. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  17275. }
  17276. return ret;
  17277. };
  17278. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  17279. get: function () {
  17280. return this._LODLevels.length > 0;
  17281. },
  17282. enumerable: true,
  17283. configurable: true
  17284. });
  17285. Mesh.prototype._sortLODLevels = function () {
  17286. this._LODLevels.sort(function (a, b) {
  17287. if (a.distance < b.distance) {
  17288. return 1;
  17289. }
  17290. if (a.distance > b.distance) {
  17291. return -1;
  17292. }
  17293. return 0;
  17294. });
  17295. };
  17296. /**
  17297. * Add a mesh as LOD level triggered at the given distance.
  17298. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17299. * @param {number} distance - the distance from the center of the object to show this level
  17300. * @param {Mesh} mesh - the mesh to be added as LOD level
  17301. * @return {Mesh} this mesh (for chaining)
  17302. */
  17303. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17304. if (mesh && mesh._masterMesh) {
  17305. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17306. return this;
  17307. }
  17308. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17309. this._LODLevels.push(level);
  17310. if (mesh) {
  17311. mesh._masterMesh = this;
  17312. }
  17313. this._sortLODLevels();
  17314. return this;
  17315. };
  17316. /**
  17317. * Returns the LOD level mesh at the passed distance or null if not found.
  17318. * It is related to the method `addLODLevel(distance, mesh)`.
  17319. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17320. */
  17321. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17322. for (var index = 0; index < this._LODLevels.length; index++) {
  17323. var level = this._LODLevels[index];
  17324. if (level.distance === distance) {
  17325. return level.mesh;
  17326. }
  17327. }
  17328. return null;
  17329. };
  17330. /**
  17331. * Remove a mesh from the LOD array
  17332. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17333. * @param {Mesh} mesh - the mesh to be removed.
  17334. * @return {Mesh} this mesh (for chaining)
  17335. */
  17336. Mesh.prototype.removeLODLevel = function (mesh) {
  17337. for (var index = 0; index < this._LODLevels.length; index++) {
  17338. if (this._LODLevels[index].mesh === mesh) {
  17339. this._LODLevels.splice(index, 1);
  17340. if (mesh) {
  17341. mesh._masterMesh = null;
  17342. }
  17343. }
  17344. }
  17345. this._sortLODLevels();
  17346. return this;
  17347. };
  17348. /**
  17349. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17350. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17351. */
  17352. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17353. if (!this._LODLevels || this._LODLevels.length === 0) {
  17354. return this;
  17355. }
  17356. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17357. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17358. if (this.onLODLevelSelection) {
  17359. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17360. }
  17361. return this;
  17362. }
  17363. for (var index = 0; index < this._LODLevels.length; index++) {
  17364. var level = this._LODLevels[index];
  17365. if (level.distance < distanceToCamera) {
  17366. if (level.mesh) {
  17367. level.mesh._preActivate();
  17368. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17369. }
  17370. if (this.onLODLevelSelection) {
  17371. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17372. }
  17373. return level.mesh;
  17374. }
  17375. }
  17376. if (this.onLODLevelSelection) {
  17377. this.onLODLevelSelection(distanceToCamera, this, this);
  17378. }
  17379. return this;
  17380. };
  17381. Object.defineProperty(Mesh.prototype, "geometry", {
  17382. /**
  17383. * Returns the mesh internal `Geometry` object.
  17384. */
  17385. get: function () {
  17386. return this._geometry;
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. /**
  17392. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17393. */
  17394. Mesh.prototype.getTotalVertices = function () {
  17395. if (!this._geometry) {
  17396. return 0;
  17397. }
  17398. return this._geometry.getTotalVertices();
  17399. };
  17400. /**
  17401. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17402. * 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.
  17403. * Returns null if the mesh has no geometry or no vertex buffer.
  17404. * Possible `kind` values :
  17405. * - BABYLON.VertexBuffer.PositionKind
  17406. * - BABYLON.VertexBuffer.UVKind
  17407. * - BABYLON.VertexBuffer.UV2Kind
  17408. * - BABYLON.VertexBuffer.UV3Kind
  17409. * - BABYLON.VertexBuffer.UV4Kind
  17410. * - BABYLON.VertexBuffer.UV5Kind
  17411. * - BABYLON.VertexBuffer.UV6Kind
  17412. * - BABYLON.VertexBuffer.ColorKind
  17413. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17414. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17415. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17416. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17417. */
  17418. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17419. if (!this._geometry) {
  17420. return null;
  17421. }
  17422. return this._geometry.getVerticesData(kind, copyWhenShared);
  17423. };
  17424. /**
  17425. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17426. * Returns `undefined` if the mesh has no geometry.
  17427. * Possible `kind` values :
  17428. * - BABYLON.VertexBuffer.PositionKind
  17429. * - BABYLON.VertexBuffer.UVKind
  17430. * - BABYLON.VertexBuffer.UV2Kind
  17431. * - BABYLON.VertexBuffer.UV3Kind
  17432. * - BABYLON.VertexBuffer.UV4Kind
  17433. * - BABYLON.VertexBuffer.UV5Kind
  17434. * - BABYLON.VertexBuffer.UV6Kind
  17435. * - BABYLON.VertexBuffer.ColorKind
  17436. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17437. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17438. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17439. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17440. */
  17441. Mesh.prototype.getVertexBuffer = function (kind) {
  17442. if (!this._geometry) {
  17443. return undefined;
  17444. }
  17445. return this._geometry.getVertexBuffer(kind);
  17446. };
  17447. /**
  17448. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17449. * Possible `kind` values :
  17450. * - BABYLON.VertexBuffer.PositionKind
  17451. * - BABYLON.VertexBuffer.UVKind
  17452. * - BABYLON.VertexBuffer.UV2Kind
  17453. * - BABYLON.VertexBuffer.UV3Kind
  17454. * - BABYLON.VertexBuffer.UV4Kind
  17455. * - BABYLON.VertexBuffer.UV5Kind
  17456. * - BABYLON.VertexBuffer.UV6Kind
  17457. * - BABYLON.VertexBuffer.ColorKind
  17458. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17459. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17460. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17461. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17462. */
  17463. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17464. if (!this._geometry) {
  17465. if (this._delayInfo) {
  17466. return this._delayInfo.indexOf(kind) !== -1;
  17467. }
  17468. return false;
  17469. }
  17470. return this._geometry.isVerticesDataPresent(kind);
  17471. };
  17472. /**
  17473. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17474. * Possible `kind` values :
  17475. * - BABYLON.VertexBuffer.PositionKind
  17476. * - BABYLON.VertexBuffer.UVKind
  17477. * - BABYLON.VertexBuffer.UV2Kind
  17478. * - BABYLON.VertexBuffer.UV3Kind
  17479. * - BABYLON.VertexBuffer.UV4Kind
  17480. * - BABYLON.VertexBuffer.UV5Kind
  17481. * - BABYLON.VertexBuffer.UV6Kind
  17482. * - BABYLON.VertexBuffer.ColorKind
  17483. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17484. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17485. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17486. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17487. */
  17488. Mesh.prototype.getVerticesDataKinds = function () {
  17489. if (!this._geometry) {
  17490. var result = [];
  17491. if (this._delayInfo) {
  17492. for (var kind in this._delayInfo) {
  17493. result.push(kind);
  17494. }
  17495. }
  17496. return result;
  17497. }
  17498. return this._geometry.getVerticesDataKinds();
  17499. };
  17500. /**
  17501. * Returns a positive integer : the total number of indices in this mesh geometry.
  17502. * Returns zero if the mesh has no geometry.
  17503. */
  17504. Mesh.prototype.getTotalIndices = function () {
  17505. if (!this._geometry) {
  17506. return 0;
  17507. }
  17508. return this._geometry.getTotalIndices();
  17509. };
  17510. /**
  17511. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17512. * 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.
  17513. * Returns an empty array if the mesh has no geometry.
  17514. */
  17515. Mesh.prototype.getIndices = function (copyWhenShared) {
  17516. if (!this._geometry) {
  17517. return [];
  17518. }
  17519. return this._geometry.getIndices(copyWhenShared);
  17520. };
  17521. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17522. get: function () {
  17523. return this._masterMesh !== null && this._masterMesh !== undefined;
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. /**
  17529. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17530. */
  17531. Mesh.prototype.isReady = function () {
  17532. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17533. return false;
  17534. }
  17535. return _super.prototype.isReady.call(this);
  17536. };
  17537. /**
  17538. * Boolean : true if the mesh has been disposed.
  17539. */
  17540. Mesh.prototype.isDisposed = function () {
  17541. return this._isDisposed;
  17542. };
  17543. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17544. get: function () {
  17545. return this._sideOrientation;
  17546. },
  17547. /**
  17548. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17549. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17550. */
  17551. set: function (sideO) {
  17552. this._sideOrientation = sideO;
  17553. },
  17554. enumerable: true,
  17555. configurable: true
  17556. });
  17557. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17558. /**
  17559. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17560. * This property is pertinent only for updatable parametric shapes.
  17561. */
  17562. get: function () {
  17563. return this._areNormalsFrozen;
  17564. },
  17565. enumerable: true,
  17566. configurable: true
  17567. });
  17568. /**
  17569. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17570. * It has no effect at all on other shapes.
  17571. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17572. */
  17573. Mesh.prototype.freezeNormals = function () {
  17574. this._areNormalsFrozen = true;
  17575. };
  17576. /**
  17577. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17578. * It has no effect at all on other shapes.
  17579. * It reactivates the mesh normals computation if it was previously frozen.
  17580. */
  17581. Mesh.prototype.unfreezeNormals = function () {
  17582. this._areNormalsFrozen = false;
  17583. };
  17584. // Methods
  17585. Mesh.prototype._preActivate = function () {
  17586. var sceneRenderId = this.getScene().getRenderId();
  17587. if (this._preActivateId === sceneRenderId) {
  17588. return;
  17589. }
  17590. this._preActivateId = sceneRenderId;
  17591. this._visibleInstances = null;
  17592. };
  17593. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17594. if (this._visibleInstances) {
  17595. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17596. }
  17597. };
  17598. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17599. if (!this._visibleInstances) {
  17600. this._visibleInstances = {};
  17601. this._visibleInstances.defaultRenderId = renderId;
  17602. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17603. }
  17604. if (!this._visibleInstances[renderId]) {
  17605. this._visibleInstances[renderId] = new Array();
  17606. }
  17607. this._visibleInstances[renderId].push(instance);
  17608. };
  17609. /**
  17610. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17611. * This means the mesh underlying bounding box and sphere are recomputed.
  17612. */
  17613. Mesh.prototype.refreshBoundingInfo = function () {
  17614. if (this._boundingInfo.isLocked) {
  17615. return;
  17616. }
  17617. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17618. if (data) {
  17619. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17620. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17621. }
  17622. if (this.subMeshes) {
  17623. for (var index = 0; index < this.subMeshes.length; index++) {
  17624. this.subMeshes[index].refreshBoundingInfo();
  17625. }
  17626. }
  17627. this._updateBoundingInfo();
  17628. };
  17629. Mesh.prototype._createGlobalSubMesh = function () {
  17630. var totalVertices = this.getTotalVertices();
  17631. if (!totalVertices || !this.getIndices()) {
  17632. return null;
  17633. }
  17634. this.releaseSubMeshes();
  17635. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17636. };
  17637. Mesh.prototype.subdivide = function (count) {
  17638. if (count < 1) {
  17639. return;
  17640. }
  17641. var totalIndices = this.getTotalIndices();
  17642. var subdivisionSize = (totalIndices / count) | 0;
  17643. var offset = 0;
  17644. // Ensure that subdivisionSize is a multiple of 3
  17645. while (subdivisionSize % 3 !== 0) {
  17646. subdivisionSize++;
  17647. }
  17648. this.releaseSubMeshes();
  17649. for (var index = 0; index < count; index++) {
  17650. if (offset >= totalIndices) {
  17651. break;
  17652. }
  17653. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17654. offset += subdivisionSize;
  17655. }
  17656. this.synchronizeInstances();
  17657. };
  17658. /**
  17659. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17660. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17661. * The `data` are either a numeric array either a Float32Array.
  17662. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  17663. * 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).
  17664. * Note that a new underlying `VertexBuffer` object is created each call.
  17665. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17666. *
  17667. * Possible `kind` values :
  17668. * - BABYLON.VertexBuffer.PositionKind
  17669. * - BABYLON.VertexBuffer.UVKind
  17670. * - BABYLON.VertexBuffer.UV2Kind
  17671. * - BABYLON.VertexBuffer.UV3Kind
  17672. * - BABYLON.VertexBuffer.UV4Kind
  17673. * - BABYLON.VertexBuffer.UV5Kind
  17674. * - BABYLON.VertexBuffer.UV6Kind
  17675. * - BABYLON.VertexBuffer.ColorKind
  17676. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17677. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17678. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17679. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17680. */
  17681. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17682. if (!this._geometry) {
  17683. var vertexData = new BABYLON.VertexData();
  17684. vertexData.set(data, kind);
  17685. var scene = this.getScene();
  17686. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17687. }
  17688. else {
  17689. this._geometry.setVerticesData(kind, data, updatable, stride);
  17690. }
  17691. };
  17692. /**
  17693. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17694. * If the mesh has no geometry, it is simply returned as it is.
  17695. * The `data` are either a numeric array either a Float32Array.
  17696. * No new underlying `VertexBuffer` object is created.
  17697. * 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.
  17698. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17699. *
  17700. * Possible `kind` values :
  17701. * - BABYLON.VertexBuffer.PositionKind
  17702. * - BABYLON.VertexBuffer.UVKind
  17703. * - BABYLON.VertexBuffer.UV2Kind
  17704. * - BABYLON.VertexBuffer.UV3Kind
  17705. * - BABYLON.VertexBuffer.UV4Kind
  17706. * - BABYLON.VertexBuffer.UV5Kind
  17707. * - BABYLON.VertexBuffer.UV6Kind
  17708. * - BABYLON.VertexBuffer.ColorKind
  17709. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17710. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17711. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17712. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17713. */
  17714. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17715. if (!this._geometry) {
  17716. return;
  17717. }
  17718. if (!makeItUnique) {
  17719. this._geometry.updateVerticesData(kind, data, updateExtends);
  17720. }
  17721. else {
  17722. this.makeGeometryUnique();
  17723. this.updateVerticesData(kind, data, updateExtends, false);
  17724. }
  17725. };
  17726. /**
  17727. * Deprecated since BabylonJS v2.3
  17728. */
  17729. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17730. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17731. if (!this._geometry) {
  17732. return;
  17733. }
  17734. if (!makeItUnique) {
  17735. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17736. }
  17737. else {
  17738. this.makeGeometryUnique();
  17739. this.updateVerticesDataDirectly(kind, data, offset, false);
  17740. }
  17741. };
  17742. /**
  17743. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17744. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17745. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17746. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17747. */
  17748. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17749. if (computeNormals === void 0) { computeNormals = true; }
  17750. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17751. positionFunction(positions);
  17752. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17753. if (computeNormals) {
  17754. var indices = this.getIndices();
  17755. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17756. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17757. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17758. }
  17759. };
  17760. Mesh.prototype.makeGeometryUnique = function () {
  17761. if (!this._geometry) {
  17762. return;
  17763. }
  17764. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17765. geometry.applyToMesh(this);
  17766. };
  17767. /**
  17768. * Sets the mesh indices.
  17769. * Expects an array populated with integers or a Int32Array.
  17770. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17771. * This method creates a new index buffer each call.
  17772. */
  17773. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17774. if (!this._geometry) {
  17775. var vertexData = new BABYLON.VertexData();
  17776. vertexData.indices = indices;
  17777. var scene = this.getScene();
  17778. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17779. }
  17780. else {
  17781. this._geometry.setIndices(indices, totalVertices);
  17782. }
  17783. };
  17784. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17785. var engine = this.getScene().getEngine();
  17786. // Wireframe
  17787. var indexToBind;
  17788. if (this._unIndexed) {
  17789. indexToBind = null;
  17790. }
  17791. else {
  17792. switch (fillMode) {
  17793. case BABYLON.Material.PointFillMode:
  17794. indexToBind = null;
  17795. break;
  17796. case BABYLON.Material.WireFrameFillMode:
  17797. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17798. break;
  17799. default:
  17800. case BABYLON.Material.TriangleFillMode:
  17801. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17802. break;
  17803. }
  17804. }
  17805. // VBOs
  17806. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17807. };
  17808. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17809. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17810. return;
  17811. }
  17812. this.onBeforeDrawObservable.notifyObservers(this);
  17813. var engine = this.getScene().getEngine();
  17814. // Draw order
  17815. switch (fillMode) {
  17816. case BABYLON.Material.PointFillMode:
  17817. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17818. break;
  17819. case BABYLON.Material.WireFrameFillMode:
  17820. if (this._unIndexed) {
  17821. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17822. }
  17823. else {
  17824. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17825. }
  17826. break;
  17827. default:
  17828. if (this._unIndexed) {
  17829. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17830. }
  17831. else {
  17832. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17833. }
  17834. }
  17835. };
  17836. /**
  17837. * Registers for this mesh a javascript function called just before the rendering process.
  17838. * This function is passed the current mesh and doesn't return anything.
  17839. */
  17840. Mesh.prototype.registerBeforeRender = function (func) {
  17841. this.onBeforeRenderObservable.add(func);
  17842. };
  17843. /**
  17844. * Disposes a previously registered javascript function called before the rendering.
  17845. * This function is passed the current mesh and doesn't return anything.
  17846. */
  17847. Mesh.prototype.unregisterBeforeRender = function (func) {
  17848. this.onBeforeRenderObservable.removeCallback(func);
  17849. };
  17850. /**
  17851. * Registers for this mesh a javascript function called just after the rendering is complete.
  17852. * This function is passed the current mesh and doesn't return anything.
  17853. */
  17854. Mesh.prototype.registerAfterRender = function (func) {
  17855. this.onAfterRenderObservable.add(func);
  17856. };
  17857. /**
  17858. * Disposes a previously registered javascript function called after the rendering.
  17859. * This function is passed the current mesh and doesn't return anything.
  17860. */
  17861. Mesh.prototype.unregisterAfterRender = function (func) {
  17862. this.onAfterRenderObservable.removeCallback(func);
  17863. };
  17864. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17865. var scene = this.getScene();
  17866. this._batchCache.mustReturn = false;
  17867. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17868. this._batchCache.visibleInstances[subMeshId] = null;
  17869. if (this._visibleInstances) {
  17870. var currentRenderId = scene.getRenderId();
  17871. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17872. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17873. var selfRenderId = this._renderId;
  17874. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17875. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17876. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17877. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17878. }
  17879. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17880. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17881. this._batchCache.mustReturn = true;
  17882. return this._batchCache;
  17883. }
  17884. if (currentRenderId !== selfRenderId) {
  17885. this._batchCache.renderSelf[subMeshId] = false;
  17886. }
  17887. }
  17888. this._renderIdForInstances[subMeshId] = currentRenderId;
  17889. }
  17890. return this._batchCache;
  17891. };
  17892. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17893. var visibleInstances = batch.visibleInstances[subMesh._id];
  17894. var matricesCount = visibleInstances.length + 1;
  17895. var bufferSize = matricesCount * 16 * 4;
  17896. while (this._instancesBufferSize < bufferSize) {
  17897. this._instancesBufferSize *= 2;
  17898. }
  17899. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17900. if (this._worldMatricesInstancesBuffer) {
  17901. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17902. }
  17903. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17904. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17905. }
  17906. var offset = 0;
  17907. var instancesCount = 0;
  17908. var world = this.getWorldMatrix();
  17909. if (batch.renderSelf[subMesh._id]) {
  17910. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17911. offset += 16;
  17912. instancesCount++;
  17913. }
  17914. if (visibleInstances) {
  17915. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17916. var instance = visibleInstances[instanceIndex];
  17917. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17918. offset += 16;
  17919. instancesCount++;
  17920. }
  17921. }
  17922. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17923. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17924. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17925. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17926. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17927. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17928. this._draw(subMesh, fillMode, instancesCount);
  17929. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17930. };
  17931. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17932. var scene = this.getScene();
  17933. var engine = scene.getEngine();
  17934. if (hardwareInstancedRendering) {
  17935. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17936. }
  17937. else {
  17938. if (batch.renderSelf[subMesh._id]) {
  17939. // Draw
  17940. if (onBeforeDraw) {
  17941. onBeforeDraw(false, this.getWorldMatrix());
  17942. }
  17943. this._draw(subMesh, fillMode);
  17944. }
  17945. if (batch.visibleInstances[subMesh._id]) {
  17946. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17947. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17948. // World
  17949. var world = instance.getWorldMatrix();
  17950. if (onBeforeDraw) {
  17951. onBeforeDraw(true, world);
  17952. }
  17953. // Draw
  17954. this._draw(subMesh, fillMode);
  17955. }
  17956. }
  17957. }
  17958. };
  17959. /**
  17960. * Triggers the draw call for the mesh.
  17961. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  17962. */
  17963. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17964. var scene = this.getScene();
  17965. // Managing instances
  17966. var batch = this._getInstancesRenderList(subMesh._id);
  17967. if (batch.mustReturn) {
  17968. return;
  17969. }
  17970. // Checking geometry state
  17971. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17972. return;
  17973. }
  17974. var callbackIndex;
  17975. this.onBeforeRenderObservable.notifyObservers(this);
  17976. var engine = scene.getEngine();
  17977. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17978. // Material
  17979. var effectiveMaterial = subMesh.getMaterial();
  17980. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17981. return;
  17982. }
  17983. // Outline - step 1
  17984. var savedDepthWrite = engine.getDepthWrite();
  17985. if (this.renderOutline) {
  17986. engine.setDepthWrite(false);
  17987. scene.getOutlineRenderer().render(subMesh, batch);
  17988. engine.setDepthWrite(savedDepthWrite);
  17989. }
  17990. effectiveMaterial._preBind();
  17991. var effect = effectiveMaterial.getEffect();
  17992. // Bind
  17993. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17994. this._bind(subMesh, effect, fillMode);
  17995. var world = this.getWorldMatrix();
  17996. effectiveMaterial.bind(world, this);
  17997. // Alpha mode
  17998. if (enableAlphaMode) {
  17999. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18000. }
  18001. // Draw
  18002. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  18003. if (isInstance) {
  18004. effectiveMaterial.bindOnlyWorldMatrix(world);
  18005. }
  18006. });
  18007. // Unbind
  18008. effectiveMaterial.unbind();
  18009. // Outline - step 2
  18010. if (this.renderOutline && savedDepthWrite) {
  18011. engine.setDepthWrite(true);
  18012. engine.setColorWrite(false);
  18013. scene.getOutlineRenderer().render(subMesh, batch);
  18014. engine.setColorWrite(true);
  18015. }
  18016. // Overlay
  18017. if (this.renderOverlay) {
  18018. var currentMode = engine.getAlphaMode();
  18019. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18020. scene.getOutlineRenderer().render(subMesh, batch, true);
  18021. engine.setAlphaMode(currentMode);
  18022. }
  18023. this.onAfterRenderObservable.notifyObservers(this);
  18024. };
  18025. /**
  18026. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  18027. */
  18028. Mesh.prototype.getEmittedParticleSystems = function () {
  18029. var results = new Array();
  18030. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18031. var particleSystem = this.getScene().particleSystems[index];
  18032. if (particleSystem.emitter === this) {
  18033. results.push(particleSystem);
  18034. }
  18035. }
  18036. return results;
  18037. };
  18038. /**
  18039. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  18040. */
  18041. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18042. var results = new Array();
  18043. var descendants = this.getDescendants();
  18044. descendants.push(this);
  18045. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18046. var particleSystem = this.getScene().particleSystems[index];
  18047. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18048. results.push(particleSystem);
  18049. }
  18050. }
  18051. return results;
  18052. };
  18053. Mesh.prototype._checkDelayState = function () {
  18054. var _this = this;
  18055. var that = this;
  18056. var scene = this.getScene();
  18057. if (this._geometry) {
  18058. this._geometry.load(scene);
  18059. }
  18060. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18061. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18062. scene._addPendingData(that);
  18063. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18064. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18065. if (data instanceof ArrayBuffer) {
  18066. _this._delayLoadingFunction(data, _this);
  18067. }
  18068. else {
  18069. _this._delayLoadingFunction(JSON.parse(data), _this);
  18070. }
  18071. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18072. scene._removePendingData(_this);
  18073. }, function () { }, scene.database, getBinaryData);
  18074. }
  18075. };
  18076. /**
  18077. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  18078. */
  18079. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18080. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18081. return false;
  18082. }
  18083. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18084. return false;
  18085. }
  18086. this._checkDelayState();
  18087. return true;
  18088. };
  18089. /**
  18090. * Sets the mesh material by the material or multiMaterial `id` property.
  18091. * The material `id` is a string identifying the material or the multiMaterial.
  18092. * This method returns nothing.
  18093. */
  18094. Mesh.prototype.setMaterialByID = function (id) {
  18095. var materials = this.getScene().materials;
  18096. var index;
  18097. for (index = 0; index < materials.length; index++) {
  18098. if (materials[index].id === id) {
  18099. this.material = materials[index];
  18100. return;
  18101. }
  18102. }
  18103. // Multi
  18104. var multiMaterials = this.getScene().multiMaterials;
  18105. for (index = 0; index < multiMaterials.length; index++) {
  18106. if (multiMaterials[index].id === id) {
  18107. this.material = multiMaterials[index];
  18108. return;
  18109. }
  18110. }
  18111. };
  18112. /**
  18113. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18114. */
  18115. Mesh.prototype.getAnimatables = function () {
  18116. var results = [];
  18117. if (this.material) {
  18118. results.push(this.material);
  18119. }
  18120. if (this.skeleton) {
  18121. results.push(this.skeleton);
  18122. }
  18123. return results;
  18124. };
  18125. /**
  18126. * Modifies the mesh geometry according to the passed transformation matrix.
  18127. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18128. * The mesh normals are modified accordingly the same transformation.
  18129. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18130. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18131. */
  18132. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18133. // Position
  18134. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18135. return;
  18136. }
  18137. var submeshes = this.subMeshes.splice(0);
  18138. this._resetPointsArrayCache();
  18139. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18140. var temp = [];
  18141. var index;
  18142. for (index = 0; index < data.length; index += 3) {
  18143. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18144. }
  18145. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18146. // Normals
  18147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18148. return;
  18149. }
  18150. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18151. temp = [];
  18152. for (index = 0; index < data.length; index += 3) {
  18153. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  18154. }
  18155. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  18156. // flip faces?
  18157. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  18158. this.flipFaces();
  18159. }
  18160. // Restore submeshes
  18161. this.releaseSubMeshes();
  18162. this.subMeshes = submeshes;
  18163. };
  18164. /**
  18165. * Modifies the mesh geometry according to its own current World Matrix.
  18166. * The mesh World Matrix is then reset.
  18167. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  18168. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18169. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18170. */
  18171. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  18172. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  18173. this.scaling.copyFromFloats(1, 1, 1);
  18174. this.position.copyFromFloats(0, 0, 0);
  18175. this.rotation.copyFromFloats(0, 0, 0);
  18176. //only if quaternion is already set
  18177. if (this.rotationQuaternion) {
  18178. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  18179. }
  18180. this._worldMatrix = BABYLON.Matrix.Identity();
  18181. };
  18182. // Cache
  18183. Mesh.prototype._resetPointsArrayCache = function () {
  18184. this._positions = null;
  18185. };
  18186. Mesh.prototype._generatePointsArray = function () {
  18187. if (this._positions)
  18188. return true;
  18189. this._positions = [];
  18190. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18191. if (!data) {
  18192. return false;
  18193. }
  18194. for (var index = 0; index < data.length; index += 3) {
  18195. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  18196. }
  18197. return true;
  18198. };
  18199. /**
  18200. * Returns a new `Mesh` object generated from the current mesh properties.
  18201. * This method must not get confused with createInstance().
  18202. * The parameter `name` is a string, the name given to the new mesh.
  18203. * The optional parameter `newParent` can be any `Node` object (default `null`).
  18204. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  18205. * 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.
  18206. */
  18207. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  18208. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18209. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  18210. };
  18211. /**
  18212. * Disposes the mesh.
  18213. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  18214. */
  18215. Mesh.prototype.dispose = function (doNotRecurse) {
  18216. if (this._geometry) {
  18217. this._geometry.releaseForMesh(this, true);
  18218. }
  18219. // Instances
  18220. if (this._worldMatricesInstancesBuffer) {
  18221. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  18222. this._worldMatricesInstancesBuffer = null;
  18223. }
  18224. while (this.instances.length) {
  18225. this.instances[0].dispose();
  18226. }
  18227. _super.prototype.dispose.call(this, doNotRecurse);
  18228. };
  18229. /**
  18230. * Modifies the mesh geometry according to a displacement map.
  18231. * 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.
  18232. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18233. * This method returns nothing.
  18234. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  18235. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18236. * 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.
  18237. */
  18238. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  18239. var _this = this;
  18240. var scene = this.getScene();
  18241. var onload = function (img) {
  18242. // Getting height map data
  18243. var canvas = document.createElement("canvas");
  18244. var context = canvas.getContext("2d");
  18245. var heightMapWidth = img.width;
  18246. var heightMapHeight = img.height;
  18247. canvas.width = heightMapWidth;
  18248. canvas.height = heightMapHeight;
  18249. context.drawImage(img, 0, 0);
  18250. // Create VertexData from map data
  18251. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  18252. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  18253. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  18254. //execute success callback, if set
  18255. if (onSuccess) {
  18256. onSuccess(_this);
  18257. }
  18258. };
  18259. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  18260. };
  18261. /**
  18262. * Modifies the mesh geometry according to a displacementMap buffer.
  18263. * 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.
  18264. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  18265. * This method returns nothing.
  18266. * 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.
  18267. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  18268. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  18269. */
  18270. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  18271. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  18272. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  18273. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18274. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  18275. return;
  18276. }
  18277. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18278. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18279. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18280. var position = BABYLON.Vector3.Zero();
  18281. var normal = BABYLON.Vector3.Zero();
  18282. var uv = BABYLON.Vector2.Zero();
  18283. for (var index = 0; index < positions.length; index += 3) {
  18284. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  18285. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  18286. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  18287. // Compute height
  18288. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  18289. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  18290. var pos = (u + v * heightMapWidth) * 4;
  18291. var r = buffer[pos] / 255.0;
  18292. var g = buffer[pos + 1] / 255.0;
  18293. var b = buffer[pos + 2] / 255.0;
  18294. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18295. normal.normalize();
  18296. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18297. position = position.add(normal);
  18298. position.toArray(positions, index);
  18299. }
  18300. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18301. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18302. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18303. };
  18304. /**
  18305. * Modify the mesh to get a flat shading rendering.
  18306. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18307. * This method returns nothing.
  18308. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18309. */
  18310. Mesh.prototype.convertToFlatShadedMesh = function () {
  18311. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18312. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18313. var kinds = this.getVerticesDataKinds();
  18314. var vbs = [];
  18315. var data = [];
  18316. var newdata = [];
  18317. var updatableNormals = false;
  18318. var kindIndex;
  18319. var kind;
  18320. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18321. kind = kinds[kindIndex];
  18322. var vertexBuffer = this.getVertexBuffer(kind);
  18323. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18324. updatableNormals = vertexBuffer.isUpdatable();
  18325. kinds.splice(kindIndex, 1);
  18326. kindIndex--;
  18327. continue;
  18328. }
  18329. vbs[kind] = vertexBuffer;
  18330. data[kind] = vbs[kind].getData();
  18331. newdata[kind] = [];
  18332. }
  18333. // Save previous submeshes
  18334. var previousSubmeshes = this.subMeshes.slice(0);
  18335. var indices = this.getIndices();
  18336. var totalIndices = this.getTotalIndices();
  18337. // Generating unique vertices per face
  18338. var index;
  18339. for (index = 0; index < totalIndices; index++) {
  18340. var vertexIndex = indices[index];
  18341. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18342. kind = kinds[kindIndex];
  18343. var stride = vbs[kind].getStrideSize();
  18344. for (var offset = 0; offset < stride; offset++) {
  18345. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18346. }
  18347. }
  18348. }
  18349. // Updating faces & normal
  18350. var normals = [];
  18351. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18352. for (index = 0; index < totalIndices; index += 3) {
  18353. indices[index] = index;
  18354. indices[index + 1] = index + 1;
  18355. indices[index + 2] = index + 2;
  18356. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18357. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18358. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18359. var p1p2 = p1.subtract(p2);
  18360. var p3p2 = p3.subtract(p2);
  18361. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18362. // Store same normals for every vertex
  18363. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18364. normals.push(normal.x);
  18365. normals.push(normal.y);
  18366. normals.push(normal.z);
  18367. }
  18368. }
  18369. this.setIndices(indices);
  18370. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18371. // Updating vertex buffers
  18372. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18373. kind = kinds[kindIndex];
  18374. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18375. }
  18376. // Updating submeshes
  18377. this.releaseSubMeshes();
  18378. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18379. var previousOne = previousSubmeshes[submeshIndex];
  18380. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18381. }
  18382. this.synchronizeInstances();
  18383. };
  18384. /**
  18385. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18386. * In other words, more vertices, no more indices and a single bigger VBO.
  18387. * This method returns nothing.
  18388. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18389. *
  18390. */
  18391. Mesh.prototype.convertToUnIndexedMesh = function () {
  18392. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18393. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18394. var kinds = this.getVerticesDataKinds();
  18395. var vbs = [];
  18396. var data = [];
  18397. var newdata = [];
  18398. var updatableNormals = false;
  18399. var kindIndex;
  18400. var kind;
  18401. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18402. kind = kinds[kindIndex];
  18403. var vertexBuffer = this.getVertexBuffer(kind);
  18404. vbs[kind] = vertexBuffer;
  18405. data[kind] = vbs[kind].getData();
  18406. newdata[kind] = [];
  18407. }
  18408. // Save previous submeshes
  18409. var previousSubmeshes = this.subMeshes.slice(0);
  18410. var indices = this.getIndices();
  18411. var totalIndices = this.getTotalIndices();
  18412. // Generating unique vertices per face
  18413. var index;
  18414. for (index = 0; index < totalIndices; index++) {
  18415. var vertexIndex = indices[index];
  18416. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18417. kind = kinds[kindIndex];
  18418. var stride = vbs[kind].getStrideSize();
  18419. for (var offset = 0; offset < stride; offset++) {
  18420. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18421. }
  18422. }
  18423. }
  18424. // Updating indices
  18425. for (index = 0; index < totalIndices; index += 3) {
  18426. indices[index] = index;
  18427. indices[index + 1] = index + 1;
  18428. indices[index + 2] = index + 2;
  18429. }
  18430. this.setIndices(indices);
  18431. // Updating vertex buffers
  18432. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18433. kind = kinds[kindIndex];
  18434. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18435. }
  18436. // Updating submeshes
  18437. this.releaseSubMeshes();
  18438. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18439. var previousOne = previousSubmeshes[submeshIndex];
  18440. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18441. }
  18442. this._unIndexed = true;
  18443. this.synchronizeInstances();
  18444. };
  18445. /**
  18446. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18447. * This method returns nothing.
  18448. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18449. */
  18450. Mesh.prototype.flipFaces = function (flipNormals) {
  18451. if (flipNormals === void 0) { flipNormals = false; }
  18452. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18453. var i;
  18454. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18455. for (i = 0; i < vertex_data.normals.length; i++) {
  18456. vertex_data.normals[i] *= -1;
  18457. }
  18458. }
  18459. var temp;
  18460. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18461. // reassign indices
  18462. temp = vertex_data.indices[i + 1];
  18463. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18464. vertex_data.indices[i + 2] = temp;
  18465. }
  18466. vertex_data.applyToMesh(this);
  18467. };
  18468. // Instances
  18469. /**
  18470. * Creates a new `InstancedMesh` object from the mesh model.
  18471. * An instance shares the same properties and the same material than its model.
  18472. * Only these properties of each instance can then be set individually :
  18473. * - position
  18474. * - rotation
  18475. * - rotationQuaternion
  18476. * - setPivotMatrix
  18477. * - scaling
  18478. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18479. * Warning : this method is not supported for `Line` mesh and `LineSystem`
  18480. */
  18481. Mesh.prototype.createInstance = function (name) {
  18482. return new BABYLON.InstancedMesh(name, this);
  18483. };
  18484. /**
  18485. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18486. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18487. * This method returns nothing.
  18488. */
  18489. Mesh.prototype.synchronizeInstances = function () {
  18490. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18491. var instance = this.instances[instanceIndex];
  18492. instance._syncSubMeshes();
  18493. }
  18494. };
  18495. /**
  18496. * Simplify the mesh according to the given array of settings.
  18497. * Function will return immediately and will simplify async. It returns nothing.
  18498. * @param settings a collection of simplification settings.
  18499. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18500. * @param type the type of simplification to run.
  18501. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18502. */
  18503. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18504. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18505. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18506. this.getScene().simplificationQueue.addTask({
  18507. settings: settings,
  18508. parallelProcessing: parallelProcessing,
  18509. mesh: this,
  18510. simplificationType: simplificationType,
  18511. successCallback: successCallback
  18512. });
  18513. };
  18514. /**
  18515. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18516. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18517. * This should be used together with the simplification to avoid disappearing triangles.
  18518. * @param successCallback an optional success callback to be called after the optimization finished.
  18519. */
  18520. Mesh.prototype.optimizeIndices = function (successCallback) {
  18521. var _this = this;
  18522. var indices = this.getIndices();
  18523. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18524. var vectorPositions = [];
  18525. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18526. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18527. }
  18528. var dupes = [];
  18529. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18530. var realPos = vectorPositions.length - 1 - iteration;
  18531. var testedPosition = vectorPositions[realPos];
  18532. for (var j = 0; j < realPos; ++j) {
  18533. var againstPosition = vectorPositions[j];
  18534. if (testedPosition.equals(againstPosition)) {
  18535. dupes[realPos] = j;
  18536. break;
  18537. }
  18538. }
  18539. }, function () {
  18540. for (var i = 0; i < indices.length; ++i) {
  18541. indices[i] = dupes[indices[i]] || indices[i];
  18542. }
  18543. //indices are now reordered
  18544. var originalSubMeshes = _this.subMeshes.slice(0);
  18545. _this.setIndices(indices);
  18546. _this.subMeshes = originalSubMeshes;
  18547. if (successCallback) {
  18548. successCallback(_this);
  18549. }
  18550. });
  18551. };
  18552. // Statics
  18553. /**
  18554. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  18555. * The parameter `parsedMesh` is the mesh to be copied.
  18556. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18557. */
  18558. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18559. var mesh = new Mesh(parsedMesh.name, scene);
  18560. mesh.id = parsedMesh.id;
  18561. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18562. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18563. if (parsedMesh.rotationQuaternion) {
  18564. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18565. }
  18566. else if (parsedMesh.rotation) {
  18567. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18568. }
  18569. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18570. if (parsedMesh.localMatrix) {
  18571. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18572. }
  18573. else if (parsedMesh.pivotMatrix) {
  18574. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18575. }
  18576. mesh.setEnabled(parsedMesh.isEnabled);
  18577. mesh.isVisible = parsedMesh.isVisible;
  18578. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18579. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18580. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18581. if (parsedMesh.applyFog !== undefined) {
  18582. mesh.applyFog = parsedMesh.applyFog;
  18583. }
  18584. if (parsedMesh.pickable !== undefined) {
  18585. mesh.isPickable = parsedMesh.pickable;
  18586. }
  18587. if (parsedMesh.alphaIndex !== undefined) {
  18588. mesh.alphaIndex = parsedMesh.alphaIndex;
  18589. }
  18590. mesh.receiveShadows = parsedMesh.receiveShadows;
  18591. mesh.billboardMode = parsedMesh.billboardMode;
  18592. if (parsedMesh.visibility !== undefined) {
  18593. mesh.visibility = parsedMesh.visibility;
  18594. }
  18595. mesh.checkCollisions = parsedMesh.checkCollisions;
  18596. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18597. // freezeWorldMatrix
  18598. if (parsedMesh.freezeWorldMatrix) {
  18599. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18600. }
  18601. // Parent
  18602. if (parsedMesh.parentId) {
  18603. mesh._waitingParentId = parsedMesh.parentId;
  18604. }
  18605. // Actions
  18606. if (parsedMesh.actions !== undefined) {
  18607. mesh._waitingActions = parsedMesh.actions;
  18608. }
  18609. // Geometry
  18610. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18611. if (parsedMesh.delayLoadingFile) {
  18612. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18613. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18614. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18615. if (parsedMesh._binaryInfo) {
  18616. mesh._binaryInfo = parsedMesh._binaryInfo;
  18617. }
  18618. mesh._delayInfo = [];
  18619. if (parsedMesh.hasUVs) {
  18620. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18621. }
  18622. if (parsedMesh.hasUVs2) {
  18623. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18624. }
  18625. if (parsedMesh.hasUVs3) {
  18626. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18627. }
  18628. if (parsedMesh.hasUVs4) {
  18629. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18630. }
  18631. if (parsedMesh.hasUVs5) {
  18632. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18633. }
  18634. if (parsedMesh.hasUVs6) {
  18635. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18636. }
  18637. if (parsedMesh.hasColors) {
  18638. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18639. }
  18640. if (parsedMesh.hasMatricesIndices) {
  18641. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18642. }
  18643. if (parsedMesh.hasMatricesWeights) {
  18644. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18645. }
  18646. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18647. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18648. mesh._checkDelayState();
  18649. }
  18650. }
  18651. else {
  18652. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18653. }
  18654. // Material
  18655. if (parsedMesh.materialId) {
  18656. mesh.setMaterialByID(parsedMesh.materialId);
  18657. }
  18658. else {
  18659. mesh.material = null;
  18660. }
  18661. // Skeleton
  18662. if (parsedMesh.skeletonId > -1) {
  18663. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18664. if (parsedMesh.numBoneInfluencers) {
  18665. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18666. }
  18667. }
  18668. // Animations
  18669. if (parsedMesh.animations) {
  18670. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18671. var parsedAnimation = parsedMesh.animations[animationIndex];
  18672. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18673. }
  18674. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18675. }
  18676. if (parsedMesh.autoAnimate) {
  18677. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18678. }
  18679. // Layer Mask
  18680. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18681. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18682. }
  18683. else {
  18684. mesh.layerMask = 0x0FFFFFFF;
  18685. }
  18686. //(Deprecated) physics
  18687. if (parsedMesh.physicsImpostor) {
  18688. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18689. mass: parsedMesh.physicsMass,
  18690. friction: parsedMesh.physicsFriction,
  18691. restitution: parsedMesh.physicsRestitution
  18692. }, scene);
  18693. }
  18694. // Instances
  18695. if (parsedMesh.instances) {
  18696. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18697. var parsedInstance = parsedMesh.instances[index];
  18698. var instance = mesh.createInstance(parsedInstance.name);
  18699. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18700. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18701. if (parsedInstance.rotationQuaternion) {
  18702. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18703. }
  18704. else if (parsedInstance.rotation) {
  18705. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18706. }
  18707. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18708. instance.checkCollisions = mesh.checkCollisions;
  18709. if (parsedMesh.animations) {
  18710. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18711. parsedAnimation = parsedMesh.animations[animationIndex];
  18712. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18713. }
  18714. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18715. }
  18716. }
  18717. }
  18718. return mesh;
  18719. };
  18720. /**
  18721. * Creates a ribbon mesh.
  18722. * Please consider using the same method from the `MeshBuilder` class instead.
  18723. * 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.
  18724. *
  18725. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18726. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18727. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18728. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18729. * 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.
  18730. * 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.
  18731. * 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
  18732. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18733. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18735. */
  18736. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18737. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18738. pathArray: pathArray,
  18739. closeArray: closeArray,
  18740. closePath: closePath,
  18741. offset: offset,
  18742. updatable: updatable,
  18743. sideOrientation: sideOrientation,
  18744. instance: instance
  18745. }, scene);
  18746. };
  18747. /**
  18748. * Creates a plane polygonal mesh. By default, this is a disc.
  18749. * Please consider using the same method from the `MeshBuilder` class instead.
  18750. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18751. * 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.
  18752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18753. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18755. */
  18756. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18757. var options = {
  18758. radius: radius,
  18759. tessellation: tessellation,
  18760. sideOrientation: sideOrientation,
  18761. updatable: updatable
  18762. };
  18763. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18764. };
  18765. /**
  18766. * Creates a box mesh.
  18767. * Please consider using the same method from the `MeshBuilder` class instead.
  18768. * The parameter `size` sets the size (float) of each box side (default 1).
  18769. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18770. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18772. */
  18773. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18774. var options = {
  18775. size: size,
  18776. sideOrientation: sideOrientation,
  18777. updatable: updatable
  18778. };
  18779. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18780. };
  18781. /**
  18782. * Creates a sphere mesh.
  18783. * Please consider using the same method from the `MeshBuilder` class instead.
  18784. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18785. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18789. */
  18790. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18791. var options = {
  18792. segments: segments,
  18793. diameterX: diameter,
  18794. diameterY: diameter,
  18795. diameterZ: diameter,
  18796. sideOrientation: sideOrientation,
  18797. updatable: updatable
  18798. };
  18799. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18800. };
  18801. /**
  18802. * Creates a cylinder or a cone mesh.
  18803. * Please consider using the same method from the `MeshBuilder` class instead.
  18804. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18805. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18806. * 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.
  18807. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18808. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18810. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18812. */
  18813. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18814. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18815. if (scene !== undefined) {
  18816. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18817. updatable = scene;
  18818. }
  18819. scene = subdivisions;
  18820. subdivisions = 1;
  18821. }
  18822. var options = {
  18823. height: height,
  18824. diameterTop: diameterTop,
  18825. diameterBottom: diameterBottom,
  18826. tessellation: tessellation,
  18827. subdivisions: subdivisions,
  18828. sideOrientation: sideOrientation,
  18829. updatable: updatable
  18830. };
  18831. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18832. };
  18833. // Torus (Code from SharpDX.org)
  18834. /**
  18835. * Creates a torus mesh.
  18836. * Please consider using the same method from the `MeshBuilder` class instead.
  18837. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18838. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18839. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18841. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18843. */
  18844. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18845. var options = {
  18846. diameter: diameter,
  18847. thickness: thickness,
  18848. tessellation: tessellation,
  18849. sideOrientation: sideOrientation,
  18850. updatable: updatable
  18851. };
  18852. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18853. };
  18854. /**
  18855. * Creates a torus knot mesh.
  18856. * Please consider using the same method from the `MeshBuilder` class instead.
  18857. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18858. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18859. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18860. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18864. */
  18865. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18866. var options = {
  18867. radius: radius,
  18868. tube: tube,
  18869. radialSegments: radialSegments,
  18870. tubularSegments: tubularSegments,
  18871. p: p,
  18872. q: q,
  18873. sideOrientation: sideOrientation,
  18874. updatable: updatable
  18875. };
  18876. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18877. };
  18878. /**
  18879. * Creates a line mesh.
  18880. * Please consider using the same method from the `MeshBuilder` class instead.
  18881. * 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.
  18882. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18883. * The parameter `points` is an array successive Vector3.
  18884. * 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
  18885. * When updating an instance, remember that only point positions can change, not the number of points.
  18886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18887. */
  18888. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18889. var options = {
  18890. points: points,
  18891. updatable: updatable,
  18892. instance: instance
  18893. };
  18894. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18895. };
  18896. /**
  18897. * Creates a dashed line mesh.
  18898. * Please consider using the same method from the `MeshBuilder` class instead.
  18899. * 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.
  18900. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18901. * The parameter `points` is an array successive Vector3.
  18902. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18903. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18904. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18905. * 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
  18906. * When updating an instance, remember that only point positions can change, not the number of points.
  18907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18908. */
  18909. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18910. var options = {
  18911. points: points,
  18912. dashSize: dashSize,
  18913. gapSize: gapSize,
  18914. dashNb: dashNb,
  18915. updatable: updatable
  18916. };
  18917. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18918. };
  18919. /**
  18920. * Creates an extruded shape mesh.
  18921. * 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.
  18922. * Please consider using the same method from the `MeshBuilder` class instead.
  18923. *
  18924. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18925. * 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
  18926. * extruded along the Z axis.
  18927. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18928. * 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.
  18929. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18930. * 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
  18931. * 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
  18932. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18936. */
  18937. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18938. var options = {
  18939. shape: shape,
  18940. path: path,
  18941. scale: scale,
  18942. rotation: rotation,
  18943. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18944. sideOrientation: sideOrientation,
  18945. instance: instance,
  18946. updatable: updatable
  18947. };
  18948. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18949. };
  18950. /**
  18951. * Creates an custom extruded shape mesh.
  18952. * 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.
  18953. * Please consider using the same method from the `MeshBuilder` class instead.
  18954. *
  18955. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18956. * 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
  18957. * extruded along the Z axis.
  18958. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18959. * 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
  18960. * and the distance of this point from the begining of the path :
  18961. * ```rotationFunction = function(i, distance) {
  18962. * // do things
  18963. * return rotationValue; }```
  18964. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18965. * 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
  18966. * and the distance of this point from the begining of the path :
  18967. * ````scaleFunction = function(i, distance) {
  18968. * // do things
  18969. * return scaleValue;}```
  18970. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18971. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18972. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18973. * 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
  18974. * 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
  18975. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18979. */
  18980. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18981. var options = {
  18982. shape: shape,
  18983. path: path,
  18984. scaleFunction: scaleFunction,
  18985. rotationFunction: rotationFunction,
  18986. ribbonCloseArray: ribbonCloseArray,
  18987. ribbonClosePath: ribbonClosePath,
  18988. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18989. sideOrientation: sideOrientation,
  18990. instance: instance,
  18991. updatable: updatable
  18992. };
  18993. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18994. };
  18995. /**
  18996. * Creates lathe mesh.
  18997. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18998. * Please consider using the same method from the `MeshBuilder` class instead.
  18999. *
  19000. * 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
  19001. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19002. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19003. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19007. */
  19008. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19009. var options = {
  19010. shape: shape,
  19011. radius: radius,
  19012. tessellation: tessellation,
  19013. sideOrientation: sideOrientation,
  19014. updatable: updatable
  19015. };
  19016. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19017. };
  19018. /**
  19019. * Creates a plane mesh.
  19020. * Please consider using the same method from the `MeshBuilder` class instead.
  19021. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19023. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19025. */
  19026. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19027. var options = {
  19028. size: size,
  19029. width: size,
  19030. height: size,
  19031. sideOrientation: sideOrientation,
  19032. updatable: updatable
  19033. };
  19034. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19035. };
  19036. /**
  19037. * Creates a ground mesh.
  19038. * Please consider using the same method from the `MeshBuilder` class instead.
  19039. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19040. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19042. */
  19043. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19044. var options = {
  19045. width: width,
  19046. height: height,
  19047. subdivisions: subdivisions,
  19048. updatable: updatable
  19049. };
  19050. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19051. };
  19052. /**
  19053. * Creates a tiled ground mesh.
  19054. * Please consider using the same method from the `MeshBuilder` class instead.
  19055. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19056. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19057. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19058. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19059. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19060. * numbers of subdivisions on the ground width and height of each tile.
  19061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19062. */
  19063. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19064. var options = {
  19065. xmin: xmin,
  19066. zmin: zmin,
  19067. xmax: xmax,
  19068. zmax: zmax,
  19069. subdivisions: subdivisions,
  19070. precision: precision,
  19071. updatable: updatable
  19072. };
  19073. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19074. };
  19075. /**
  19076. * Creates a ground mesh from a height map.
  19077. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19078. * Please consider using the same method from the `MeshBuilder` class instead.
  19079. * The parameter `url` sets the URL of the height map image resource.
  19080. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19081. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19082. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19083. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19084. * 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).
  19085. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19086. * return; }```
  19087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19088. */
  19089. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19090. var options = {
  19091. width: width,
  19092. height: height,
  19093. subdivisions: subdivisions,
  19094. minHeight: minHeight,
  19095. maxHeight: maxHeight,
  19096. updatable: updatable,
  19097. onReady: onReady
  19098. };
  19099. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19100. };
  19101. /**
  19102. * Creates a tube mesh.
  19103. * 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.
  19104. *
  19105. * Please consider using the same method from the `MeshBuilder` class instead.
  19106. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19107. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19108. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19109. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19110. * 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.
  19111. * It must return a radius value (positive float) :
  19112. * ```var radiusFunction = function(i, distance) {
  19113. * // do things
  19114. * return radius; }```
  19115. * 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
  19116. * 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
  19117. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19120. */
  19121. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19122. var options = {
  19123. path: path,
  19124. radius: radius,
  19125. tessellation: tessellation,
  19126. radiusFunction: radiusFunction,
  19127. arc: 1,
  19128. cap: cap,
  19129. updatable: updatable,
  19130. sideOrientation: sideOrientation,
  19131. instance: instance
  19132. };
  19133. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19134. };
  19135. /**
  19136. * Creates a polyhedron mesh.
  19137. *
  19138. * Please consider using the same method from the `MeshBuilder` class instead.
  19139. * 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
  19140. * to choose the wanted type.
  19141. * The parameter `size` (positive float, default 1) sets the polygon size.
  19142. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19143. * 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`.
  19144. * 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
  19145. * 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)`).
  19146. * 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
  19147. * 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.
  19148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19151. */
  19152. Mesh.CreatePolyhedron = function (name, options, scene) {
  19153. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  19154. };
  19155. /**
  19156. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19157. * Please consider using the same method from the `MeshBuilder` class instead.
  19158. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19159. * 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`).
  19160. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19161. * 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.
  19162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19163. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19165. */
  19166. Mesh.CreateIcoSphere = function (name, options, scene) {
  19167. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  19168. };
  19169. /**
  19170. * Creates a decal mesh.
  19171. * Please consider using the same method from the `MeshBuilder` class instead.
  19172. * 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.
  19173. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19174. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19175. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19176. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19177. */
  19178. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  19179. var options = {
  19180. position: position,
  19181. normal: normal,
  19182. size: size,
  19183. angle: angle
  19184. };
  19185. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  19186. };
  19187. // Skeletons
  19188. /**
  19189. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19190. */
  19191. Mesh.prototype.setPositionsForCPUSkinning = function () {
  19192. var source;
  19193. if (!this._sourcePositions) {
  19194. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19195. this._sourcePositions = new Float32Array(source);
  19196. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  19197. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  19198. }
  19199. }
  19200. return this._sourcePositions;
  19201. };
  19202. /**
  19203. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  19204. */
  19205. Mesh.prototype.setNormalsForCPUSkinning = function () {
  19206. var source;
  19207. if (!this._sourceNormals) {
  19208. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19209. this._sourceNormals = new Float32Array(source);
  19210. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  19211. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  19212. }
  19213. }
  19214. return this._sourceNormals;
  19215. };
  19216. /**
  19217. * Update the vertex buffers by applying transformation from the bones
  19218. * @param {skeleton} skeleton to apply
  19219. */
  19220. Mesh.prototype.applySkeleton = function (skeleton) {
  19221. if (!this.geometry) {
  19222. return;
  19223. }
  19224. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  19225. return;
  19226. }
  19227. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  19228. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19229. return this;
  19230. }
  19231. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19232. return this;
  19233. }
  19234. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19235. return this;
  19236. }
  19237. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19238. return this;
  19239. }
  19240. if (!this._sourcePositions) {
  19241. this.setPositionsForCPUSkinning();
  19242. }
  19243. if (!this._sourceNormals) {
  19244. this.setNormalsForCPUSkinning();
  19245. }
  19246. // positionsData checks for not being Float32Array will only pass at most once
  19247. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19248. if (!(positionsData instanceof Float32Array)) {
  19249. positionsData = new Float32Array(positionsData);
  19250. }
  19251. // normalsData checks for not being Float32Array will only pass at most once
  19252. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19253. if (!(normalsData instanceof Float32Array)) {
  19254. normalsData = new Float32Array(normalsData);
  19255. }
  19256. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19257. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19258. var needExtras = this.numBoneInfluencers > 4;
  19259. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  19260. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  19261. var skeletonMatrices = skeleton.getTransformMatrices(this);
  19262. var tempVector3 = BABYLON.Vector3.Zero();
  19263. var finalMatrix = new BABYLON.Matrix();
  19264. var tempMatrix = new BABYLON.Matrix();
  19265. var matWeightIdx = 0;
  19266. var inf;
  19267. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  19268. var weight;
  19269. for (inf = 0; inf < 4; inf++) {
  19270. weight = matricesWeightsData[matWeightIdx + inf];
  19271. if (weight > 0) {
  19272. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19273. finalMatrix.addToSelf(tempMatrix);
  19274. }
  19275. else
  19276. break;
  19277. }
  19278. if (needExtras) {
  19279. for (inf = 0; inf < 4; inf++) {
  19280. weight = matricesWeightsExtraData[matWeightIdx + inf];
  19281. if (weight > 0) {
  19282. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  19283. finalMatrix.addToSelf(tempMatrix);
  19284. }
  19285. else
  19286. break;
  19287. }
  19288. }
  19289. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  19290. tempVector3.toArray(positionsData, index);
  19291. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19292. tempVector3.toArray(normalsData, index);
  19293. finalMatrix.reset();
  19294. }
  19295. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19296. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19297. return this;
  19298. };
  19299. // Tools
  19300. /**
  19301. * Returns an object `{min: Vector3, max: Vector3}`
  19302. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19303. */
  19304. Mesh.MinMax = function (meshes) {
  19305. var minVector = null;
  19306. var maxVector = null;
  19307. for (var i in meshes) {
  19308. var mesh = meshes[i];
  19309. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19310. if (!minVector) {
  19311. minVector = boundingBox.minimumWorld;
  19312. maxVector = boundingBox.maximumWorld;
  19313. continue;
  19314. }
  19315. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19316. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19317. }
  19318. return {
  19319. min: minVector,
  19320. max: maxVector
  19321. };
  19322. };
  19323. /**
  19324. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19325. */
  19326. Mesh.Center = function (meshesOrMinMaxVector) {
  19327. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19328. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19329. };
  19330. /**
  19331. * Merge the array of meshes into a single mesh for performance reasons.
  19332. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19333. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19334. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19335. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19336. */
  19337. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19338. if (disposeSource === void 0) { disposeSource = true; }
  19339. var index;
  19340. if (!allow32BitsIndices) {
  19341. var totalVertices = 0;
  19342. // Counting vertices
  19343. for (index = 0; index < meshes.length; index++) {
  19344. if (meshes[index]) {
  19345. totalVertices += meshes[index].getTotalVertices();
  19346. if (totalVertices > 65536) {
  19347. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19348. return null;
  19349. }
  19350. }
  19351. }
  19352. }
  19353. // Merge
  19354. var vertexData;
  19355. var otherVertexData;
  19356. var source;
  19357. for (index = 0; index < meshes.length; index++) {
  19358. if (meshes[index]) {
  19359. meshes[index].computeWorldMatrix(true);
  19360. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19361. otherVertexData.transform(meshes[index].getWorldMatrix());
  19362. if (vertexData) {
  19363. vertexData.merge(otherVertexData);
  19364. }
  19365. else {
  19366. vertexData = otherVertexData;
  19367. source = meshes[index];
  19368. }
  19369. }
  19370. }
  19371. if (!meshSubclass) {
  19372. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19373. }
  19374. vertexData.applyToMesh(meshSubclass);
  19375. // Setting properties
  19376. meshSubclass.material = source.material;
  19377. meshSubclass.checkCollisions = source.checkCollisions;
  19378. // Cleaning
  19379. if (disposeSource) {
  19380. for (index = 0; index < meshes.length; index++) {
  19381. if (meshes[index]) {
  19382. meshes[index].dispose();
  19383. }
  19384. }
  19385. }
  19386. return meshSubclass;
  19387. };
  19388. // Consts
  19389. Mesh._FRONTSIDE = 0;
  19390. Mesh._BACKSIDE = 1;
  19391. Mesh._DOUBLESIDE = 2;
  19392. Mesh._DEFAULTSIDE = 0;
  19393. Mesh._NO_CAP = 0;
  19394. Mesh._CAP_START = 1;
  19395. Mesh._CAP_END = 2;
  19396. Mesh._CAP_ALL = 3;
  19397. return Mesh;
  19398. })(BABYLON.AbstractMesh);
  19399. BABYLON.Mesh = Mesh;
  19400. })(BABYLON || (BABYLON = {}));
  19401. var BABYLON;
  19402. (function (BABYLON) {
  19403. var SubMesh = (function () {
  19404. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19405. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19406. this.materialIndex = materialIndex;
  19407. this.verticesStart = verticesStart;
  19408. this.verticesCount = verticesCount;
  19409. this.indexStart = indexStart;
  19410. this.indexCount = indexCount;
  19411. this._renderId = 0;
  19412. this._mesh = mesh;
  19413. this._renderingMesh = renderingMesh || mesh;
  19414. mesh.subMeshes.push(this);
  19415. this._trianglePlanes = [];
  19416. this._id = mesh.subMeshes.length - 1;
  19417. if (createBoundingBox) {
  19418. this.refreshBoundingInfo();
  19419. mesh.computeWorldMatrix(true);
  19420. }
  19421. }
  19422. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19423. get: function () {
  19424. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19425. },
  19426. enumerable: true,
  19427. configurable: true
  19428. });
  19429. SubMesh.prototype.getBoundingInfo = function () {
  19430. if (this.IsGlobal) {
  19431. return this._mesh.getBoundingInfo();
  19432. }
  19433. return this._boundingInfo;
  19434. };
  19435. SubMesh.prototype.getMesh = function () {
  19436. return this._mesh;
  19437. };
  19438. SubMesh.prototype.getRenderingMesh = function () {
  19439. return this._renderingMesh;
  19440. };
  19441. SubMesh.prototype.getMaterial = function () {
  19442. var rootMaterial = this._renderingMesh.material;
  19443. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19444. var multiMaterial = rootMaterial;
  19445. return multiMaterial.getSubMaterial(this.materialIndex);
  19446. }
  19447. if (!rootMaterial) {
  19448. return this._mesh.getScene().defaultMaterial;
  19449. }
  19450. return rootMaterial;
  19451. };
  19452. // Methods
  19453. SubMesh.prototype.refreshBoundingInfo = function () {
  19454. this._lastColliderWorldVertices = null;
  19455. if (this.IsGlobal) {
  19456. return;
  19457. }
  19458. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19459. if (!data) {
  19460. this._boundingInfo = this._mesh._boundingInfo;
  19461. return;
  19462. }
  19463. var indices = this._renderingMesh.getIndices();
  19464. var extend;
  19465. //is this the only submesh?
  19466. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19467. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19468. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19469. }
  19470. else {
  19471. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19472. }
  19473. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19474. };
  19475. SubMesh.prototype._checkCollision = function (collider) {
  19476. return this.getBoundingInfo()._checkCollision(collider);
  19477. };
  19478. SubMesh.prototype.updateBoundingInfo = function (world) {
  19479. if (!this.getBoundingInfo()) {
  19480. this.refreshBoundingInfo();
  19481. }
  19482. this.getBoundingInfo().update(world);
  19483. };
  19484. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19485. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19486. };
  19487. SubMesh.prototype.render = function (enableAlphaMode) {
  19488. this._renderingMesh.render(this, enableAlphaMode);
  19489. };
  19490. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19491. if (!this._linesIndexBuffer) {
  19492. var linesIndices = [];
  19493. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19494. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19495. }
  19496. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19497. this.linesIndexCount = linesIndices.length;
  19498. }
  19499. return this._linesIndexBuffer;
  19500. };
  19501. SubMesh.prototype.canIntersects = function (ray) {
  19502. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19503. };
  19504. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19505. var intersectInfo = null;
  19506. // LineMesh first as it's also a Mesh...
  19507. if (this._mesh instanceof BABYLON.LinesMesh) {
  19508. var lineMesh = this._mesh;
  19509. // Line test
  19510. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19511. var p0 = positions[indices[index]];
  19512. var p1 = positions[indices[index + 1]];
  19513. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19514. if (length < 0) {
  19515. continue;
  19516. }
  19517. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19518. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19519. if (fastCheck) {
  19520. break;
  19521. }
  19522. }
  19523. }
  19524. }
  19525. else {
  19526. // Triangles test
  19527. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19528. var p0 = positions[indices[index]];
  19529. var p1 = positions[indices[index + 1]];
  19530. var p2 = positions[indices[index + 2]];
  19531. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19532. if (currentIntersectInfo) {
  19533. if (currentIntersectInfo.distance < 0) {
  19534. continue;
  19535. }
  19536. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19537. intersectInfo = currentIntersectInfo;
  19538. intersectInfo.faceId = index / 3;
  19539. if (fastCheck) {
  19540. break;
  19541. }
  19542. }
  19543. }
  19544. }
  19545. }
  19546. return intersectInfo;
  19547. };
  19548. // Clone
  19549. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19550. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19551. if (!this.IsGlobal) {
  19552. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19553. }
  19554. return result;
  19555. };
  19556. // Dispose
  19557. SubMesh.prototype.dispose = function () {
  19558. if (this._linesIndexBuffer) {
  19559. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19560. this._linesIndexBuffer = null;
  19561. }
  19562. // Remove from mesh
  19563. var index = this._mesh.subMeshes.indexOf(this);
  19564. this._mesh.subMeshes.splice(index, 1);
  19565. };
  19566. // Statics
  19567. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19568. var minVertexIndex = Number.MAX_VALUE;
  19569. var maxVertexIndex = -Number.MAX_VALUE;
  19570. renderingMesh = renderingMesh || mesh;
  19571. var indices = renderingMesh.getIndices();
  19572. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19573. var vertexIndex = indices[index];
  19574. if (vertexIndex < minVertexIndex)
  19575. minVertexIndex = vertexIndex;
  19576. if (vertexIndex > maxVertexIndex)
  19577. maxVertexIndex = vertexIndex;
  19578. }
  19579. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19580. };
  19581. return SubMesh;
  19582. })();
  19583. BABYLON.SubMesh = SubMesh;
  19584. })(BABYLON || (BABYLON = {}));
  19585. var BABYLON;
  19586. (function (BABYLON) {
  19587. var MeshBuilder = (function () {
  19588. function MeshBuilder() {
  19589. }
  19590. /**
  19591. * Creates a box mesh.
  19592. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19593. * The parameter `size` sets the size (float) of each box side (default 1).
  19594. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19595. * 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).
  19596. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19598. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19600. */
  19601. MeshBuilder.CreateBox = function (name, options, scene) {
  19602. var box = new BABYLON.Mesh(name, scene);
  19603. var vertexData = BABYLON.VertexData.CreateBox(options);
  19604. vertexData.applyToMesh(box, options.updatable);
  19605. return box;
  19606. };
  19607. /**
  19608. * Creates a sphere mesh.
  19609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19610. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19611. * 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`).
  19612. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19613. * 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
  19614. * 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).
  19615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19618. */
  19619. MeshBuilder.CreateSphere = function (name, options, scene) {
  19620. var sphere = new BABYLON.Mesh(name, scene);
  19621. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19622. vertexData.applyToMesh(sphere, options.updatable);
  19623. return sphere;
  19624. };
  19625. /**
  19626. * Creates a plane polygonal mesh. By default, this is a disc.
  19627. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19628. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19629. * 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.
  19630. * 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
  19631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19632. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19634. */
  19635. MeshBuilder.CreateDisc = function (name, options, scene) {
  19636. var disc = new BABYLON.Mesh(name, scene);
  19637. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19638. vertexData.applyToMesh(disc, options.updatable);
  19639. return disc;
  19640. };
  19641. /**
  19642. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19643. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19644. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19645. * 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`).
  19646. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19647. * 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.
  19648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19651. */
  19652. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19653. var sphere = new BABYLON.Mesh(name, scene);
  19654. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19655. vertexData.applyToMesh(sphere, options.updatable);
  19656. return sphere;
  19657. };
  19658. ;
  19659. /**
  19660. * Creates a ribbon mesh.
  19661. * 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.
  19662. *
  19663. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19664. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19665. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19666. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19667. * 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.
  19668. * 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.
  19669. * 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
  19670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19672. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19673. */
  19674. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19675. var pathArray = options.pathArray;
  19676. var closeArray = options.closeArray;
  19677. var closePath = options.closePath;
  19678. var offset = options.offset;
  19679. var sideOrientation = options.sideOrientation;
  19680. var instance = options.instance;
  19681. var updatable = options.updatable;
  19682. if (instance) {
  19683. // positionFunction : ribbon case
  19684. // only pathArray and sideOrientation parameters are taken into account for positions update
  19685. var positionFunction = function (positions) {
  19686. var minlg = pathArray[0].length;
  19687. var i = 0;
  19688. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19689. for (var si = 1; si <= ns; si++) {
  19690. for (var p = 0; p < pathArray.length; p++) {
  19691. var path = pathArray[p];
  19692. var l = path.length;
  19693. minlg = (minlg < l) ? minlg : l;
  19694. var j = 0;
  19695. while (j < minlg) {
  19696. positions[i] = path[j].x;
  19697. positions[i + 1] = path[j].y;
  19698. positions[i + 2] = path[j].z;
  19699. j++;
  19700. i += 3;
  19701. }
  19702. if (instance._closePath) {
  19703. positions[i] = path[0].x;
  19704. positions[i + 1] = path[0].y;
  19705. positions[i + 2] = path[0].z;
  19706. i += 3;
  19707. }
  19708. }
  19709. }
  19710. };
  19711. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19712. positionFunction(positions);
  19713. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19714. if (!(instance.areNormalsFrozen)) {
  19715. var indices = instance.getIndices();
  19716. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19717. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19718. if (instance._closePath) {
  19719. var indexFirst = 0;
  19720. var indexLast = 0;
  19721. for (var p = 0; p < pathArray.length; p++) {
  19722. indexFirst = instance._idx[p] * 3;
  19723. if (p + 1 < pathArray.length) {
  19724. indexLast = (instance._idx[p + 1] - 1) * 3;
  19725. }
  19726. else {
  19727. indexLast = normals.length - 3;
  19728. }
  19729. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19730. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19731. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19732. normals[indexLast] = normals[indexFirst];
  19733. normals[indexLast + 1] = normals[indexFirst + 1];
  19734. normals[indexLast + 2] = normals[indexFirst + 2];
  19735. }
  19736. }
  19737. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19738. }
  19739. return instance;
  19740. }
  19741. else {
  19742. var ribbon = new BABYLON.Mesh(name, scene);
  19743. ribbon.sideOrientation = sideOrientation;
  19744. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19745. if (closePath) {
  19746. ribbon._idx = vertexData._idx;
  19747. }
  19748. ribbon._closePath = closePath;
  19749. ribbon._closeArray = closeArray;
  19750. vertexData.applyToMesh(ribbon, updatable);
  19751. return ribbon;
  19752. }
  19753. };
  19754. /**
  19755. * Creates a cylinder or a cone mesh.
  19756. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19757. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19758. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19759. * 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.
  19760. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19761. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19762. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19763. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19764. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19765. * 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).
  19766. * 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
  19767. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19768. * 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
  19769. * 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.
  19770. * If `enclose` is false, a ring surface is one element.
  19771. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19772. * 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
  19773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19774. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19776. */
  19777. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19778. var cylinder = new BABYLON.Mesh(name, scene);
  19779. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19780. vertexData.applyToMesh(cylinder, options.updatable);
  19781. return cylinder;
  19782. };
  19783. /**
  19784. * Creates a torus mesh.
  19785. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19786. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19787. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19788. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19789. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19792. */
  19793. MeshBuilder.CreateTorus = function (name, options, scene) {
  19794. var torus = new BABYLON.Mesh(name, scene);
  19795. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19796. vertexData.applyToMesh(torus, options.updatable);
  19797. return torus;
  19798. };
  19799. /**
  19800. * Creates a torus knot mesh.
  19801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19802. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19803. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19804. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19805. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19809. */
  19810. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19811. var torusKnot = new BABYLON.Mesh(name, scene);
  19812. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19813. vertexData.applyToMesh(torusKnot, options.updatable);
  19814. return torusKnot;
  19815. };
  19816. /**
  19817. * Creates a line system mesh.
  19818. * A line system is a pool of many lines gathered in a single mesh.
  19819. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19820. * 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.
  19821. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19822. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19823. * 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
  19824. * 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
  19825. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19827. */
  19828. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19829. var instance = options.instance;
  19830. var lines = options.lines;
  19831. if (instance) {
  19832. var positionFunction = function (positions) {
  19833. var i = 0;
  19834. for (var l = 0; l < lines.length; l++) {
  19835. var points = lines[l];
  19836. for (var p = 0; p < points.length; p++) {
  19837. positions[i] = points[p].x;
  19838. positions[i + 1] = points[p].y;
  19839. positions[i + 2] = points[p].z;
  19840. i += 3;
  19841. }
  19842. }
  19843. };
  19844. instance.updateMeshPositions(positionFunction, false);
  19845. return instance;
  19846. }
  19847. // line system creation
  19848. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19849. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19850. vertexData.applyToMesh(lineSystem, options.updatable);
  19851. return lineSystem;
  19852. };
  19853. /**
  19854. * Creates a line mesh.
  19855. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19856. * 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.
  19857. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19858. * The parameter `points` is an array successive Vector3.
  19859. * 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
  19860. * When updating an instance, remember that only point positions can change, not the number of points.
  19861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19862. */
  19863. MeshBuilder.CreateLines = function (name, options, scene) {
  19864. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19865. return lines;
  19866. };
  19867. /**
  19868. * Creates a dashed line mesh.
  19869. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19870. * 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.
  19871. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19872. * The parameter `points` is an array successive Vector3.
  19873. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19874. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19875. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19876. * 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
  19877. * When updating an instance, remember that only point positions can change, not the number of points.
  19878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19879. */
  19880. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19881. var points = options.points;
  19882. var instance = options.instance;
  19883. var gapSize = options.gapSize;
  19884. var dashNb = options.dashNb;
  19885. var dashSize = options.dashSize;
  19886. if (instance) {
  19887. var positionFunction = function (positions) {
  19888. var curvect = BABYLON.Vector3.Zero();
  19889. var nbSeg = positions.length / 6;
  19890. var lg = 0;
  19891. var nb = 0;
  19892. var shft = 0;
  19893. var dashshft = 0;
  19894. var curshft = 0;
  19895. var p = 0;
  19896. var i = 0;
  19897. var j = 0;
  19898. for (i = 0; i < points.length - 1; i++) {
  19899. points[i + 1].subtractToRef(points[i], curvect);
  19900. lg += curvect.length();
  19901. }
  19902. shft = lg / nbSeg;
  19903. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19904. for (i = 0; i < points.length - 1; i++) {
  19905. points[i + 1].subtractToRef(points[i], curvect);
  19906. nb = Math.floor(curvect.length() / shft);
  19907. curvect.normalize();
  19908. j = 0;
  19909. while (j < nb && p < positions.length) {
  19910. curshft = shft * j;
  19911. positions[p] = points[i].x + curshft * curvect.x;
  19912. positions[p + 1] = points[i].y + curshft * curvect.y;
  19913. positions[p + 2] = points[i].z + curshft * curvect.z;
  19914. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19915. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19916. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19917. p += 6;
  19918. j++;
  19919. }
  19920. }
  19921. while (p < positions.length) {
  19922. positions[p] = points[i].x;
  19923. positions[p + 1] = points[i].y;
  19924. positions[p + 2] = points[i].z;
  19925. p += 3;
  19926. }
  19927. };
  19928. instance.updateMeshPositions(positionFunction, false);
  19929. return instance;
  19930. }
  19931. // dashed lines creation
  19932. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19933. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19934. vertexData.applyToMesh(dashedLines, options.updatable);
  19935. dashedLines.dashSize = dashSize;
  19936. dashedLines.gapSize = gapSize;
  19937. return dashedLines;
  19938. };
  19939. /**
  19940. * Creates an extruded shape mesh.
  19941. * 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.
  19942. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19943. *
  19944. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19945. * 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
  19946. * extruded along the Z axis.
  19947. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19948. * 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.
  19949. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19950. * 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
  19951. * 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
  19952. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19953. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19954. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19956. */
  19957. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19958. var path = options.path;
  19959. var shape = options.shape;
  19960. var scale = options.scale || 1;
  19961. var rotation = options.rotation || 0;
  19962. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19963. var updatable = options.updatable;
  19964. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19965. var instance = options.instance;
  19966. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19967. };
  19968. /**
  19969. * Creates an custom extruded shape mesh.
  19970. * 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.
  19971. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19972. *
  19973. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19974. * 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
  19975. * extruded along the Z axis.
  19976. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19977. * 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
  19978. * and the distance of this point from the begining of the path :
  19979. * ```rotationFunction = function(i, distance) {
  19980. * // do things
  19981. * return rotationValue; }```
  19982. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19983. * 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
  19984. * and the distance of this point from the begining of the path :
  19985. * ````scaleFunction = function(i, distance) {
  19986. * // do things
  19987. * return scaleValue;}```
  19988. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19989. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19990. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19991. * 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
  19992. * 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
  19993. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19997. */
  19998. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19999. var path = options.path;
  20000. var shape = options.shape;
  20001. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20002. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20003. var ribbonCloseArray = options.ribbonCloseArray || false;
  20004. var ribbonClosePath = options.ribbonClosePath || false;
  20005. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20006. var updatable = options.updatable;
  20007. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20008. var instance = options.instance;
  20009. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  20010. };
  20011. /**
  20012. * Creates lathe mesh.
  20013. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20015. *
  20016. * 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
  20017. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20018. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20019. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20020. * 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.
  20021. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20022. * 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
  20023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20024. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20025. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20026. */
  20027. MeshBuilder.CreateLathe = function (name, options, scene) {
  20028. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20029. var closed = (options.closed === undefined) ? true : options.closed;
  20030. var shape = options.shape;
  20031. var radius = options.radius || 1;
  20032. var tessellation = options.tessellation || 64;
  20033. var updatable = options.updatable;
  20034. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20035. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20036. var pi2 = Math.PI * 2;
  20037. var paths = new Array();
  20038. var i = 0;
  20039. var p = 0;
  20040. var step = pi2 / tessellation * arc;
  20041. var rotated;
  20042. var path = new Array();
  20043. ;
  20044. for (i = 0; i <= tessellation; i++) {
  20045. var path = [];
  20046. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20047. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20048. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20049. }
  20050. for (p = 0; p < shape.length; p++) {
  20051. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20052. path.push(rotated);
  20053. }
  20054. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20055. 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));
  20056. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20057. }
  20058. paths.push(path);
  20059. }
  20060. // lathe ribbon
  20061. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  20062. return lathe;
  20063. };
  20064. /**
  20065. * Creates a plane mesh.
  20066. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20067. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20068. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20069. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  20070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20073. */
  20074. MeshBuilder.CreatePlane = function (name, options, scene) {
  20075. var plane = new BABYLON.Mesh(name, scene);
  20076. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20077. vertexData.applyToMesh(plane, options.updatable);
  20078. if (options.sourcePlane) {
  20079. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20080. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20081. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20082. plane.rotate(vectorProduct, product);
  20083. }
  20084. return plane;
  20085. };
  20086. /**
  20087. * Creates a ground mesh.
  20088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20089. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20090. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20092. */
  20093. MeshBuilder.CreateGround = function (name, options, scene) {
  20094. var ground = new BABYLON.GroundMesh(name, scene);
  20095. ground._setReady(false);
  20096. ground._subdivisions = options.subdivisions || 1;
  20097. ground._width = options.width || 1;
  20098. ground._height = options.height || 1;
  20099. ground._maxX = ground._width / 2;
  20100. ground._maxZ = ground._height / 2;
  20101. ground._minX = -ground._maxX;
  20102. ground._minZ = -ground._maxZ;
  20103. var vertexData = BABYLON.VertexData.CreateGround(options);
  20104. vertexData.applyToMesh(ground, options.updatable);
  20105. ground._setReady(true);
  20106. return ground;
  20107. };
  20108. /**
  20109. * Creates a tiled ground mesh.
  20110. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  20111. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20112. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20113. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20114. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20115. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20116. * numbers of subdivisions on the ground width and height of each tile.
  20117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20118. */
  20119. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  20120. var tiledGround = new BABYLON.Mesh(name, scene);
  20121. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  20122. vertexData.applyToMesh(tiledGround, options.updatable);
  20123. return tiledGround;
  20124. };
  20125. /**
  20126. * Creates a ground mesh from a height map.
  20127. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20128. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  20129. * The parameter `url` sets the URL of the height map image resource.
  20130. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20131. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20132. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20133. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20134. * 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).
  20135. * This function is passed the newly built mesh : ```function(mesh) { // do things
  20136. * return; }```
  20137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20138. */
  20139. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  20140. var width = options.width || 10;
  20141. var height = options.height || 10;
  20142. var subdivisions = options.subdivisions || 1;
  20143. var minHeight = options.minHeight;
  20144. var maxHeight = options.maxHeight || 10;
  20145. var updatable = options.updatable;
  20146. var onReady = options.onReady;
  20147. var ground = new BABYLON.GroundMesh(name, scene);
  20148. ground._subdivisions = subdivisions;
  20149. ground._width = width;
  20150. ground._height = height;
  20151. ground._maxX = ground._width / 2;
  20152. ground._maxZ = ground._height / 2;
  20153. ground._minX = -ground._maxX;
  20154. ground._minZ = -ground._maxZ;
  20155. ground._setReady(false);
  20156. var onload = function (img) {
  20157. // Getting height map data
  20158. var canvas = document.createElement("canvas");
  20159. var context = canvas.getContext("2d");
  20160. var bufferWidth = img.width;
  20161. var bufferHeight = img.height;
  20162. canvas.width = bufferWidth;
  20163. canvas.height = bufferHeight;
  20164. context.drawImage(img, 0, 0);
  20165. // Create VertexData from map data
  20166. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20167. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  20168. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  20169. width: width, height: height,
  20170. subdivisions: subdivisions,
  20171. minHeight: minHeight, maxHeight: maxHeight,
  20172. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  20173. });
  20174. vertexData.applyToMesh(ground, updatable);
  20175. ground._setReady(true);
  20176. //execute ready callback, if set
  20177. if (onReady) {
  20178. onReady(ground);
  20179. }
  20180. };
  20181. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20182. return ground;
  20183. };
  20184. /**
  20185. * Creates a tube mesh.
  20186. * 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.
  20187. *
  20188. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  20189. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  20190. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20191. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20192. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20193. * 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.
  20194. * It must return a radius value (positive float) :
  20195. * ```var radiusFunction = function(i, distance) {
  20196. * // do things
  20197. * return radius; }```
  20198. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  20199. * 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
  20200. * 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
  20201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20202. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20204. */
  20205. MeshBuilder.CreateTube = function (name, options, scene) {
  20206. var path = options.path;
  20207. var radius = options.radius || 1;
  20208. var tessellation = options.tessellation || 64;
  20209. var radiusFunction = options.radiusFunction;
  20210. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20211. var updatable = options.updatable;
  20212. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20213. var instance = options.instance;
  20214. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  20215. // tube geometry
  20216. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  20217. var tangents = path3D.getTangents();
  20218. var normals = path3D.getNormals();
  20219. var distances = path3D.getDistances();
  20220. var pi2 = Math.PI * 2;
  20221. var step = pi2 / tessellation * arc;
  20222. var returnRadius = function () { return radius; };
  20223. var radiusFunctionFinal = radiusFunction || returnRadius;
  20224. var circlePath;
  20225. var rad;
  20226. var normal;
  20227. var rotated;
  20228. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20229. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20230. for (var i = 0; i < path.length; i++) {
  20231. rad = radiusFunctionFinal(i, distances[i]); // current radius
  20232. circlePath = Array(); // current circle array
  20233. normal = normals[i]; // current normal
  20234. for (var t = 0; t < tessellation; t++) {
  20235. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  20236. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  20237. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  20238. rotated.scaleInPlace(rad).addInPlace(path[i]);
  20239. circlePath[t] = rotated;
  20240. }
  20241. circlePaths[index] = circlePath;
  20242. index++;
  20243. }
  20244. // cap
  20245. var capPath = function (nbPoints, pathIndex) {
  20246. var pointCap = Array();
  20247. for (var i = 0; i < nbPoints; i++) {
  20248. pointCap.push(path[pathIndex]);
  20249. }
  20250. return pointCap;
  20251. };
  20252. switch (cap) {
  20253. case BABYLON.Mesh.NO_CAP:
  20254. break;
  20255. case BABYLON.Mesh.CAP_START:
  20256. circlePaths[0] = capPath(tessellation, 0);
  20257. circlePaths[1] = circlePaths[2].slice(0);
  20258. break;
  20259. case BABYLON.Mesh.CAP_END:
  20260. circlePaths[index] = circlePaths[index - 1].slice(0);
  20261. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20262. break;
  20263. case BABYLON.Mesh.CAP_ALL:
  20264. circlePaths[0] = capPath(tessellation, 0);
  20265. circlePaths[1] = circlePaths[2].slice(0);
  20266. circlePaths[index] = circlePaths[index - 1].slice(0);
  20267. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  20268. break;
  20269. default:
  20270. break;
  20271. }
  20272. return circlePaths;
  20273. };
  20274. var path3D;
  20275. var pathArray;
  20276. if (instance) {
  20277. var arc = options.arc || instance.arc;
  20278. path3D = (instance.path3D).update(path);
  20279. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  20280. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  20281. instance.path3D = path3D;
  20282. instance.pathArray = pathArray;
  20283. instance.arc = arc;
  20284. return instance;
  20285. }
  20286. // tube creation
  20287. path3D = new BABYLON.Path3D(path);
  20288. var newPathArray = new Array();
  20289. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20290. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  20291. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  20292. tube.pathArray = pathArray;
  20293. tube.path3D = path3D;
  20294. tube.tessellation = tessellation;
  20295. tube.cap = cap;
  20296. tube.arc = options.arc;
  20297. return tube;
  20298. };
  20299. /**
  20300. * Creates a polyhedron mesh.
  20301. *
  20302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20303. * 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
  20304. * to choose the wanted type.
  20305. * The parameter `size` (positive float, default 1) sets the polygon size.
  20306. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20307. * 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`.
  20308. * 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
  20309. * 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)`).
  20310. * 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
  20311. * 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.
  20312. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20315. */
  20316. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20317. var polyhedron = new BABYLON.Mesh(name, scene);
  20318. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20319. vertexData.applyToMesh(polyhedron, options.updatable);
  20320. return polyhedron;
  20321. };
  20322. /**
  20323. * Creates a decal mesh.
  20324. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20325. * 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.
  20326. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20327. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20328. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  20329. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20330. */
  20331. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20332. var indices = sourceMesh.getIndices();
  20333. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20334. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20335. var position = options.position || BABYLON.Vector3.Zero();
  20336. var normal = options.normal || BABYLON.Vector3.Up();
  20337. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20338. var angle = options.angle || 0;
  20339. // Getting correct rotation
  20340. if (!normal) {
  20341. var target = new BABYLON.Vector3(0, 0, 1);
  20342. var camera = sourceMesh.getScene().activeCamera;
  20343. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20344. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20345. }
  20346. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20347. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20348. var pitch = Math.atan2(normal.y, len);
  20349. // Matrix
  20350. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20351. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20352. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20353. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20354. var vertexData = new BABYLON.VertexData();
  20355. vertexData.indices = [];
  20356. vertexData.positions = [];
  20357. vertexData.normals = [];
  20358. vertexData.uvs = [];
  20359. var currentVertexDataIndex = 0;
  20360. var extractDecalVector3 = function (indexId) {
  20361. var vertexId = indices[indexId];
  20362. var result = new BABYLON.PositionNormalVertex();
  20363. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20364. // Send vector to decal local world
  20365. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20366. // Get normal
  20367. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20368. return result;
  20369. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20370. var clip = function (vertices, axis) {
  20371. if (vertices.length === 0) {
  20372. return vertices;
  20373. }
  20374. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20375. var clipVertices = function (v0, v1) {
  20376. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20377. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20378. };
  20379. var result = new Array();
  20380. for (var index = 0; index < vertices.length; index += 3) {
  20381. var v1Out;
  20382. var v2Out;
  20383. var v3Out;
  20384. var total = 0;
  20385. var nV1, nV2, nV3, nV4;
  20386. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20387. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20388. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20389. v1Out = d1 > 0;
  20390. v2Out = d2 > 0;
  20391. v3Out = d3 > 0;
  20392. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20393. switch (total) {
  20394. case 0:
  20395. result.push(vertices[index]);
  20396. result.push(vertices[index + 1]);
  20397. result.push(vertices[index + 2]);
  20398. break;
  20399. case 1:
  20400. if (v1Out) {
  20401. nV1 = vertices[index + 1];
  20402. nV2 = vertices[index + 2];
  20403. nV3 = clipVertices(vertices[index], nV1);
  20404. nV4 = clipVertices(vertices[index], nV2);
  20405. }
  20406. if (v2Out) {
  20407. nV1 = vertices[index];
  20408. nV2 = vertices[index + 2];
  20409. nV3 = clipVertices(vertices[index + 1], nV1);
  20410. nV4 = clipVertices(vertices[index + 1], nV2);
  20411. result.push(nV3);
  20412. result.push(nV2.clone());
  20413. result.push(nV1.clone());
  20414. result.push(nV2.clone());
  20415. result.push(nV3.clone());
  20416. result.push(nV4);
  20417. break;
  20418. }
  20419. if (v3Out) {
  20420. nV1 = vertices[index];
  20421. nV2 = vertices[index + 1];
  20422. nV3 = clipVertices(vertices[index + 2], nV1);
  20423. nV4 = clipVertices(vertices[index + 2], nV2);
  20424. }
  20425. result.push(nV1.clone());
  20426. result.push(nV2.clone());
  20427. result.push(nV3);
  20428. result.push(nV4);
  20429. result.push(nV3.clone());
  20430. result.push(nV2.clone());
  20431. break;
  20432. case 2:
  20433. if (!v1Out) {
  20434. nV1 = vertices[index].clone();
  20435. nV2 = clipVertices(nV1, vertices[index + 1]);
  20436. nV3 = clipVertices(nV1, vertices[index + 2]);
  20437. result.push(nV1);
  20438. result.push(nV2);
  20439. result.push(nV3);
  20440. }
  20441. if (!v2Out) {
  20442. nV1 = vertices[index + 1].clone();
  20443. nV2 = clipVertices(nV1, vertices[index + 2]);
  20444. nV3 = clipVertices(nV1, vertices[index]);
  20445. result.push(nV1);
  20446. result.push(nV2);
  20447. result.push(nV3);
  20448. }
  20449. if (!v3Out) {
  20450. nV1 = vertices[index + 2].clone();
  20451. nV2 = clipVertices(nV1, vertices[index]);
  20452. nV3 = clipVertices(nV1, vertices[index + 1]);
  20453. result.push(nV1);
  20454. result.push(nV2);
  20455. result.push(nV3);
  20456. }
  20457. break;
  20458. case 3:
  20459. break;
  20460. }
  20461. }
  20462. return result;
  20463. };
  20464. for (var index = 0; index < indices.length; index += 3) {
  20465. var faceVertices = new Array();
  20466. faceVertices.push(extractDecalVector3(index));
  20467. faceVertices.push(extractDecalVector3(index + 1));
  20468. faceVertices.push(extractDecalVector3(index + 2));
  20469. // Clip
  20470. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20471. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20472. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20473. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20474. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20475. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20476. if (faceVertices.length === 0) {
  20477. continue;
  20478. }
  20479. // Add UVs and get back to world
  20480. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20481. var vertex = faceVertices[vIndex];
  20482. //TODO check for Int32Array
  20483. vertexData.indices.push(currentVertexDataIndex);
  20484. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20485. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20486. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20487. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20488. currentVertexDataIndex++;
  20489. }
  20490. }
  20491. // Return mesh
  20492. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20493. vertexData.applyToMesh(decal);
  20494. decal.position = position.clone();
  20495. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20496. return decal;
  20497. };
  20498. // Privates
  20499. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20500. // extrusion geometry
  20501. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20502. var tangents = path3D.getTangents();
  20503. var normals = path3D.getNormals();
  20504. var binormals = path3D.getBinormals();
  20505. var distances = path3D.getDistances();
  20506. var angle = 0;
  20507. var returnScale = function () { return scale; };
  20508. var returnRotation = function () { return rotation; };
  20509. var rotate = custom ? rotateFunction : returnRotation;
  20510. var scl = custom ? scaleFunction : returnScale;
  20511. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20512. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20513. for (var i = 0; i < curve.length; i++) {
  20514. var shapePath = new Array();
  20515. var angleStep = rotate(i, distances[i]);
  20516. var scaleRatio = scl(i, distances[i]);
  20517. for (var p = 0; p < shape.length; p++) {
  20518. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20519. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20520. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20521. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20522. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20523. shapePath[p] = rotated;
  20524. }
  20525. shapePaths[index] = shapePath;
  20526. angle += angleStep;
  20527. index++;
  20528. }
  20529. // cap
  20530. var capPath = function (shapePath) {
  20531. var pointCap = Array();
  20532. var barycenter = BABYLON.Vector3.Zero();
  20533. var i;
  20534. for (i = 0; i < shapePath.length; i++) {
  20535. barycenter.addInPlace(shapePath[i]);
  20536. }
  20537. barycenter.scaleInPlace(1 / shapePath.length);
  20538. for (i = 0; i < shapePath.length; i++) {
  20539. pointCap.push(barycenter);
  20540. }
  20541. return pointCap;
  20542. };
  20543. switch (cap) {
  20544. case BABYLON.Mesh.NO_CAP:
  20545. break;
  20546. case BABYLON.Mesh.CAP_START:
  20547. shapePaths[0] = capPath(shapePaths[2]);
  20548. shapePaths[1] = shapePaths[2].slice(0);
  20549. break;
  20550. case BABYLON.Mesh.CAP_END:
  20551. shapePaths[index] = shapePaths[index - 1];
  20552. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20553. break;
  20554. case BABYLON.Mesh.CAP_ALL:
  20555. shapePaths[0] = capPath(shapePaths[2]);
  20556. shapePaths[1] = shapePaths[2].slice(0);
  20557. shapePaths[index] = shapePaths[index - 1];
  20558. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20559. break;
  20560. default:
  20561. break;
  20562. }
  20563. return shapePaths;
  20564. };
  20565. var path3D;
  20566. var pathArray;
  20567. if (instance) {
  20568. path3D = (instance.path3D).update(curve);
  20569. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20570. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20571. return instance;
  20572. }
  20573. // extruded shape creation
  20574. path3D = new BABYLON.Path3D(curve);
  20575. var newShapePaths = new Array();
  20576. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20577. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20578. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20579. extrudedGeneric.pathArray = pathArray;
  20580. extrudedGeneric.path3D = path3D;
  20581. extrudedGeneric.cap = cap;
  20582. return extrudedGeneric;
  20583. };
  20584. return MeshBuilder;
  20585. })();
  20586. BABYLON.MeshBuilder = MeshBuilder;
  20587. })(BABYLON || (BABYLON = {}));
  20588. var BABYLON;
  20589. (function (BABYLON) {
  20590. var BaseTexture = (function () {
  20591. function BaseTexture(scene) {
  20592. this.hasAlpha = false;
  20593. this.getAlphaFromRGB = false;
  20594. this.level = 1;
  20595. this.coordinatesIndex = 0;
  20596. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20597. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20598. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20599. this.anisotropicFilteringLevel = 4;
  20600. this.isCube = false;
  20601. this.isRenderTarget = false;
  20602. this.animations = new Array();
  20603. /**
  20604. * An event triggered when the texture is disposed.
  20605. * @type {BABYLON.Observable}
  20606. */
  20607. this.onDisposeObservable = new BABYLON.Observable();
  20608. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20609. this._scene = scene;
  20610. this._scene.textures.push(this);
  20611. }
  20612. BaseTexture.prototype.toString = function () {
  20613. return this.name;
  20614. };
  20615. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20616. set: function (callback) {
  20617. if (this._onDisposeObserver) {
  20618. this.onDisposeObservable.remove(this._onDisposeObserver);
  20619. }
  20620. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20621. },
  20622. enumerable: true,
  20623. configurable: true
  20624. });
  20625. BaseTexture.prototype.getScene = function () {
  20626. return this._scene;
  20627. };
  20628. BaseTexture.prototype.getTextureMatrix = function () {
  20629. return null;
  20630. };
  20631. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20632. return null;
  20633. };
  20634. BaseTexture.prototype.getInternalTexture = function () {
  20635. return this._texture;
  20636. };
  20637. BaseTexture.prototype.isReady = function () {
  20638. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20639. return true;
  20640. }
  20641. if (this._texture) {
  20642. return this._texture.isReady;
  20643. }
  20644. return false;
  20645. };
  20646. BaseTexture.prototype.getSize = function () {
  20647. if (this._texture._width) {
  20648. return { width: this._texture._width, height: this._texture._height };
  20649. }
  20650. if (this._texture._size) {
  20651. return { width: this._texture._size, height: this._texture._size };
  20652. }
  20653. return { width: 0, height: 0 };
  20654. };
  20655. BaseTexture.prototype.getBaseSize = function () {
  20656. if (!this.isReady() || !this._texture)
  20657. return { width: 0, height: 0 };
  20658. if (this._texture._size) {
  20659. return { width: this._texture._size, height: this._texture._size };
  20660. }
  20661. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20662. };
  20663. BaseTexture.prototype.scale = function (ratio) {
  20664. };
  20665. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20666. get: function () {
  20667. return false;
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20673. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20674. for (var index = 0; index < texturesCache.length; index++) {
  20675. var texturesCacheEntry = texturesCache[index];
  20676. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20677. texturesCache.splice(index, 1);
  20678. return;
  20679. }
  20680. }
  20681. };
  20682. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20683. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20684. for (var index = 0; index < texturesCache.length; index++) {
  20685. var texturesCacheEntry = texturesCache[index];
  20686. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20687. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20688. texturesCacheEntry.references++;
  20689. return texturesCacheEntry;
  20690. }
  20691. }
  20692. }
  20693. return null;
  20694. };
  20695. BaseTexture.prototype.delayLoad = function () {
  20696. };
  20697. BaseTexture.prototype.clone = function () {
  20698. return null;
  20699. };
  20700. BaseTexture.prototype.releaseInternalTexture = function () {
  20701. if (this._texture) {
  20702. this._scene.getEngine().releaseInternalTexture(this._texture);
  20703. delete this._texture;
  20704. }
  20705. };
  20706. BaseTexture.prototype.dispose = function () {
  20707. // Animations
  20708. this.getScene().stopAnimation(this);
  20709. // Remove from scene
  20710. var index = this._scene.textures.indexOf(this);
  20711. if (index >= 0) {
  20712. this._scene.textures.splice(index, 1);
  20713. }
  20714. if (this._texture === undefined) {
  20715. return;
  20716. }
  20717. // Release
  20718. this.releaseInternalTexture();
  20719. // Callback
  20720. this.onDisposeObservable.notifyObservers(this);
  20721. this.onDisposeObservable.clear();
  20722. };
  20723. BaseTexture.prototype.serialize = function () {
  20724. if (!this.name) {
  20725. return null;
  20726. }
  20727. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20728. // Animations
  20729. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20730. return serializationObject;
  20731. };
  20732. __decorate([
  20733. BABYLON.serialize()
  20734. ], BaseTexture.prototype, "name", void 0);
  20735. __decorate([
  20736. BABYLON.serialize()
  20737. ], BaseTexture.prototype, "hasAlpha", void 0);
  20738. __decorate([
  20739. BABYLON.serialize()
  20740. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20741. __decorate([
  20742. BABYLON.serialize()
  20743. ], BaseTexture.prototype, "level", void 0);
  20744. __decorate([
  20745. BABYLON.serialize()
  20746. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20747. __decorate([
  20748. BABYLON.serialize()
  20749. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20750. __decorate([
  20751. BABYLON.serialize()
  20752. ], BaseTexture.prototype, "wrapU", void 0);
  20753. __decorate([
  20754. BABYLON.serialize()
  20755. ], BaseTexture.prototype, "wrapV", void 0);
  20756. __decorate([
  20757. BABYLON.serialize()
  20758. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20759. __decorate([
  20760. BABYLON.serialize()
  20761. ], BaseTexture.prototype, "isCube", void 0);
  20762. __decorate([
  20763. BABYLON.serialize()
  20764. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20765. return BaseTexture;
  20766. })();
  20767. BABYLON.BaseTexture = BaseTexture;
  20768. })(BABYLON || (BABYLON = {}));
  20769. var BABYLON;
  20770. (function (BABYLON) {
  20771. var Texture = (function (_super) {
  20772. __extends(Texture, _super);
  20773. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20774. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20775. if (onLoad === void 0) { onLoad = null; }
  20776. if (onError === void 0) { onError = null; }
  20777. if (buffer === void 0) { buffer = null; }
  20778. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20779. _super.call(this, scene);
  20780. this.uOffset = 0;
  20781. this.vOffset = 0;
  20782. this.uScale = 1.0;
  20783. this.vScale = 1.0;
  20784. this.uAng = 0;
  20785. this.vAng = 0;
  20786. this.wAng = 0;
  20787. this.name = url;
  20788. this.url = url;
  20789. this._noMipmap = noMipmap;
  20790. this._invertY = invertY;
  20791. this._samplingMode = samplingMode;
  20792. this._buffer = buffer;
  20793. this._deleteBuffer = deleteBuffer;
  20794. if (!url) {
  20795. return;
  20796. }
  20797. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20798. if (!this._texture) {
  20799. if (!scene.useDelayedTextureLoading) {
  20800. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20801. if (deleteBuffer) {
  20802. delete this._buffer;
  20803. }
  20804. }
  20805. else {
  20806. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20807. this._delayedOnLoad = onLoad;
  20808. this._delayedOnError = onError;
  20809. }
  20810. }
  20811. else {
  20812. BABYLON.Tools.SetImmediate(function () {
  20813. if (onLoad) {
  20814. onLoad();
  20815. }
  20816. });
  20817. }
  20818. }
  20819. Object.defineProperty(Texture.prototype, "noMipmap", {
  20820. get: function () {
  20821. return this._noMipmap;
  20822. },
  20823. enumerable: true,
  20824. configurable: true
  20825. });
  20826. Texture.prototype.delayLoad = function () {
  20827. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20828. return;
  20829. }
  20830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20831. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20832. if (!this._texture) {
  20833. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20834. if (this._deleteBuffer) {
  20835. delete this._buffer;
  20836. }
  20837. }
  20838. };
  20839. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20840. if (!this._texture) {
  20841. return;
  20842. }
  20843. this._samplingMode = samplingMode;
  20844. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20845. };
  20846. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20847. x *= this.uScale;
  20848. y *= this.vScale;
  20849. x -= 0.5 * this.uScale;
  20850. y -= 0.5 * this.vScale;
  20851. z -= 0.5;
  20852. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20853. t.x += 0.5 * this.uScale + this.uOffset;
  20854. t.y += 0.5 * this.vScale + this.vOffset;
  20855. t.z += 0.5;
  20856. };
  20857. Texture.prototype.getTextureMatrix = function () {
  20858. if (this.uOffset === this._cachedUOffset &&
  20859. this.vOffset === this._cachedVOffset &&
  20860. this.uScale === this._cachedUScale &&
  20861. this.vScale === this._cachedVScale &&
  20862. this.uAng === this._cachedUAng &&
  20863. this.vAng === this._cachedVAng &&
  20864. this.wAng === this._cachedWAng) {
  20865. return this._cachedTextureMatrix;
  20866. }
  20867. this._cachedUOffset = this.uOffset;
  20868. this._cachedVOffset = this.vOffset;
  20869. this._cachedUScale = this.uScale;
  20870. this._cachedVScale = this.vScale;
  20871. this._cachedUAng = this.uAng;
  20872. this._cachedVAng = this.vAng;
  20873. this._cachedWAng = this.wAng;
  20874. if (!this._cachedTextureMatrix) {
  20875. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20876. this._rowGenerationMatrix = new BABYLON.Matrix();
  20877. this._t0 = BABYLON.Vector3.Zero();
  20878. this._t1 = BABYLON.Vector3.Zero();
  20879. this._t2 = BABYLON.Vector3.Zero();
  20880. }
  20881. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20882. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20883. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20884. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20885. this._t1.subtractInPlace(this._t0);
  20886. this._t2.subtractInPlace(this._t0);
  20887. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20888. this._cachedTextureMatrix.m[0] = this._t1.x;
  20889. this._cachedTextureMatrix.m[1] = this._t1.y;
  20890. this._cachedTextureMatrix.m[2] = this._t1.z;
  20891. this._cachedTextureMatrix.m[4] = this._t2.x;
  20892. this._cachedTextureMatrix.m[5] = this._t2.y;
  20893. this._cachedTextureMatrix.m[6] = this._t2.z;
  20894. this._cachedTextureMatrix.m[8] = this._t0.x;
  20895. this._cachedTextureMatrix.m[9] = this._t0.y;
  20896. this._cachedTextureMatrix.m[10] = this._t0.z;
  20897. return this._cachedTextureMatrix;
  20898. };
  20899. Texture.prototype.getReflectionTextureMatrix = function () {
  20900. if (this.uOffset === this._cachedUOffset &&
  20901. this.vOffset === this._cachedVOffset &&
  20902. this.uScale === this._cachedUScale &&
  20903. this.vScale === this._cachedVScale &&
  20904. this.coordinatesMode === this._cachedCoordinatesMode) {
  20905. return this._cachedTextureMatrix;
  20906. }
  20907. if (!this._cachedTextureMatrix) {
  20908. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20909. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20910. }
  20911. this._cachedCoordinatesMode = this.coordinatesMode;
  20912. switch (this.coordinatesMode) {
  20913. case Texture.PLANAR_MODE:
  20914. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20915. this._cachedTextureMatrix[0] = this.uScale;
  20916. this._cachedTextureMatrix[5] = this.vScale;
  20917. this._cachedTextureMatrix[12] = this.uOffset;
  20918. this._cachedTextureMatrix[13] = this.vOffset;
  20919. break;
  20920. case Texture.PROJECTION_MODE:
  20921. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20922. this._projectionModeMatrix.m[0] = 0.5;
  20923. this._projectionModeMatrix.m[5] = -0.5;
  20924. this._projectionModeMatrix.m[10] = 0.0;
  20925. this._projectionModeMatrix.m[12] = 0.5;
  20926. this._projectionModeMatrix.m[13] = 0.5;
  20927. this._projectionModeMatrix.m[14] = 1.0;
  20928. this._projectionModeMatrix.m[15] = 1.0;
  20929. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20930. break;
  20931. default:
  20932. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20933. break;
  20934. }
  20935. return this._cachedTextureMatrix;
  20936. };
  20937. Texture.prototype.clone = function () {
  20938. var _this = this;
  20939. return BABYLON.SerializationHelper.Clone(function () {
  20940. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20941. }, this);
  20942. };
  20943. // Statics
  20944. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20945. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20946. if (onLoad === void 0) { onLoad = null; }
  20947. if (onError === void 0) { onError = null; }
  20948. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20949. };
  20950. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20951. if (parsedTexture.isCube) {
  20952. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20953. }
  20954. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20955. return null;
  20956. }
  20957. var texture = BABYLON.SerializationHelper.Parse(function () {
  20958. if (parsedTexture.mirrorPlane) {
  20959. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20960. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20961. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20962. return mirrorTexture;
  20963. }
  20964. else if (parsedTexture.isRenderTarget) {
  20965. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20966. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20967. return renderTargetTexture;
  20968. }
  20969. else {
  20970. var texture;
  20971. if (parsedTexture.base64String) {
  20972. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20973. }
  20974. else {
  20975. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20976. }
  20977. return texture;
  20978. }
  20979. }, parsedTexture, scene);
  20980. // Animations
  20981. if (parsedTexture.animations) {
  20982. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20983. var parsedAnimation = parsedTexture.animations[animationIndex];
  20984. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20985. }
  20986. }
  20987. return texture;
  20988. };
  20989. // Constants
  20990. Texture.NEAREST_SAMPLINGMODE = 1;
  20991. Texture.BILINEAR_SAMPLINGMODE = 2;
  20992. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20993. Texture.EXPLICIT_MODE = 0;
  20994. Texture.SPHERICAL_MODE = 1;
  20995. Texture.PLANAR_MODE = 2;
  20996. Texture.CUBIC_MODE = 3;
  20997. Texture.PROJECTION_MODE = 4;
  20998. Texture.SKYBOX_MODE = 5;
  20999. Texture.INVCUBIC_MODE = 6;
  21000. Texture.EQUIRECTANGULAR_MODE = 7;
  21001. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21002. Texture.CLAMP_ADDRESSMODE = 0;
  21003. Texture.WRAP_ADDRESSMODE = 1;
  21004. Texture.MIRROR_ADDRESSMODE = 2;
  21005. __decorate([
  21006. BABYLON.serialize()
  21007. ], Texture.prototype, "url", void 0);
  21008. __decorate([
  21009. BABYLON.serialize()
  21010. ], Texture.prototype, "uOffset", void 0);
  21011. __decorate([
  21012. BABYLON.serialize()
  21013. ], Texture.prototype, "vOffset", void 0);
  21014. __decorate([
  21015. BABYLON.serialize()
  21016. ], Texture.prototype, "uScale", void 0);
  21017. __decorate([
  21018. BABYLON.serialize()
  21019. ], Texture.prototype, "vScale", void 0);
  21020. __decorate([
  21021. BABYLON.serialize()
  21022. ], Texture.prototype, "uAng", void 0);
  21023. __decorate([
  21024. BABYLON.serialize()
  21025. ], Texture.prototype, "vAng", void 0);
  21026. __decorate([
  21027. BABYLON.serialize()
  21028. ], Texture.prototype, "wAng", void 0);
  21029. return Texture;
  21030. })(BABYLON.BaseTexture);
  21031. BABYLON.Texture = Texture;
  21032. })(BABYLON || (BABYLON = {}));
  21033. var BABYLON;
  21034. (function (BABYLON) {
  21035. var CubeTexture = (function (_super) {
  21036. __extends(CubeTexture, _super);
  21037. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21038. _super.call(this, scene);
  21039. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21040. this.name = rootUrl;
  21041. this.url = rootUrl;
  21042. this._noMipmap = noMipmap;
  21043. this.hasAlpha = false;
  21044. if (!rootUrl && !files) {
  21045. return;
  21046. }
  21047. this._texture = this._getFromCache(rootUrl, noMipmap);
  21048. if (!files) {
  21049. if (!extensions) {
  21050. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21051. }
  21052. files = [];
  21053. for (var index = 0; index < extensions.length; index++) {
  21054. files.push(rootUrl + extensions[index]);
  21055. }
  21056. this._extensions = extensions;
  21057. }
  21058. this._files = files;
  21059. if (!this._texture) {
  21060. if (!scene.useDelayedTextureLoading) {
  21061. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21062. }
  21063. else {
  21064. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21065. }
  21066. }
  21067. this.isCube = true;
  21068. this._textureMatrix = BABYLON.Matrix.Identity();
  21069. }
  21070. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21071. return new CubeTexture("", scene, null, noMipmap, files);
  21072. };
  21073. // Methods
  21074. CubeTexture.prototype.delayLoad = function () {
  21075. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21076. return;
  21077. }
  21078. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21079. this._texture = this._getFromCache(this.url, this._noMipmap);
  21080. if (!this._texture) {
  21081. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  21082. }
  21083. };
  21084. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  21085. return this._textureMatrix;
  21086. };
  21087. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  21088. var texture = BABYLON.SerializationHelper.Parse(function () {
  21089. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  21090. }, parsedTexture, scene);
  21091. // Animations
  21092. if (parsedTexture.animations) {
  21093. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21094. var parsedAnimation = parsedTexture.animations[animationIndex];
  21095. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21096. }
  21097. }
  21098. return texture;
  21099. };
  21100. CubeTexture.prototype.clone = function () {
  21101. var _this = this;
  21102. return BABYLON.SerializationHelper.Clone(function () {
  21103. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  21104. }, this);
  21105. };
  21106. return CubeTexture;
  21107. })(BABYLON.BaseTexture);
  21108. BABYLON.CubeTexture = CubeTexture;
  21109. })(BABYLON || (BABYLON = {}));
  21110. var BABYLON;
  21111. (function (BABYLON) {
  21112. var RenderTargetTexture = (function (_super) {
  21113. __extends(RenderTargetTexture, _super);
  21114. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  21115. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  21116. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21117. if (isCube === void 0) { isCube = false; }
  21118. _super.call(this, null, scene, !generateMipMaps);
  21119. this.isCube = isCube;
  21120. /**
  21121. * Use this list to define the list of mesh you want to render.
  21122. */
  21123. this.renderList = new Array();
  21124. this.renderParticles = true;
  21125. this.renderSprites = false;
  21126. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  21127. // Events
  21128. /**
  21129. * An event triggered when the texture is unbind.
  21130. * @type {BABYLON.Observable}
  21131. */
  21132. this.onAfterUnbindObservable = new BABYLON.Observable();
  21133. /**
  21134. * An event triggered before rendering the texture
  21135. * @type {BABYLON.Observable}
  21136. */
  21137. this.onBeforeRenderObservable = new BABYLON.Observable();
  21138. /**
  21139. * An event triggered after rendering the texture
  21140. * @type {BABYLON.Observable}
  21141. */
  21142. this.onAfterRenderObservable = new BABYLON.Observable();
  21143. /**
  21144. * An event triggered after the texture clear
  21145. * @type {BABYLON.Observable}
  21146. */
  21147. this.onClearObservable = new BABYLON.Observable();
  21148. this._currentRefreshId = -1;
  21149. this._refreshRate = 1;
  21150. this.name = name;
  21151. this.isRenderTarget = true;
  21152. this._size = size;
  21153. this._generateMipMaps = generateMipMaps;
  21154. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  21155. if (isCube) {
  21156. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21157. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  21158. this._textureMatrix = BABYLON.Matrix.Identity();
  21159. }
  21160. else {
  21161. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  21162. }
  21163. // Rendering groups
  21164. this._renderingManager = new BABYLON.RenderingManager(scene);
  21165. }
  21166. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  21167. get: function () {
  21168. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  21174. get: function () {
  21175. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  21176. },
  21177. enumerable: true,
  21178. configurable: true
  21179. });
  21180. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  21181. get: function () {
  21182. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  21188. set: function (callback) {
  21189. if (this._onAfterUnbindObserver) {
  21190. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  21191. }
  21192. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  21193. },
  21194. enumerable: true,
  21195. configurable: true
  21196. });
  21197. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  21198. set: function (callback) {
  21199. if (this._onBeforeRenderObserver) {
  21200. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21201. }
  21202. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21203. },
  21204. enumerable: true,
  21205. configurable: true
  21206. });
  21207. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  21208. set: function (callback) {
  21209. if (this._onAfterRenderObserver) {
  21210. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21211. }
  21212. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21213. },
  21214. enumerable: true,
  21215. configurable: true
  21216. });
  21217. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  21218. set: function (callback) {
  21219. if (this._onClearObserver) {
  21220. this.onClearObservable.remove(this._onClearObserver);
  21221. }
  21222. this._onClearObserver = this.onClearObservable.add(callback);
  21223. },
  21224. enumerable: true,
  21225. configurable: true
  21226. });
  21227. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  21228. this._currentRefreshId = -1;
  21229. };
  21230. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  21231. get: function () {
  21232. return this._refreshRate;
  21233. },
  21234. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21235. set: function (value) {
  21236. this._refreshRate = value;
  21237. this.resetRefreshCounter();
  21238. },
  21239. enumerable: true,
  21240. configurable: true
  21241. });
  21242. RenderTargetTexture.prototype._shouldRender = function () {
  21243. if (this._currentRefreshId === -1) {
  21244. this._currentRefreshId = 1;
  21245. return true;
  21246. }
  21247. if (this.refreshRate === this._currentRefreshId) {
  21248. this._currentRefreshId = 1;
  21249. return true;
  21250. }
  21251. this._currentRefreshId++;
  21252. return false;
  21253. };
  21254. RenderTargetTexture.prototype.isReady = function () {
  21255. if (!this.getScene().renderTargetsEnabled) {
  21256. return false;
  21257. }
  21258. return _super.prototype.isReady.call(this);
  21259. };
  21260. RenderTargetTexture.prototype.getRenderSize = function () {
  21261. return this._size;
  21262. };
  21263. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  21264. get: function () {
  21265. return true;
  21266. },
  21267. enumerable: true,
  21268. configurable: true
  21269. });
  21270. RenderTargetTexture.prototype.scale = function (ratio) {
  21271. var newSize = this._size * ratio;
  21272. this.resize(newSize, this._generateMipMaps);
  21273. };
  21274. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  21275. if (this.isCube) {
  21276. return this._textureMatrix;
  21277. }
  21278. return _super.prototype.getReflectionTextureMatrix.call(this);
  21279. };
  21280. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  21281. this.releaseInternalTexture();
  21282. if (this.isCube) {
  21283. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  21284. }
  21285. else {
  21286. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21287. }
  21288. };
  21289. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  21290. var scene = this.getScene();
  21291. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21292. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  21293. }
  21294. if (this._waitingRenderList) {
  21295. this.renderList = [];
  21296. for (var index = 0; index < this._waitingRenderList.length; index++) {
  21297. var id = this._waitingRenderList[index];
  21298. this.renderList.push(scene.getMeshByID(id));
  21299. }
  21300. delete this._waitingRenderList;
  21301. }
  21302. // Is predicate defined?
  21303. if (this.renderListPredicate) {
  21304. this.renderList.splice(0); // Clear previous renderList
  21305. var sceneMeshes = this.getScene().meshes;
  21306. for (var index = 0; index < sceneMeshes.length; index++) {
  21307. var mesh = sceneMeshes[index];
  21308. if (this.renderListPredicate(mesh)) {
  21309. this.renderList.push(mesh);
  21310. }
  21311. }
  21312. }
  21313. if (this.renderList && this.renderList.length === 0) {
  21314. return;
  21315. }
  21316. // Prepare renderingManager
  21317. this._renderingManager.reset();
  21318. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  21319. var sceneRenderId = scene.getRenderId();
  21320. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  21321. var mesh = currentRenderList[meshIndex];
  21322. if (mesh) {
  21323. if (!mesh.isReady()) {
  21324. // Reset _currentRefreshId
  21325. this.resetRefreshCounter();
  21326. continue;
  21327. }
  21328. mesh._preActivateForIntermediateRendering(sceneRenderId);
  21329. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  21330. mesh._activate(sceneRenderId);
  21331. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  21332. var subMesh = mesh.subMeshes[subIndex];
  21333. scene._activeIndices += subMesh.indexCount;
  21334. this._renderingManager.dispatch(subMesh);
  21335. }
  21336. }
  21337. }
  21338. }
  21339. if (this.isCube) {
  21340. for (var face = 0; face < 6; face++) {
  21341. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  21342. scene.incrementRenderId();
  21343. scene.resetCachedMaterial();
  21344. }
  21345. }
  21346. else {
  21347. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  21348. }
  21349. this.onAfterUnbindObservable.notifyObservers(this);
  21350. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  21351. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  21352. }
  21353. scene.resetCachedMaterial();
  21354. };
  21355. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  21356. var scene = this.getScene();
  21357. var engine = scene.getEngine();
  21358. // Bind
  21359. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  21360. if (this.isCube) {
  21361. engine.bindFramebuffer(this._texture, faceIndex);
  21362. }
  21363. else {
  21364. engine.bindFramebuffer(this._texture);
  21365. }
  21366. }
  21367. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  21368. // Clear
  21369. if (this.onClearObservable.hasObservers()) {
  21370. this.onClearObservable.notifyObservers(engine);
  21371. }
  21372. else {
  21373. engine.clear(scene.clearColor, true, true);
  21374. }
  21375. if (!this._doNotChangeAspectRatio) {
  21376. scene.updateTransformMatrix(true);
  21377. }
  21378. // Render
  21379. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  21380. if (useCameraPostProcess) {
  21381. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  21382. }
  21383. if (!this._doNotChangeAspectRatio) {
  21384. scene.updateTransformMatrix(true);
  21385. }
  21386. this.onAfterRenderObservable.notifyObservers(faceIndex);
  21387. // Dump ?
  21388. if (dumpForDebug) {
  21389. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  21390. }
  21391. // Unbind
  21392. if (!this.isCube || faceIndex === 5) {
  21393. if (this.isCube) {
  21394. if (faceIndex === 5) {
  21395. engine.generateMipMapsForCubemap(this._texture);
  21396. }
  21397. }
  21398. engine.unBindFramebuffer(this._texture, this.isCube);
  21399. }
  21400. };
  21401. RenderTargetTexture.prototype.clone = function () {
  21402. var textureSize = this.getSize();
  21403. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21404. // Base texture
  21405. newTexture.hasAlpha = this.hasAlpha;
  21406. newTexture.level = this.level;
  21407. // RenderTarget Texture
  21408. newTexture.coordinatesMode = this.coordinatesMode;
  21409. newTexture.renderList = this.renderList.slice(0);
  21410. return newTexture;
  21411. };
  21412. RenderTargetTexture.prototype.serialize = function () {
  21413. if (!this.name) {
  21414. return null;
  21415. }
  21416. var serializationObject = _super.prototype.serialize.call(this);
  21417. serializationObject.renderTargetSize = this.getRenderSize();
  21418. serializationObject.renderList = [];
  21419. for (var index = 0; index < this.renderList.length; index++) {
  21420. serializationObject.renderList.push(this.renderList[index].id);
  21421. }
  21422. return serializationObject;
  21423. };
  21424. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21425. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21426. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21427. return RenderTargetTexture;
  21428. })(BABYLON.Texture);
  21429. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21430. })(BABYLON || (BABYLON = {}));
  21431. var BABYLON;
  21432. (function (BABYLON) {
  21433. var ProceduralTexture = (function (_super) {
  21434. __extends(ProceduralTexture, _super);
  21435. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21436. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21437. if (isCube === void 0) { isCube = false; }
  21438. _super.call(this, null, scene, !generateMipMaps);
  21439. this.isCube = isCube;
  21440. this.isEnabled = true;
  21441. this._currentRefreshId = -1;
  21442. this._refreshRate = 1;
  21443. this._vertexDeclaration = [2];
  21444. this._vertexStrideSize = 2 * 4;
  21445. this._uniforms = new Array();
  21446. this._samplers = new Array();
  21447. this._textures = new Array();
  21448. this._floats = new Array();
  21449. this._floatsArrays = {};
  21450. this._colors3 = new Array();
  21451. this._colors4 = new Array();
  21452. this._vectors2 = new Array();
  21453. this._vectors3 = new Array();
  21454. this._matrices = new Array();
  21455. this._fallbackTextureUsed = false;
  21456. scene._proceduralTextures.push(this);
  21457. this.name = name;
  21458. this.isRenderTarget = true;
  21459. this._size = size;
  21460. this._generateMipMaps = generateMipMaps;
  21461. this.setFragment(fragment);
  21462. this._fallbackTexture = fallbackTexture;
  21463. if (isCube) {
  21464. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21465. this.setFloat("face", 0);
  21466. }
  21467. else {
  21468. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  21469. }
  21470. // VBO
  21471. var vertices = [];
  21472. vertices.push(1, 1);
  21473. vertices.push(-1, 1);
  21474. vertices.push(-1, -1);
  21475. vertices.push(1, -1);
  21476. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21477. // Indices
  21478. var indices = [];
  21479. indices.push(0);
  21480. indices.push(1);
  21481. indices.push(2);
  21482. indices.push(0);
  21483. indices.push(2);
  21484. indices.push(3);
  21485. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21486. }
  21487. ProceduralTexture.prototype.reset = function () {
  21488. if (this._effect === undefined) {
  21489. return;
  21490. }
  21491. var engine = this.getScene().getEngine();
  21492. engine._releaseEffect(this._effect);
  21493. };
  21494. ProceduralTexture.prototype.isReady = function () {
  21495. var _this = this;
  21496. var engine = this.getScene().getEngine();
  21497. var shaders;
  21498. if (!this._fragment) {
  21499. return false;
  21500. }
  21501. if (this._fallbackTextureUsed) {
  21502. return true;
  21503. }
  21504. if (this._fragment.fragmentElement !== undefined) {
  21505. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21506. }
  21507. else {
  21508. shaders = { vertex: "procedural", fragment: this._fragment };
  21509. }
  21510. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  21511. _this.releaseInternalTexture();
  21512. if (_this._fallbackTexture) {
  21513. _this._texture = _this._fallbackTexture._texture;
  21514. _this._texture.references++;
  21515. }
  21516. _this._fallbackTextureUsed = true;
  21517. });
  21518. return this._effect.isReady();
  21519. };
  21520. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21521. this._currentRefreshId = -1;
  21522. };
  21523. ProceduralTexture.prototype.setFragment = function (fragment) {
  21524. this._fragment = fragment;
  21525. };
  21526. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21527. get: function () {
  21528. return this._refreshRate;
  21529. },
  21530. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21531. set: function (value) {
  21532. this._refreshRate = value;
  21533. this.resetRefreshCounter();
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. ProceduralTexture.prototype._shouldRender = function () {
  21539. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21540. return false;
  21541. }
  21542. if (this._fallbackTextureUsed) {
  21543. return false;
  21544. }
  21545. if (this._currentRefreshId === -1) {
  21546. this._currentRefreshId = 1;
  21547. return true;
  21548. }
  21549. if (this.refreshRate === this._currentRefreshId) {
  21550. this._currentRefreshId = 1;
  21551. return true;
  21552. }
  21553. this._currentRefreshId++;
  21554. return false;
  21555. };
  21556. ProceduralTexture.prototype.getRenderSize = function () {
  21557. return this._size;
  21558. };
  21559. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21560. if (this._fallbackTextureUsed) {
  21561. return;
  21562. }
  21563. this.releaseInternalTexture();
  21564. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21565. };
  21566. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21567. if (this._uniforms.indexOf(uniformName) === -1) {
  21568. this._uniforms.push(uniformName);
  21569. }
  21570. };
  21571. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21572. if (this._samplers.indexOf(name) === -1) {
  21573. this._samplers.push(name);
  21574. }
  21575. this._textures[name] = texture;
  21576. return this;
  21577. };
  21578. ProceduralTexture.prototype.setFloat = function (name, value) {
  21579. this._checkUniform(name);
  21580. this._floats[name] = value;
  21581. return this;
  21582. };
  21583. ProceduralTexture.prototype.setFloats = function (name, value) {
  21584. this._checkUniform(name);
  21585. this._floatsArrays[name] = value;
  21586. return this;
  21587. };
  21588. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21589. this._checkUniform(name);
  21590. this._colors3[name] = value;
  21591. return this;
  21592. };
  21593. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21594. this._checkUniform(name);
  21595. this._colors4[name] = value;
  21596. return this;
  21597. };
  21598. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21599. this._checkUniform(name);
  21600. this._vectors2[name] = value;
  21601. return this;
  21602. };
  21603. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21604. this._checkUniform(name);
  21605. this._vectors3[name] = value;
  21606. return this;
  21607. };
  21608. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21609. this._checkUniform(name);
  21610. this._matrices[name] = value;
  21611. return this;
  21612. };
  21613. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21614. var scene = this.getScene();
  21615. var engine = scene.getEngine();
  21616. // Render
  21617. engine.enableEffect(this._effect);
  21618. engine.setState(false);
  21619. // Texture
  21620. for (var name in this._textures) {
  21621. this._effect.setTexture(name, this._textures[name]);
  21622. }
  21623. // Float
  21624. for (name in this._floats) {
  21625. this._effect.setFloat(name, this._floats[name]);
  21626. }
  21627. // Floats
  21628. for (name in this._floatsArrays) {
  21629. this._effect.setArray(name, this._floatsArrays[name]);
  21630. }
  21631. // Color3
  21632. for (name in this._colors3) {
  21633. this._effect.setColor3(name, this._colors3[name]);
  21634. }
  21635. // Color4
  21636. for (name in this._colors4) {
  21637. var color = this._colors4[name];
  21638. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21639. }
  21640. // Vector2
  21641. for (name in this._vectors2) {
  21642. this._effect.setVector2(name, this._vectors2[name]);
  21643. }
  21644. // Vector3
  21645. for (name in this._vectors3) {
  21646. this._effect.setVector3(name, this._vectors3[name]);
  21647. }
  21648. // Matrix
  21649. for (name in this._matrices) {
  21650. this._effect.setMatrix(name, this._matrices[name]);
  21651. }
  21652. // VBOs
  21653. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21654. if (this.isCube) {
  21655. for (var face = 0; face < 6; face++) {
  21656. engine.bindFramebuffer(this._texture, face);
  21657. this._effect.setFloat("face", face);
  21658. // Clear
  21659. engine.clear(scene.clearColor, true, true);
  21660. // Draw order
  21661. engine.draw(true, 0, 6);
  21662. // Mipmaps
  21663. if (face === 5) {
  21664. engine.generateMipMapsForCubemap(this._texture);
  21665. }
  21666. }
  21667. }
  21668. else {
  21669. engine.bindFramebuffer(this._texture);
  21670. // Clear
  21671. engine.clear(scene.clearColor, true, true);
  21672. // Draw order
  21673. engine.draw(true, 0, 6);
  21674. }
  21675. // Unbind
  21676. engine.unBindFramebuffer(this._texture, this.isCube);
  21677. if (this.onGenerated) {
  21678. this.onGenerated();
  21679. }
  21680. };
  21681. ProceduralTexture.prototype.clone = function () {
  21682. var textureSize = this.getSize();
  21683. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21684. // Base texture
  21685. newTexture.hasAlpha = this.hasAlpha;
  21686. newTexture.level = this.level;
  21687. // RenderTarget Texture
  21688. newTexture.coordinatesMode = this.coordinatesMode;
  21689. return newTexture;
  21690. };
  21691. ProceduralTexture.prototype.dispose = function () {
  21692. var index = this.getScene()._proceduralTextures.indexOf(this);
  21693. if (index >= 0) {
  21694. this.getScene()._proceduralTextures.splice(index, 1);
  21695. }
  21696. _super.prototype.dispose.call(this);
  21697. };
  21698. return ProceduralTexture;
  21699. })(BABYLON.Texture);
  21700. BABYLON.ProceduralTexture = ProceduralTexture;
  21701. })(BABYLON || (BABYLON = {}));
  21702. var BABYLON;
  21703. (function (BABYLON) {
  21704. var MirrorTexture = (function (_super) {
  21705. __extends(MirrorTexture, _super);
  21706. function MirrorTexture(name, size, scene, generateMipMaps) {
  21707. var _this = this;
  21708. _super.call(this, name, size, scene, generateMipMaps, true);
  21709. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21710. this._transformMatrix = BABYLON.Matrix.Zero();
  21711. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21712. this.onBeforeRenderObservable.add(function () {
  21713. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21714. _this._savedViewMatrix = scene.getViewMatrix();
  21715. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21716. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21717. scene.clipPlane = _this.mirrorPlane;
  21718. scene.getEngine().cullBackFaces = false;
  21719. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21720. });
  21721. this.onAfterRenderObservable.add(function () {
  21722. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21723. scene.getEngine().cullBackFaces = true;
  21724. scene._mirroredCameraPosition = null;
  21725. delete scene.clipPlane;
  21726. });
  21727. }
  21728. MirrorTexture.prototype.clone = function () {
  21729. var textureSize = this.getSize();
  21730. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21731. // Base texture
  21732. newTexture.hasAlpha = this.hasAlpha;
  21733. newTexture.level = this.level;
  21734. // Mirror Texture
  21735. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21736. newTexture.renderList = this.renderList.slice(0);
  21737. return newTexture;
  21738. };
  21739. MirrorTexture.prototype.serialize = function () {
  21740. if (!this.name) {
  21741. return null;
  21742. }
  21743. var serializationObject = _super.prototype.serialize.call(this);
  21744. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21745. return serializationObject;
  21746. };
  21747. return MirrorTexture;
  21748. })(BABYLON.RenderTargetTexture);
  21749. BABYLON.MirrorTexture = MirrorTexture;
  21750. })(BABYLON || (BABYLON = {}));
  21751. var BABYLON;
  21752. (function (BABYLON) {
  21753. /**
  21754. * Creates a refraction texture used by refraction channel of the standard material.
  21755. * @param name the texture name
  21756. * @param size size of the underlying texture
  21757. * @param scene root scene
  21758. */
  21759. var RefractionTexture = (function (_super) {
  21760. __extends(RefractionTexture, _super);
  21761. function RefractionTexture(name, size, scene, generateMipMaps) {
  21762. var _this = this;
  21763. _super.call(this, name, size, scene, generateMipMaps, true);
  21764. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21765. this.depth = 2.0;
  21766. this.onBeforeRenderObservable.add(function () {
  21767. scene.clipPlane = _this.refractionPlane;
  21768. });
  21769. this.onAfterRenderObservable.add(function () {
  21770. delete scene.clipPlane;
  21771. });
  21772. }
  21773. RefractionTexture.prototype.clone = function () {
  21774. var textureSize = this.getSize();
  21775. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21776. // Base texture
  21777. newTexture.hasAlpha = this.hasAlpha;
  21778. newTexture.level = this.level;
  21779. // Refraction Texture
  21780. newTexture.refractionPlane = this.refractionPlane.clone();
  21781. newTexture.renderList = this.renderList.slice(0);
  21782. newTexture.depth = this.depth;
  21783. return newTexture;
  21784. };
  21785. RefractionTexture.prototype.serialize = function () {
  21786. if (!this.name) {
  21787. return null;
  21788. }
  21789. var serializationObject = _super.prototype.serialize.call(this);
  21790. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21791. serializationObject.depth = this.depth;
  21792. return serializationObject;
  21793. };
  21794. return RefractionTexture;
  21795. })(BABYLON.RenderTargetTexture);
  21796. BABYLON.RefractionTexture = RefractionTexture;
  21797. })(BABYLON || (BABYLON = {}));
  21798. var BABYLON;
  21799. (function (BABYLON) {
  21800. var DynamicTexture = (function (_super) {
  21801. __extends(DynamicTexture, _super);
  21802. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21803. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21804. _super.call(this, null, scene, !generateMipMaps);
  21805. this.name = name;
  21806. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21807. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21808. this._generateMipMaps = generateMipMaps;
  21809. if (options.getContext) {
  21810. this._canvas = options;
  21811. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21812. }
  21813. else {
  21814. this._canvas = document.createElement("canvas");
  21815. if (options.width) {
  21816. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21817. }
  21818. else {
  21819. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21820. }
  21821. }
  21822. var textureSize = this.getSize();
  21823. this._canvas.width = textureSize.width;
  21824. this._canvas.height = textureSize.height;
  21825. this._context = this._canvas.getContext("2d");
  21826. }
  21827. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21828. get: function () {
  21829. return true;
  21830. },
  21831. enumerable: true,
  21832. configurable: true
  21833. });
  21834. DynamicTexture.prototype.scale = function (ratio) {
  21835. var textureSize = this.getSize();
  21836. textureSize.width *= ratio;
  21837. textureSize.height *= ratio;
  21838. this._canvas.width = textureSize.width;
  21839. this._canvas.height = textureSize.height;
  21840. this.releaseInternalTexture();
  21841. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21842. };
  21843. DynamicTexture.prototype.getContext = function () {
  21844. return this._context;
  21845. };
  21846. DynamicTexture.prototype.clear = function () {
  21847. var size = this.getSize();
  21848. this._context.fillRect(0, 0, size.width, size.height);
  21849. };
  21850. DynamicTexture.prototype.update = function (invertY) {
  21851. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21852. };
  21853. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21854. if (update === void 0) { update = true; }
  21855. var size = this.getSize();
  21856. if (clearColor) {
  21857. this._context.fillStyle = clearColor;
  21858. this._context.fillRect(0, 0, size.width, size.height);
  21859. }
  21860. this._context.font = font;
  21861. if (x === null) {
  21862. var textSize = this._context.measureText(text);
  21863. x = (size.width - textSize.width) / 2;
  21864. }
  21865. this._context.fillStyle = color;
  21866. this._context.fillText(text, x, y);
  21867. if (update) {
  21868. this.update(invertY);
  21869. }
  21870. };
  21871. DynamicTexture.prototype.clone = function () {
  21872. var textureSize = this.getSize();
  21873. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21874. // Base texture
  21875. newTexture.hasAlpha = this.hasAlpha;
  21876. newTexture.level = this.level;
  21877. // Dynamic Texture
  21878. newTexture.wrapU = this.wrapU;
  21879. newTexture.wrapV = this.wrapV;
  21880. return newTexture;
  21881. };
  21882. return DynamicTexture;
  21883. })(BABYLON.Texture);
  21884. BABYLON.DynamicTexture = DynamicTexture;
  21885. })(BABYLON || (BABYLON = {}));
  21886. var BABYLON;
  21887. (function (BABYLON) {
  21888. var VideoTexture = (function (_super) {
  21889. __extends(VideoTexture, _super);
  21890. /**
  21891. * Creates a video texture.
  21892. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21893. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21894. * @param {BABYLON.Scene} scene is obviously the current scene.
  21895. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21896. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21897. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21898. */
  21899. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21900. var _this = this;
  21901. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21902. if (invertY === void 0) { invertY = false; }
  21903. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21904. _super.call(this, null, scene, !generateMipMaps, invertY);
  21905. this._autoLaunch = true;
  21906. var urls;
  21907. this.name = name;
  21908. if (urlsOrVideo instanceof HTMLVideoElement) {
  21909. this.video = urlsOrVideo;
  21910. }
  21911. else {
  21912. urls = urlsOrVideo;
  21913. this.video = document.createElement("video");
  21914. this.video.autoplay = false;
  21915. this.video.loop = true;
  21916. }
  21917. this._generateMipMaps = generateMipMaps;
  21918. this._samplingMode = samplingMode;
  21919. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21920. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21921. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21922. }
  21923. else {
  21924. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21925. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21926. this._generateMipMaps = false;
  21927. }
  21928. if (urls) {
  21929. this.video.addEventListener("canplaythrough", function () {
  21930. _this._createTexture();
  21931. });
  21932. urls.forEach(function (url) {
  21933. var source = document.createElement("source");
  21934. source.src = url;
  21935. _this.video.appendChild(source);
  21936. });
  21937. }
  21938. else {
  21939. this._createTexture();
  21940. }
  21941. this._lastUpdate = BABYLON.Tools.Now;
  21942. }
  21943. VideoTexture.prototype._createTexture = function () {
  21944. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21945. this._texture.isReady = true;
  21946. };
  21947. VideoTexture.prototype.update = function () {
  21948. if (this._autoLaunch) {
  21949. this._autoLaunch = false;
  21950. this.video.play();
  21951. }
  21952. var now = BABYLON.Tools.Now;
  21953. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21954. return false;
  21955. }
  21956. this._lastUpdate = now;
  21957. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21958. return true;
  21959. };
  21960. return VideoTexture;
  21961. })(BABYLON.Texture);
  21962. BABYLON.VideoTexture = VideoTexture;
  21963. })(BABYLON || (BABYLON = {}));
  21964. var BABYLON;
  21965. (function (BABYLON) {
  21966. var CustomProceduralTexture = (function (_super) {
  21967. __extends(CustomProceduralTexture, _super);
  21968. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21969. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21970. this._animate = true;
  21971. this._time = 0;
  21972. this._texturePath = texturePath;
  21973. //Try to load json
  21974. this.loadJson(texturePath);
  21975. this.refreshRate = 1;
  21976. }
  21977. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21978. var _this = this;
  21979. var that = this;
  21980. function noConfigFile() {
  21981. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21982. try {
  21983. that.setFragment(that._texturePath);
  21984. }
  21985. catch (ex) {
  21986. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21987. }
  21988. }
  21989. var configFileUrl = jsonUrl + "/config.json";
  21990. var xhr = new XMLHttpRequest();
  21991. xhr.open("GET", configFileUrl, true);
  21992. xhr.addEventListener("load", function () {
  21993. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21994. try {
  21995. _this._config = JSON.parse(xhr.response);
  21996. _this.updateShaderUniforms();
  21997. _this.updateTextures();
  21998. _this.setFragment(_this._texturePath + "/custom");
  21999. _this._animate = _this._config.animate;
  22000. _this.refreshRate = _this._config.refreshrate;
  22001. }
  22002. catch (ex) {
  22003. noConfigFile();
  22004. }
  22005. }
  22006. else {
  22007. noConfigFile();
  22008. }
  22009. }, false);
  22010. xhr.addEventListener("error", function () {
  22011. noConfigFile();
  22012. }, false);
  22013. try {
  22014. xhr.send();
  22015. }
  22016. catch (ex) {
  22017. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22018. }
  22019. };
  22020. CustomProceduralTexture.prototype.isReady = function () {
  22021. if (!_super.prototype.isReady.call(this)) {
  22022. return false;
  22023. }
  22024. for (var name in this._textures) {
  22025. var texture = this._textures[name];
  22026. if (!texture.isReady()) {
  22027. return false;
  22028. }
  22029. }
  22030. return true;
  22031. };
  22032. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22033. if (this._animate) {
  22034. this._time += this.getScene().getAnimationRatio() * 0.03;
  22035. this.updateShaderUniforms();
  22036. }
  22037. _super.prototype.render.call(this, useCameraPostProcess);
  22038. };
  22039. CustomProceduralTexture.prototype.updateTextures = function () {
  22040. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22041. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22042. }
  22043. };
  22044. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22045. if (this._config) {
  22046. for (var j = 0; j < this._config.uniforms.length; j++) {
  22047. var uniform = this._config.uniforms[j];
  22048. switch (uniform.type) {
  22049. case "float":
  22050. this.setFloat(uniform.name, uniform.value);
  22051. break;
  22052. case "color3":
  22053. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22054. break;
  22055. case "color4":
  22056. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22057. break;
  22058. case "vector2":
  22059. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22060. break;
  22061. case "vector3":
  22062. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  22063. break;
  22064. }
  22065. }
  22066. }
  22067. this.setFloat("time", this._time);
  22068. };
  22069. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  22070. get: function () {
  22071. return this._animate;
  22072. },
  22073. set: function (value) {
  22074. this._animate = value;
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. return CustomProceduralTexture;
  22080. })(BABYLON.ProceduralTexture);
  22081. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  22082. })(BABYLON || (BABYLON = {}));
  22083. var BABYLON;
  22084. (function (BABYLON) {
  22085. var EffectFallbacks = (function () {
  22086. function EffectFallbacks() {
  22087. this._defines = {};
  22088. this._currentRank = 32;
  22089. this._maxRank = -1;
  22090. }
  22091. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22092. if (!this._defines[rank]) {
  22093. if (rank < this._currentRank) {
  22094. this._currentRank = rank;
  22095. }
  22096. if (rank > this._maxRank) {
  22097. this._maxRank = rank;
  22098. }
  22099. this._defines[rank] = new Array();
  22100. }
  22101. this._defines[rank].push(define);
  22102. };
  22103. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22104. this._meshRank = rank;
  22105. this._mesh = mesh;
  22106. if (rank > this._maxRank) {
  22107. this._maxRank = rank;
  22108. }
  22109. };
  22110. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22111. get: function () {
  22112. return this._currentRank <= this._maxRank;
  22113. },
  22114. enumerable: true,
  22115. configurable: true
  22116. });
  22117. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22118. var currentFallbacks = this._defines[this._currentRank];
  22119. for (var index = 0; index < currentFallbacks.length; index++) {
  22120. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22121. }
  22122. if (this._mesh && this._currentRank === this._meshRank) {
  22123. this._mesh.computeBonesUsingShaders = false;
  22124. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22125. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22126. }
  22127. this._currentRank++;
  22128. return currentDefines;
  22129. };
  22130. return EffectFallbacks;
  22131. })();
  22132. BABYLON.EffectFallbacks = EffectFallbacks;
  22133. var Effect = (function () {
  22134. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22135. var _this = this;
  22136. this._isReady = false;
  22137. this._compilationError = "";
  22138. this._valueCache = [];
  22139. this._engine = engine;
  22140. this.name = baseName;
  22141. this.defines = defines;
  22142. this._uniformsNames = uniformsNames.concat(samplers);
  22143. this._samplers = samplers;
  22144. this._attributesNames = attributesNames;
  22145. this.onError = onError;
  22146. this.onCompiled = onCompiled;
  22147. this._indexParameters = indexParameters;
  22148. var vertexSource;
  22149. var fragmentSource;
  22150. if (baseName.vertexElement) {
  22151. vertexSource = document.getElementById(baseName.vertexElement);
  22152. if (!vertexSource) {
  22153. vertexSource = baseName.vertexElement;
  22154. }
  22155. }
  22156. else {
  22157. vertexSource = baseName.vertex || baseName;
  22158. }
  22159. if (baseName.fragmentElement) {
  22160. fragmentSource = document.getElementById(baseName.fragmentElement);
  22161. if (!fragmentSource) {
  22162. fragmentSource = baseName.fragmentElement;
  22163. }
  22164. }
  22165. else {
  22166. fragmentSource = baseName.fragment || baseName;
  22167. }
  22168. this._loadVertexShader(vertexSource, function (vertexCode) {
  22169. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22170. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22171. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22172. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  22173. });
  22174. });
  22175. });
  22176. });
  22177. }
  22178. // Properties
  22179. Effect.prototype.isReady = function () {
  22180. return this._isReady;
  22181. };
  22182. Effect.prototype.getProgram = function () {
  22183. return this._program;
  22184. };
  22185. Effect.prototype.getAttributesNames = function () {
  22186. return this._attributesNames;
  22187. };
  22188. Effect.prototype.getAttributeLocation = function (index) {
  22189. return this._attributes[index];
  22190. };
  22191. Effect.prototype.getAttributeLocationByName = function (name) {
  22192. var index = this._attributesNames.indexOf(name);
  22193. return this._attributes[index];
  22194. };
  22195. Effect.prototype.getAttributesCount = function () {
  22196. return this._attributes.length;
  22197. };
  22198. Effect.prototype.getUniformIndex = function (uniformName) {
  22199. return this._uniformsNames.indexOf(uniformName);
  22200. };
  22201. Effect.prototype.getUniform = function (uniformName) {
  22202. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22203. };
  22204. Effect.prototype.getSamplers = function () {
  22205. return this._samplers;
  22206. };
  22207. Effect.prototype.getCompilationError = function () {
  22208. return this._compilationError;
  22209. };
  22210. // Methods
  22211. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22212. // DOM element ?
  22213. if (vertex instanceof HTMLElement) {
  22214. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22215. callback(vertexCode);
  22216. return;
  22217. }
  22218. // Is in local store ?
  22219. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22220. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22221. return;
  22222. }
  22223. var vertexShaderUrl;
  22224. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22225. vertexShaderUrl = vertex;
  22226. }
  22227. else {
  22228. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22229. }
  22230. // Vertex shader
  22231. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22232. };
  22233. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22234. // DOM element ?
  22235. if (fragment instanceof HTMLElement) {
  22236. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22237. callback(fragmentCode);
  22238. return;
  22239. }
  22240. // Is in local store ?
  22241. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22242. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22243. return;
  22244. }
  22245. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22246. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22247. return;
  22248. }
  22249. var fragmentShaderUrl;
  22250. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22251. fragmentShaderUrl = fragment;
  22252. }
  22253. else {
  22254. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22255. }
  22256. // Fragment shader
  22257. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22258. };
  22259. Effect.prototype._dumpShadersName = function () {
  22260. if (this.name.vertexElement) {
  22261. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  22262. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  22263. }
  22264. else if (this.name.vertex) {
  22265. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  22266. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  22267. }
  22268. else {
  22269. BABYLON.Tools.Error("Vertex shader:" + this.name);
  22270. BABYLON.Tools.Error("Fragment shader:" + this.name);
  22271. }
  22272. };
  22273. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22274. var _this = this;
  22275. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22276. var match = regex.exec(sourceCode);
  22277. var returnValue = new String(sourceCode);
  22278. while (match != null) {
  22279. var includeFile = match[1];
  22280. if (Effect.IncludesShadersStore[includeFile]) {
  22281. // Substitution
  22282. var includeContent = Effect.IncludesShadersStore[includeFile];
  22283. if (match[2]) {
  22284. var splits = match[3].split(",");
  22285. for (var index = 0; index < splits.length; index += 2) {
  22286. var source = new RegExp(splits[index], "g");
  22287. var dest = splits[index + 1];
  22288. includeContent = includeContent.replace(source, dest);
  22289. }
  22290. }
  22291. if (match[4]) {
  22292. var indexString = match[5];
  22293. if (indexString.indexOf("..") !== -1) {
  22294. var indexSplits = indexString.split("..");
  22295. var minIndex = parseInt(indexSplits[0]);
  22296. var maxIndex = parseInt(indexSplits[1]);
  22297. var sourceIncludeContent = includeContent.slice(0);
  22298. includeContent = "";
  22299. if (isNaN(maxIndex)) {
  22300. maxIndex = this._indexParameters[indexSplits[1]];
  22301. }
  22302. for (var i = minIndex; i <= maxIndex; i++) {
  22303. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22304. }
  22305. }
  22306. else {
  22307. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22308. }
  22309. }
  22310. // Replace
  22311. returnValue = returnValue.replace(match[0], includeContent);
  22312. }
  22313. else {
  22314. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22315. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22316. Effect.IncludesShadersStore[includeFile] = fileContent;
  22317. _this._processIncludes(returnValue, callback);
  22318. });
  22319. return;
  22320. }
  22321. match = regex.exec(sourceCode);
  22322. }
  22323. callback(returnValue);
  22324. };
  22325. Effect.prototype._processPrecision = function (source) {
  22326. if (source.indexOf("precision highp float") === -1) {
  22327. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22328. source = "precision mediump float;\n" + source;
  22329. }
  22330. else {
  22331. source = "precision highp float;\n" + source;
  22332. }
  22333. }
  22334. else {
  22335. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22336. source = source.replace("precision highp float", "precision mediump float");
  22337. }
  22338. }
  22339. return source;
  22340. };
  22341. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22342. try {
  22343. var engine = this._engine;
  22344. // Precision
  22345. vertexSourceCode = this._processPrecision(vertexSourceCode);
  22346. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  22347. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22348. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22349. this._attributes = engine.getAttributes(this._program, attributesNames);
  22350. for (var index = 0; index < this._samplers.length; index++) {
  22351. var sampler = this.getUniform(this._samplers[index]);
  22352. if (sampler == null) {
  22353. this._samplers.splice(index, 1);
  22354. index--;
  22355. }
  22356. }
  22357. engine.bindSamplers(this);
  22358. this._isReady = true;
  22359. if (this.onCompiled) {
  22360. this.onCompiled(this);
  22361. }
  22362. }
  22363. catch (e) {
  22364. // Is it a problem with precision?
  22365. if (e.message.indexOf("highp") !== -1) {
  22366. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  22367. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  22368. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22369. return;
  22370. }
  22371. // Let's go through fallbacks then
  22372. if (fallbacks && fallbacks.isMoreFallbacks) {
  22373. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  22374. this._dumpShadersName();
  22375. defines = fallbacks.reduce(defines);
  22376. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22377. }
  22378. else {
  22379. BABYLON.Tools.Error("Unable to compile effect: ");
  22380. this._dumpShadersName();
  22381. BABYLON.Tools.Error("Defines: " + defines);
  22382. BABYLON.Tools.Error("Error: " + e.message);
  22383. this._compilationError = e.message;
  22384. if (this.onError) {
  22385. this.onError(this, this._compilationError);
  22386. }
  22387. }
  22388. }
  22389. };
  22390. Object.defineProperty(Effect.prototype, "isSupported", {
  22391. get: function () {
  22392. return this._compilationError === "";
  22393. },
  22394. enumerable: true,
  22395. configurable: true
  22396. });
  22397. Effect.prototype._bindTexture = function (channel, texture) {
  22398. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22399. };
  22400. Effect.prototype.setTexture = function (channel, texture) {
  22401. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22402. };
  22403. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22404. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22405. };
  22406. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22407. if (!this._valueCache[uniformName]) {
  22408. this._valueCache[uniformName] = new BABYLON.Matrix();
  22409. }
  22410. for (var index = 0; index < 16; index++) {
  22411. this._valueCache[uniformName].m[index] = matrix.m[index];
  22412. }
  22413. };
  22414. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22415. if (!this._valueCache[uniformName]) {
  22416. this._valueCache[uniformName] = [x, y];
  22417. return;
  22418. }
  22419. this._valueCache[uniformName][0] = x;
  22420. this._valueCache[uniformName][1] = y;
  22421. };
  22422. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22423. if (!this._valueCache[uniformName]) {
  22424. this._valueCache[uniformName] = [x, y, z];
  22425. return;
  22426. }
  22427. this._valueCache[uniformName][0] = x;
  22428. this._valueCache[uniformName][1] = y;
  22429. this._valueCache[uniformName][2] = z;
  22430. };
  22431. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22432. if (!this._valueCache[uniformName]) {
  22433. this._valueCache[uniformName] = [x, y, z, w];
  22434. return;
  22435. }
  22436. this._valueCache[uniformName][0] = x;
  22437. this._valueCache[uniformName][1] = y;
  22438. this._valueCache[uniformName][2] = z;
  22439. this._valueCache[uniformName][3] = w;
  22440. };
  22441. Effect.prototype.setArray = function (uniformName, array) {
  22442. this._engine.setArray(this.getUniform(uniformName), array);
  22443. return this;
  22444. };
  22445. Effect.prototype.setArray2 = function (uniformName, array) {
  22446. this._engine.setArray2(this.getUniform(uniformName), array);
  22447. return this;
  22448. };
  22449. Effect.prototype.setArray3 = function (uniformName, array) {
  22450. this._engine.setArray3(this.getUniform(uniformName), array);
  22451. return this;
  22452. };
  22453. Effect.prototype.setArray4 = function (uniformName, array) {
  22454. this._engine.setArray4(this.getUniform(uniformName), array);
  22455. return this;
  22456. };
  22457. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22458. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22459. return this;
  22460. };
  22461. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22462. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22463. // return this;
  22464. // this._cacheMatrix(uniformName, matrix);
  22465. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22466. return this;
  22467. };
  22468. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22469. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22470. return this;
  22471. };
  22472. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22473. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22474. return this;
  22475. };
  22476. Effect.prototype.setFloat = function (uniformName, value) {
  22477. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22478. return this;
  22479. this._valueCache[uniformName] = value;
  22480. this._engine.setFloat(this.getUniform(uniformName), value);
  22481. return this;
  22482. };
  22483. Effect.prototype.setBool = function (uniformName, bool) {
  22484. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22485. return this;
  22486. this._valueCache[uniformName] = bool;
  22487. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22488. return this;
  22489. };
  22490. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22491. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22492. return this;
  22493. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22494. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22495. return this;
  22496. };
  22497. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22498. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22499. return this;
  22500. this._cacheFloat2(uniformName, x, y);
  22501. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22502. return this;
  22503. };
  22504. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22505. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22506. return this;
  22507. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22508. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22509. return this;
  22510. };
  22511. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22512. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22513. return this;
  22514. this._cacheFloat3(uniformName, x, y, z);
  22515. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22516. return this;
  22517. };
  22518. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22519. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  22520. return this;
  22521. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22522. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22523. return this;
  22524. };
  22525. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22526. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22527. return this;
  22528. this._cacheFloat4(uniformName, x, y, z, w);
  22529. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22530. return this;
  22531. };
  22532. Effect.prototype.setColor3 = function (uniformName, color3) {
  22533. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22534. return this;
  22535. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22536. this._engine.setColor3(this.getUniform(uniformName), color3);
  22537. return this;
  22538. };
  22539. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22540. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  22541. return this;
  22542. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22543. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22544. return this;
  22545. };
  22546. // Statics
  22547. Effect.ShadersStore = {};
  22548. Effect.IncludesShadersStore = {};
  22549. return Effect;
  22550. })();
  22551. BABYLON.Effect = Effect;
  22552. })(BABYLON || (BABYLON = {}));
  22553. var BABYLON;
  22554. (function (BABYLON) {
  22555. var MaterialHelper = (function () {
  22556. function MaterialHelper() {
  22557. }
  22558. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22559. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22560. var lightIndex = 0;
  22561. var needNormals = false;
  22562. var needRebuild = false;
  22563. for (var index = 0; index < scene.lights.length; index++) {
  22564. var light = scene.lights[index];
  22565. if (!light.isEnabled()) {
  22566. continue;
  22567. }
  22568. // Excluded check
  22569. if (light._excludedMeshesIds.length > 0) {
  22570. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22571. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22572. if (excludedMesh) {
  22573. light.excludedMeshes.push(excludedMesh);
  22574. }
  22575. }
  22576. light._excludedMeshesIds = [];
  22577. }
  22578. // Included check
  22579. if (light._includedOnlyMeshesIds.length > 0) {
  22580. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22581. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22582. if (includedOnlyMesh) {
  22583. light.includedOnlyMeshes.push(includedOnlyMesh);
  22584. }
  22585. }
  22586. light._includedOnlyMeshesIds = [];
  22587. }
  22588. if (!light.canAffectMesh(mesh)) {
  22589. continue;
  22590. }
  22591. needNormals = true;
  22592. if (defines["LIGHT" + lightIndex] === undefined) {
  22593. needRebuild = true;
  22594. }
  22595. defines["LIGHT" + lightIndex] = true;
  22596. var type;
  22597. if (light instanceof BABYLON.SpotLight) {
  22598. type = "SPOTLIGHT" + lightIndex;
  22599. }
  22600. else if (light instanceof BABYLON.HemisphericLight) {
  22601. type = "HEMILIGHT" + lightIndex;
  22602. }
  22603. else if (light instanceof BABYLON.PointLight) {
  22604. type = "POINTLIGHT" + lightIndex;
  22605. }
  22606. else {
  22607. type = "DIRLIGHT" + lightIndex;
  22608. }
  22609. if (defines[type] === undefined) {
  22610. needRebuild = true;
  22611. }
  22612. defines[type] = true;
  22613. // Specular
  22614. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22615. defines["SPECULARTERM"] = true;
  22616. }
  22617. // Shadows
  22618. if (scene.shadowsEnabled) {
  22619. var shadowGenerator = light.getShadowGenerator();
  22620. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22621. if (defines["SHADOW" + lightIndex] === undefined) {
  22622. needRebuild = true;
  22623. }
  22624. defines["SHADOW" + lightIndex] = true;
  22625. defines["SHADOWS"] = true;
  22626. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22627. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22628. needRebuild = true;
  22629. }
  22630. defines["SHADOWVSM" + lightIndex] = true;
  22631. }
  22632. if (shadowGenerator.usePoissonSampling) {
  22633. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22634. needRebuild = true;
  22635. }
  22636. defines["SHADOWPCF" + lightIndex] = true;
  22637. }
  22638. }
  22639. }
  22640. lightIndex++;
  22641. if (lightIndex === maxSimultaneousLights)
  22642. break;
  22643. }
  22644. if (needRebuild) {
  22645. defines.rebuild();
  22646. }
  22647. return needNormals;
  22648. };
  22649. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22650. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22651. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22652. if (!defines["LIGHT" + lightIndex]) {
  22653. break;
  22654. }
  22655. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22656. samplersList.push("shadowSampler" + lightIndex);
  22657. }
  22658. };
  22659. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22660. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22661. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22662. if (!defines["LIGHT" + lightIndex]) {
  22663. break;
  22664. }
  22665. if (lightIndex > 0) {
  22666. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22667. }
  22668. if (defines["SHADOW" + lightIndex]) {
  22669. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22670. }
  22671. if (defines["SHADOWPCF" + lightIndex]) {
  22672. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22673. }
  22674. if (defines["SHADOWVSM" + lightIndex]) {
  22675. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22676. }
  22677. }
  22678. };
  22679. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22680. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22681. fallbacks.addCPUSkinningFallback(0, mesh);
  22682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22684. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22687. }
  22688. }
  22689. };
  22690. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22691. if (defines["INSTANCES"]) {
  22692. attribs.push("world0");
  22693. attribs.push("world1");
  22694. attribs.push("world2");
  22695. attribs.push("world3");
  22696. }
  22697. };
  22698. // Bindings
  22699. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22700. var shadowGenerator = light.getShadowGenerator();
  22701. if (mesh.receiveShadows && shadowGenerator) {
  22702. if (!light.needCube()) {
  22703. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22704. }
  22705. else {
  22706. if (!depthValuesAlreadySet) {
  22707. depthValuesAlreadySet = true;
  22708. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22709. }
  22710. }
  22711. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22712. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22713. }
  22714. return depthValuesAlreadySet;
  22715. };
  22716. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22717. if (light instanceof BABYLON.PointLight) {
  22718. // Point Light
  22719. light.transferToEffect(effect, "vLightData" + lightIndex);
  22720. }
  22721. else if (light instanceof BABYLON.DirectionalLight) {
  22722. // Directional Light
  22723. light.transferToEffect(effect, "vLightData" + lightIndex);
  22724. }
  22725. else if (light instanceof BABYLON.SpotLight) {
  22726. // Spot Light
  22727. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22728. }
  22729. else if (light instanceof BABYLON.HemisphericLight) {
  22730. // Hemispheric Light
  22731. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22732. }
  22733. };
  22734. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22735. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22736. var lightIndex = 0;
  22737. var depthValuesAlreadySet = false;
  22738. for (var index = 0; index < scene.lights.length; index++) {
  22739. var light = scene.lights[index];
  22740. if (!light.isEnabled()) {
  22741. continue;
  22742. }
  22743. if (!light.canAffectMesh(mesh)) {
  22744. continue;
  22745. }
  22746. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22747. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22748. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22749. if (defines["SPECULARTERM"]) {
  22750. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22751. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22752. }
  22753. // Shadows
  22754. if (scene.shadowsEnabled) {
  22755. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22756. }
  22757. lightIndex++;
  22758. if (lightIndex === maxSimultaneousLights)
  22759. break;
  22760. }
  22761. };
  22762. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22763. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22764. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22765. effect.setColor3("vFogColor", scene.fogColor);
  22766. }
  22767. };
  22768. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22769. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22770. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22771. }
  22772. };
  22773. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22774. if (defines["LOGARITHMICDEPTH"]) {
  22775. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22776. }
  22777. };
  22778. MaterialHelper.BindClipPlane = function (effect, scene) {
  22779. if (scene.clipPlane) {
  22780. var clipPlane = scene.clipPlane;
  22781. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22782. }
  22783. };
  22784. return MaterialHelper;
  22785. })();
  22786. BABYLON.MaterialHelper = MaterialHelper;
  22787. })(BABYLON || (BABYLON = {}));
  22788. var BABYLON;
  22789. (function (BABYLON) {
  22790. var FresnelParameters = (function () {
  22791. function FresnelParameters() {
  22792. this.isEnabled = true;
  22793. this.leftColor = BABYLON.Color3.White();
  22794. this.rightColor = BABYLON.Color3.Black();
  22795. this.bias = 0;
  22796. this.power = 1;
  22797. }
  22798. FresnelParameters.prototype.clone = function () {
  22799. var newFresnelParameters = new FresnelParameters();
  22800. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22801. return new FresnelParameters;
  22802. };
  22803. FresnelParameters.prototype.serialize = function () {
  22804. var serializationObject = {};
  22805. serializationObject.isEnabled = this.isEnabled;
  22806. serializationObject.leftColor = this.leftColor;
  22807. serializationObject.rightColor = this.rightColor;
  22808. serializationObject.bias = this.bias;
  22809. serializationObject.power = this.power;
  22810. return serializationObject;
  22811. };
  22812. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22813. var fresnelParameters = new FresnelParameters();
  22814. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22815. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22816. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22817. fresnelParameters.bias = parsedFresnelParameters.bias;
  22818. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22819. return fresnelParameters;
  22820. };
  22821. return FresnelParameters;
  22822. })();
  22823. BABYLON.FresnelParameters = FresnelParameters;
  22824. })(BABYLON || (BABYLON = {}));
  22825. var BABYLON;
  22826. (function (BABYLON) {
  22827. var MaterialDefines = (function () {
  22828. function MaterialDefines() {
  22829. }
  22830. MaterialDefines.prototype.rebuild = function () {
  22831. if (this._keys) {
  22832. delete this._keys;
  22833. }
  22834. this._keys = Object.keys(this);
  22835. };
  22836. MaterialDefines.prototype.isEqual = function (other) {
  22837. if (this._keys.length !== other._keys.length) {
  22838. return false;
  22839. }
  22840. for (var index = 0; index < this._keys.length; index++) {
  22841. var prop = this._keys[index];
  22842. if (this[prop] !== other[prop]) {
  22843. return false;
  22844. }
  22845. }
  22846. return true;
  22847. };
  22848. MaterialDefines.prototype.cloneTo = function (other) {
  22849. if (this._keys.length !== other._keys.length) {
  22850. other._keys = this._keys.slice(0);
  22851. }
  22852. for (var index = 0; index < this._keys.length; index++) {
  22853. var prop = this._keys[index];
  22854. other[prop] = this[prop];
  22855. }
  22856. };
  22857. MaterialDefines.prototype.reset = function () {
  22858. for (var index = 0; index < this._keys.length; index++) {
  22859. var prop = this._keys[index];
  22860. if (typeof (this[prop]) === "number") {
  22861. this[prop] = 0;
  22862. }
  22863. else {
  22864. this[prop] = false;
  22865. }
  22866. }
  22867. };
  22868. MaterialDefines.prototype.toString = function () {
  22869. var result = "";
  22870. for (var index = 0; index < this._keys.length; index++) {
  22871. var prop = this._keys[index];
  22872. if (typeof (this[prop]) === "number") {
  22873. result += "#define " + prop + " " + this[prop] + "\n";
  22874. }
  22875. else if (this[prop]) {
  22876. result += "#define " + prop + "\n";
  22877. }
  22878. }
  22879. return result;
  22880. };
  22881. return MaterialDefines;
  22882. })();
  22883. BABYLON.MaterialDefines = MaterialDefines;
  22884. var Material = (function () {
  22885. function Material(name, scene, doNotAdd) {
  22886. this.name = name;
  22887. this.checkReadyOnEveryCall = false;
  22888. this.checkReadyOnlyOnce = false;
  22889. this.state = "";
  22890. this.alpha = 1.0;
  22891. this.backFaceCulling = true;
  22892. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22893. /**
  22894. * An event triggered when the material is disposed.
  22895. * @type {BABYLON.Observable}
  22896. */
  22897. this.onDisposeObservable = new BABYLON.Observable();
  22898. /**
  22899. * An event triggered when the material is compiled.
  22900. * @type {BABYLON.Observable}
  22901. */
  22902. this.onBindObservable = new BABYLON.Observable();
  22903. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22904. this.disableDepthWrite = false;
  22905. this.fogEnabled = true;
  22906. this.pointSize = 1.0;
  22907. this.zOffset = 0;
  22908. this._wasPreviouslyReady = false;
  22909. this._fillMode = Material.TriangleFillMode;
  22910. this.id = name;
  22911. this._scene = scene;
  22912. if (!doNotAdd) {
  22913. scene.materials.push(this);
  22914. }
  22915. }
  22916. Object.defineProperty(Material, "TriangleFillMode", {
  22917. get: function () {
  22918. return Material._TriangleFillMode;
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. Object.defineProperty(Material, "WireFrameFillMode", {
  22924. get: function () {
  22925. return Material._WireFrameFillMode;
  22926. },
  22927. enumerable: true,
  22928. configurable: true
  22929. });
  22930. Object.defineProperty(Material, "PointFillMode", {
  22931. get: function () {
  22932. return Material._PointFillMode;
  22933. },
  22934. enumerable: true,
  22935. configurable: true
  22936. });
  22937. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22938. get: function () {
  22939. return Material._ClockWiseSideOrientation;
  22940. },
  22941. enumerable: true,
  22942. configurable: true
  22943. });
  22944. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22945. get: function () {
  22946. return Material._CounterClockWiseSideOrientation;
  22947. },
  22948. enumerable: true,
  22949. configurable: true
  22950. });
  22951. Object.defineProperty(Material.prototype, "onDispose", {
  22952. set: function (callback) {
  22953. if (this._onDisposeObserver) {
  22954. this.onDisposeObservable.remove(this._onDisposeObserver);
  22955. }
  22956. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. Object.defineProperty(Material.prototype, "onBind", {
  22962. set: function (callback) {
  22963. if (this._onBindObserver) {
  22964. this.onBindObservable.remove(this._onBindObserver);
  22965. }
  22966. this._onBindObserver = this.onBindObservable.add(callback);
  22967. },
  22968. enumerable: true,
  22969. configurable: true
  22970. });
  22971. Object.defineProperty(Material.prototype, "wireframe", {
  22972. get: function () {
  22973. return this._fillMode === Material.WireFrameFillMode;
  22974. },
  22975. set: function (value) {
  22976. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22977. },
  22978. enumerable: true,
  22979. configurable: true
  22980. });
  22981. Object.defineProperty(Material.prototype, "pointsCloud", {
  22982. get: function () {
  22983. return this._fillMode === Material.PointFillMode;
  22984. },
  22985. set: function (value) {
  22986. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22987. },
  22988. enumerable: true,
  22989. configurable: true
  22990. });
  22991. Object.defineProperty(Material.prototype, "fillMode", {
  22992. get: function () {
  22993. return this._fillMode;
  22994. },
  22995. set: function (value) {
  22996. this._fillMode = value;
  22997. },
  22998. enumerable: true,
  22999. configurable: true
  23000. });
  23001. /**
  23002. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23003. * subclasses should override adding information pertainent to themselves
  23004. */
  23005. Material.prototype.toString = function (fullDetails) {
  23006. var ret = "Name: " + this.name;
  23007. if (fullDetails) {
  23008. }
  23009. return ret;
  23010. };
  23011. Object.defineProperty(Material.prototype, "isFrozen", {
  23012. get: function () {
  23013. return this.checkReadyOnlyOnce;
  23014. },
  23015. enumerable: true,
  23016. configurable: true
  23017. });
  23018. Material.prototype.freeze = function () {
  23019. this.checkReadyOnlyOnce = true;
  23020. };
  23021. Material.prototype.unfreeze = function () {
  23022. this.checkReadyOnlyOnce = false;
  23023. };
  23024. Material.prototype.isReady = function (mesh, useInstances) {
  23025. return true;
  23026. };
  23027. Material.prototype.getEffect = function () {
  23028. return this._effect;
  23029. };
  23030. Material.prototype.getScene = function () {
  23031. return this._scene;
  23032. };
  23033. Material.prototype.needAlphaBlending = function () {
  23034. return (this.alpha < 1.0);
  23035. };
  23036. Material.prototype.needAlphaTesting = function () {
  23037. return false;
  23038. };
  23039. Material.prototype.getAlphaTestTexture = function () {
  23040. return null;
  23041. };
  23042. Material.prototype.markDirty = function () {
  23043. this._wasPreviouslyReady = false;
  23044. };
  23045. Material.prototype._preBind = function () {
  23046. var engine = this._scene.getEngine();
  23047. engine.enableEffect(this._effect);
  23048. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  23049. };
  23050. Material.prototype.bind = function (world, mesh) {
  23051. this._scene._cachedMaterial = this;
  23052. this.onBindObservable.notifyObservers(mesh);
  23053. if (this.disableDepthWrite) {
  23054. var engine = this._scene.getEngine();
  23055. this._cachedDepthWriteState = engine.getDepthWrite();
  23056. engine.setDepthWrite(false);
  23057. }
  23058. };
  23059. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23060. };
  23061. Material.prototype.unbind = function () {
  23062. if (this.disableDepthWrite) {
  23063. var engine = this._scene.getEngine();
  23064. engine.setDepthWrite(this._cachedDepthWriteState);
  23065. }
  23066. };
  23067. Material.prototype.clone = function (name) {
  23068. return null;
  23069. };
  23070. Material.prototype.getBindedMeshes = function () {
  23071. var result = new Array();
  23072. for (var index = 0; index < this._scene.meshes.length; index++) {
  23073. var mesh = this._scene.meshes[index];
  23074. if (mesh.material === this) {
  23075. result.push(mesh);
  23076. }
  23077. }
  23078. return result;
  23079. };
  23080. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23081. // Animations
  23082. this.getScene().stopAnimation(this);
  23083. // Remove from scene
  23084. var index = this._scene.materials.indexOf(this);
  23085. if (index >= 0) {
  23086. this._scene.materials.splice(index, 1);
  23087. }
  23088. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23089. if (forceDisposeEffect && this._effect) {
  23090. this._scene.getEngine()._releaseEffect(this._effect);
  23091. this._effect = null;
  23092. }
  23093. // Remove from meshes
  23094. for (index = 0; index < this._scene.meshes.length; index++) {
  23095. var mesh = this._scene.meshes[index];
  23096. if (mesh.material === this) {
  23097. mesh.material = null;
  23098. }
  23099. }
  23100. // Callback
  23101. this.onDisposeObservable.notifyObservers(this);
  23102. this.onDisposeObservable.clear();
  23103. this.onBindObservable.clear();
  23104. };
  23105. Material.prototype.serialize = function () {
  23106. return BABYLON.SerializationHelper.Serialize(this);
  23107. };
  23108. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23109. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23110. multiMaterial.id = parsedMultiMaterial.id;
  23111. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23112. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23113. var subMatId = parsedMultiMaterial.materials[matIndex];
  23114. if (subMatId) {
  23115. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23116. }
  23117. else {
  23118. multiMaterial.subMaterials.push(null);
  23119. }
  23120. }
  23121. return multiMaterial;
  23122. };
  23123. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23124. if (!parsedMaterial.customType) {
  23125. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23126. }
  23127. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23128. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23129. ;
  23130. };
  23131. Material._TriangleFillMode = 0;
  23132. Material._WireFrameFillMode = 1;
  23133. Material._PointFillMode = 2;
  23134. Material._ClockWiseSideOrientation = 0;
  23135. Material._CounterClockWiseSideOrientation = 1;
  23136. __decorate([
  23137. BABYLON.serialize()
  23138. ], Material.prototype, "id", void 0);
  23139. __decorate([
  23140. BABYLON.serialize()
  23141. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23142. __decorate([
  23143. BABYLON.serialize()
  23144. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23145. __decorate([
  23146. BABYLON.serialize()
  23147. ], Material.prototype, "state", void 0);
  23148. __decorate([
  23149. BABYLON.serialize()
  23150. ], Material.prototype, "alpha", void 0);
  23151. __decorate([
  23152. BABYLON.serialize()
  23153. ], Material.prototype, "backFaceCulling", void 0);
  23154. __decorate([
  23155. BABYLON.serialize()
  23156. ], Material.prototype, "sideOrientation", void 0);
  23157. __decorate([
  23158. BABYLON.serialize()
  23159. ], Material.prototype, "alphaMode", void 0);
  23160. __decorate([
  23161. BABYLON.serialize()
  23162. ], Material.prototype, "disableDepthWrite", void 0);
  23163. __decorate([
  23164. BABYLON.serialize()
  23165. ], Material.prototype, "fogEnabled", void 0);
  23166. __decorate([
  23167. BABYLON.serialize()
  23168. ], Material.prototype, "pointSize", void 0);
  23169. __decorate([
  23170. BABYLON.serialize()
  23171. ], Material.prototype, "zOffset", void 0);
  23172. __decorate([
  23173. BABYLON.serialize()
  23174. ], Material.prototype, "wireframe", null);
  23175. __decorate([
  23176. BABYLON.serialize()
  23177. ], Material.prototype, "pointsCloud", null);
  23178. __decorate([
  23179. BABYLON.serialize()
  23180. ], Material.prototype, "fillMode", null);
  23181. return Material;
  23182. })();
  23183. BABYLON.Material = Material;
  23184. })(BABYLON || (BABYLON = {}));
  23185. var BABYLON;
  23186. (function (BABYLON) {
  23187. var StandardMaterialDefines = (function (_super) {
  23188. __extends(StandardMaterialDefines, _super);
  23189. function StandardMaterialDefines() {
  23190. _super.call(this);
  23191. this.DIFFUSE = false;
  23192. this.AMBIENT = false;
  23193. this.OPACITY = false;
  23194. this.OPACITYRGB = false;
  23195. this.REFLECTION = false;
  23196. this.EMISSIVE = false;
  23197. this.SPECULAR = false;
  23198. this.BUMP = false;
  23199. this.PARALLAX = false;
  23200. this.PARALLAXOCCLUSION = false;
  23201. this.SPECULAROVERALPHA = false;
  23202. this.CLIPPLANE = false;
  23203. this.ALPHATEST = false;
  23204. this.ALPHAFROMDIFFUSE = false;
  23205. this.POINTSIZE = false;
  23206. this.FOG = false;
  23207. this.SPECULARTERM = false;
  23208. this.DIFFUSEFRESNEL = false;
  23209. this.OPACITYFRESNEL = false;
  23210. this.REFLECTIONFRESNEL = false;
  23211. this.REFRACTIONFRESNEL = false;
  23212. this.EMISSIVEFRESNEL = false;
  23213. this.FRESNEL = false;
  23214. this.NORMAL = false;
  23215. this.UV1 = false;
  23216. this.UV2 = false;
  23217. this.VERTEXCOLOR = false;
  23218. this.VERTEXALPHA = false;
  23219. this.NUM_BONE_INFLUENCERS = 0;
  23220. this.BonesPerMesh = 0;
  23221. this.INSTANCES = false;
  23222. this.GLOSSINESS = false;
  23223. this.ROUGHNESS = false;
  23224. this.EMISSIVEASILLUMINATION = false;
  23225. this.LINKEMISSIVEWITHDIFFUSE = false;
  23226. this.REFLECTIONFRESNELFROMSPECULAR = false;
  23227. this.LIGHTMAP = false;
  23228. this.USELIGHTMAPASSHADOWMAP = false;
  23229. this.REFLECTIONMAP_3D = false;
  23230. this.REFLECTIONMAP_SPHERICAL = false;
  23231. this.REFLECTIONMAP_PLANAR = false;
  23232. this.REFLECTIONMAP_CUBIC = false;
  23233. this.REFLECTIONMAP_PROJECTION = false;
  23234. this.REFLECTIONMAP_SKYBOX = false;
  23235. this.REFLECTIONMAP_EXPLICIT = false;
  23236. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  23237. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  23238. this.INVERTCUBICMAP = false;
  23239. this.LOGARITHMICDEPTH = false;
  23240. this.REFRACTION = false;
  23241. this.REFRACTIONMAP_3D = false;
  23242. this.REFLECTIONOVERALPHA = false;
  23243. this.INVERTNORMALMAPX = false;
  23244. this.INVERTNORMALMAPY = false;
  23245. this.rebuild();
  23246. }
  23247. return StandardMaterialDefines;
  23248. })(BABYLON.MaterialDefines);
  23249. var StandardMaterial = (function (_super) {
  23250. __extends(StandardMaterial, _super);
  23251. function StandardMaterial(name, scene) {
  23252. var _this = this;
  23253. _super.call(this, name, scene);
  23254. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23255. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  23256. this.specularColor = new BABYLON.Color3(1, 1, 1);
  23257. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  23258. this.specularPower = 64;
  23259. this.useAlphaFromDiffuseTexture = false;
  23260. this.useEmissiveAsIllumination = false;
  23261. this.linkEmissiveWithDiffuse = false;
  23262. this.useReflectionFresnelFromSpecular = false;
  23263. this.useSpecularOverAlpha = false;
  23264. this.useReflectionOverAlpha = false;
  23265. this.disableLighting = false;
  23266. this.useParallax = false;
  23267. this.useParallaxOcclusion = false;
  23268. this.parallaxScaleBias = 0.05;
  23269. this.roughness = 0;
  23270. this.indexOfRefraction = 0.98;
  23271. this.invertRefractionY = true;
  23272. this.useLightmapAsShadowmap = false;
  23273. this.useGlossinessFromSpecularMapAlpha = false;
  23274. this.maxSimultaneousLights = 4;
  23275. /**
  23276. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  23277. */
  23278. this.invertNormalMapX = false;
  23279. /**
  23280. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  23281. */
  23282. this.invertNormalMapY = false;
  23283. this._renderTargets = new BABYLON.SmartArray(16);
  23284. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  23285. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  23286. this._defines = new StandardMaterialDefines();
  23287. this._cachedDefines = new StandardMaterialDefines();
  23288. this._cachedDefines.BonesPerMesh = -1;
  23289. this.getRenderTargetTextures = function () {
  23290. _this._renderTargets.reset();
  23291. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  23292. _this._renderTargets.push(_this.reflectionTexture);
  23293. }
  23294. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  23295. _this._renderTargets.push(_this.refractionTexture);
  23296. }
  23297. return _this._renderTargets;
  23298. };
  23299. }
  23300. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  23301. get: function () {
  23302. return this._useLogarithmicDepth;
  23303. },
  23304. set: function (value) {
  23305. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  23306. },
  23307. enumerable: true,
  23308. configurable: true
  23309. });
  23310. StandardMaterial.prototype.needAlphaBlending = function () {
  23311. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  23312. };
  23313. StandardMaterial.prototype.needAlphaTesting = function () {
  23314. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  23315. };
  23316. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  23317. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  23318. };
  23319. StandardMaterial.prototype.getAlphaTestTexture = function () {
  23320. return this.diffuseTexture;
  23321. };
  23322. // Methods
  23323. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  23324. if (!mesh) {
  23325. return true;
  23326. }
  23327. if (this._defines.INSTANCES !== useInstances) {
  23328. return false;
  23329. }
  23330. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  23331. return true;
  23332. }
  23333. return false;
  23334. };
  23335. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  23336. if (this.isFrozen) {
  23337. if (this._wasPreviouslyReady) {
  23338. return true;
  23339. }
  23340. }
  23341. var scene = this.getScene();
  23342. if (!this.checkReadyOnEveryCall) {
  23343. if (this._renderId === scene.getRenderId()) {
  23344. if (this._checkCache(scene, mesh, useInstances)) {
  23345. return true;
  23346. }
  23347. }
  23348. }
  23349. var engine = scene.getEngine();
  23350. var needNormals = false;
  23351. var needUVs = false;
  23352. this._defines.reset();
  23353. // Textures
  23354. if (scene.texturesEnabled) {
  23355. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23356. if (!this.diffuseTexture.isReady()) {
  23357. return false;
  23358. }
  23359. else {
  23360. needUVs = true;
  23361. this._defines.DIFFUSE = true;
  23362. }
  23363. }
  23364. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23365. if (!this.ambientTexture.isReady()) {
  23366. return false;
  23367. }
  23368. else {
  23369. needUVs = true;
  23370. this._defines.AMBIENT = true;
  23371. }
  23372. }
  23373. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23374. if (!this.opacityTexture.isReady()) {
  23375. return false;
  23376. }
  23377. else {
  23378. needUVs = true;
  23379. this._defines.OPACITY = true;
  23380. if (this.opacityTexture.getAlphaFromRGB) {
  23381. this._defines.OPACITYRGB = true;
  23382. }
  23383. }
  23384. }
  23385. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23386. if (!this.reflectionTexture.isReady()) {
  23387. return false;
  23388. }
  23389. else {
  23390. needNormals = true;
  23391. this._defines.REFLECTION = true;
  23392. if (this.roughness > 0) {
  23393. this._defines.ROUGHNESS = true;
  23394. }
  23395. if (this.useReflectionOverAlpha) {
  23396. this._defines.REFLECTIONOVERALPHA = true;
  23397. }
  23398. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  23399. this._defines.INVERTCUBICMAP = true;
  23400. }
  23401. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  23402. switch (this.reflectionTexture.coordinatesMode) {
  23403. case BABYLON.Texture.CUBIC_MODE:
  23404. case BABYLON.Texture.INVCUBIC_MODE:
  23405. this._defines.REFLECTIONMAP_CUBIC = true;
  23406. break;
  23407. case BABYLON.Texture.EXPLICIT_MODE:
  23408. this._defines.REFLECTIONMAP_EXPLICIT = true;
  23409. break;
  23410. case BABYLON.Texture.PLANAR_MODE:
  23411. this._defines.REFLECTIONMAP_PLANAR = true;
  23412. break;
  23413. case BABYLON.Texture.PROJECTION_MODE:
  23414. this._defines.REFLECTIONMAP_PROJECTION = true;
  23415. break;
  23416. case BABYLON.Texture.SKYBOX_MODE:
  23417. this._defines.REFLECTIONMAP_SKYBOX = true;
  23418. break;
  23419. case BABYLON.Texture.SPHERICAL_MODE:
  23420. this._defines.REFLECTIONMAP_SPHERICAL = true;
  23421. break;
  23422. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  23423. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  23424. break;
  23425. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  23426. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  23427. break;
  23428. }
  23429. }
  23430. }
  23431. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23432. if (!this.emissiveTexture.isReady()) {
  23433. return false;
  23434. }
  23435. else {
  23436. needUVs = true;
  23437. this._defines.EMISSIVE = true;
  23438. }
  23439. }
  23440. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23441. if (!this.lightmapTexture.isReady()) {
  23442. return false;
  23443. }
  23444. else {
  23445. needUVs = true;
  23446. this._defines.LIGHTMAP = true;
  23447. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23448. }
  23449. }
  23450. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23451. if (!this.specularTexture.isReady()) {
  23452. return false;
  23453. }
  23454. else {
  23455. needUVs = true;
  23456. this._defines.SPECULAR = true;
  23457. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23458. }
  23459. }
  23460. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23461. if (!this.bumpTexture.isReady()) {
  23462. return false;
  23463. }
  23464. else {
  23465. needUVs = true;
  23466. this._defines.BUMP = true;
  23467. if (this.useParallax) {
  23468. this._defines.PARALLAX = true;
  23469. if (this.useParallaxOcclusion) {
  23470. this._defines.PARALLAXOCCLUSION = true;
  23471. }
  23472. }
  23473. if (this.invertNormalMapX) {
  23474. this._defines.INVERTNORMALMAPX = true;
  23475. }
  23476. if (this.invertNormalMapY) {
  23477. this._defines.INVERTNORMALMAPY = true;
  23478. }
  23479. }
  23480. }
  23481. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23482. if (!this.refractionTexture.isReady()) {
  23483. return false;
  23484. }
  23485. else {
  23486. needUVs = true;
  23487. this._defines.REFRACTION = true;
  23488. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23489. }
  23490. }
  23491. }
  23492. // Effect
  23493. if (scene.clipPlane) {
  23494. this._defines.CLIPPLANE = true;
  23495. }
  23496. if (engine.getAlphaTesting()) {
  23497. this._defines.ALPHATEST = true;
  23498. }
  23499. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23500. this._defines.ALPHAFROMDIFFUSE = true;
  23501. }
  23502. if (this.useEmissiveAsIllumination) {
  23503. this._defines.EMISSIVEASILLUMINATION = true;
  23504. }
  23505. if (this.linkEmissiveWithDiffuse) {
  23506. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23507. }
  23508. if (this.useLogarithmicDepth) {
  23509. this._defines.LOGARITHMICDEPTH = true;
  23510. }
  23511. // Point size
  23512. if (this.pointsCloud || scene.forcePointsCloud) {
  23513. this._defines.POINTSIZE = true;
  23514. }
  23515. // Fog
  23516. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23517. this._defines.FOG = true;
  23518. }
  23519. if (scene.lightsEnabled && !this.disableLighting) {
  23520. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23521. }
  23522. if (StandardMaterial.FresnelEnabled) {
  23523. // Fresnel
  23524. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23525. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23526. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23527. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23528. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23529. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23530. this._defines.DIFFUSEFRESNEL = true;
  23531. }
  23532. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23533. this._defines.OPACITYFRESNEL = true;
  23534. }
  23535. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23536. this._defines.REFLECTIONFRESNEL = true;
  23537. if (this.useReflectionFresnelFromSpecular) {
  23538. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23539. }
  23540. }
  23541. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23542. this._defines.REFRACTIONFRESNEL = true;
  23543. }
  23544. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23545. this._defines.EMISSIVEFRESNEL = true;
  23546. }
  23547. needNormals = true;
  23548. this._defines.FRESNEL = true;
  23549. }
  23550. }
  23551. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23552. this._defines.SPECULAROVERALPHA = true;
  23553. }
  23554. // Attribs
  23555. if (mesh) {
  23556. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23557. this._defines.NORMAL = true;
  23558. }
  23559. if (needUVs) {
  23560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23561. this._defines.UV1 = true;
  23562. }
  23563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23564. this._defines.UV2 = true;
  23565. }
  23566. }
  23567. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23568. this._defines.VERTEXCOLOR = true;
  23569. if (mesh.hasVertexAlpha) {
  23570. this._defines.VERTEXALPHA = true;
  23571. }
  23572. }
  23573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23574. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23575. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23576. }
  23577. // Instances
  23578. if (useInstances) {
  23579. this._defines.INSTANCES = true;
  23580. }
  23581. }
  23582. // Get correct effect
  23583. if (!this._defines.isEqual(this._cachedDefines)) {
  23584. this._defines.cloneTo(this._cachedDefines);
  23585. scene.resetCachedMaterial();
  23586. // Fallbacks
  23587. var fallbacks = new BABYLON.EffectFallbacks();
  23588. if (this._defines.REFLECTION) {
  23589. fallbacks.addFallback(0, "REFLECTION");
  23590. }
  23591. if (this._defines.SPECULAR) {
  23592. fallbacks.addFallback(0, "SPECULAR");
  23593. }
  23594. if (this._defines.BUMP) {
  23595. fallbacks.addFallback(0, "BUMP");
  23596. }
  23597. if (this._defines.PARALLAX) {
  23598. fallbacks.addFallback(1, "PARALLAX");
  23599. }
  23600. if (this._defines.PARALLAXOCCLUSION) {
  23601. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23602. }
  23603. if (this._defines.SPECULAROVERALPHA) {
  23604. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23605. }
  23606. if (this._defines.FOG) {
  23607. fallbacks.addFallback(1, "FOG");
  23608. }
  23609. if (this._defines.POINTSIZE) {
  23610. fallbacks.addFallback(0, "POINTSIZE");
  23611. }
  23612. if (this._defines.LOGARITHMICDEPTH) {
  23613. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23614. }
  23615. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23616. if (this._defines.SPECULARTERM) {
  23617. fallbacks.addFallback(0, "SPECULARTERM");
  23618. }
  23619. if (this._defines.DIFFUSEFRESNEL) {
  23620. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23621. }
  23622. if (this._defines.OPACITYFRESNEL) {
  23623. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23624. }
  23625. if (this._defines.REFLECTIONFRESNEL) {
  23626. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23627. }
  23628. if (this._defines.EMISSIVEFRESNEL) {
  23629. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23630. }
  23631. if (this._defines.FRESNEL) {
  23632. fallbacks.addFallback(4, "FRESNEL");
  23633. }
  23634. //Attributes
  23635. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23636. if (this._defines.NORMAL) {
  23637. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23638. }
  23639. if (this._defines.UV1) {
  23640. attribs.push(BABYLON.VertexBuffer.UVKind);
  23641. }
  23642. if (this._defines.UV2) {
  23643. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23644. }
  23645. if (this._defines.VERTEXCOLOR) {
  23646. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23647. }
  23648. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23649. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23650. // Legacy browser patch
  23651. var shaderName = "default";
  23652. if (!scene.getEngine().getCaps().standardDerivatives) {
  23653. shaderName = "legacydefault";
  23654. }
  23655. var join = this._defines.toString();
  23656. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23657. "vFogInfos", "vFogColor", "pointSize",
  23658. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23659. "mBones",
  23660. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23661. "depthValues",
  23662. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23663. "logarithmicDepthConstant"
  23664. ];
  23665. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  23666. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  23667. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23668. }
  23669. if (!this._effect.isReady()) {
  23670. return false;
  23671. }
  23672. this._renderId = scene.getRenderId();
  23673. this._wasPreviouslyReady = true;
  23674. if (mesh) {
  23675. if (!mesh._materialDefines) {
  23676. mesh._materialDefines = new StandardMaterialDefines();
  23677. }
  23678. this._defines.cloneTo(mesh._materialDefines);
  23679. }
  23680. return true;
  23681. };
  23682. StandardMaterial.prototype.unbind = function () {
  23683. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23684. this._effect.setTexture("reflection2DSampler", null);
  23685. }
  23686. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23687. this._effect.setTexture("refraction2DSampler", null);
  23688. }
  23689. _super.prototype.unbind.call(this);
  23690. };
  23691. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23692. this._effect.setMatrix("world", world);
  23693. };
  23694. StandardMaterial.prototype.bind = function (world, mesh) {
  23695. var scene = this.getScene();
  23696. // Matrices
  23697. this.bindOnlyWorldMatrix(world);
  23698. // Bones
  23699. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23700. if (scene.getCachedMaterial() !== this) {
  23701. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23702. if (StandardMaterial.FresnelEnabled) {
  23703. // Fresnel
  23704. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23705. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23706. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23707. }
  23708. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23709. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23710. }
  23711. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23712. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23713. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23714. }
  23715. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23716. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23717. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23718. }
  23719. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23720. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23721. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23722. }
  23723. }
  23724. // Textures
  23725. if (scene.texturesEnabled) {
  23726. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23727. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23728. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23729. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23730. }
  23731. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23732. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23733. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23734. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23735. }
  23736. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23737. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23738. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23739. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23740. }
  23741. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23742. if (this.reflectionTexture.isCube) {
  23743. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23744. }
  23745. else {
  23746. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23747. }
  23748. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23749. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23750. }
  23751. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23752. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23753. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23754. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23755. }
  23756. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23757. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23758. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23759. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23760. }
  23761. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23762. this._effect.setTexture("specularSampler", this.specularTexture);
  23763. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23764. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23765. }
  23766. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23767. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23768. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23769. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23770. }
  23771. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23772. var depth = 1.0;
  23773. if (this.refractionTexture.isCube) {
  23774. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23775. }
  23776. else {
  23777. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23778. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23779. if (this.refractionTexture.depth) {
  23780. depth = this.refractionTexture.depth;
  23781. }
  23782. }
  23783. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23784. }
  23785. }
  23786. // Clip plane
  23787. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23788. // Point size
  23789. if (this.pointsCloud) {
  23790. this._effect.setFloat("pointSize", this.pointSize);
  23791. }
  23792. // Colors
  23793. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23794. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23795. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23796. if (this._defines.SPECULARTERM) {
  23797. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23798. }
  23799. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23800. }
  23801. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23802. // Diffuse
  23803. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23804. // Lights
  23805. if (scene.lightsEnabled && !this.disableLighting) {
  23806. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  23807. }
  23808. // View
  23809. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23810. this._effect.setMatrix("view", scene.getViewMatrix());
  23811. }
  23812. // Fog
  23813. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23814. // Log. depth
  23815. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23816. }
  23817. _super.prototype.bind.call(this, world, mesh);
  23818. };
  23819. StandardMaterial.prototype.getAnimatables = function () {
  23820. var results = [];
  23821. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23822. results.push(this.diffuseTexture);
  23823. }
  23824. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23825. results.push(this.ambientTexture);
  23826. }
  23827. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23828. results.push(this.opacityTexture);
  23829. }
  23830. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23831. results.push(this.reflectionTexture);
  23832. }
  23833. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23834. results.push(this.emissiveTexture);
  23835. }
  23836. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23837. results.push(this.specularTexture);
  23838. }
  23839. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23840. results.push(this.bumpTexture);
  23841. }
  23842. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23843. results.push(this.lightmapTexture);
  23844. }
  23845. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23846. results.push(this.refractionTexture);
  23847. }
  23848. return results;
  23849. };
  23850. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23851. if (forceDisposeTextures) {
  23852. if (this.diffuseTexture) {
  23853. this.diffuseTexture.dispose();
  23854. }
  23855. if (this.ambientTexture) {
  23856. this.ambientTexture.dispose();
  23857. }
  23858. if (this.opacityTexture) {
  23859. this.opacityTexture.dispose();
  23860. }
  23861. if (this.reflectionTexture) {
  23862. this.reflectionTexture.dispose();
  23863. }
  23864. if (this.emissiveTexture) {
  23865. this.emissiveTexture.dispose();
  23866. }
  23867. if (this.specularTexture) {
  23868. this.specularTexture.dispose();
  23869. }
  23870. if (this.bumpTexture) {
  23871. this.bumpTexture.dispose();
  23872. }
  23873. if (this.lightmapTexture) {
  23874. this.lightmapTexture.dispose();
  23875. }
  23876. if (this.refractionTexture) {
  23877. this.refractionTexture.dispose();
  23878. }
  23879. }
  23880. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23881. };
  23882. StandardMaterial.prototype.clone = function (name) {
  23883. var _this = this;
  23884. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23885. };
  23886. StandardMaterial.prototype.serialize = function () {
  23887. return BABYLON.SerializationHelper.Serialize(this);
  23888. };
  23889. // Statics
  23890. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23891. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23892. };
  23893. // Flags used to enable or disable a type of texture for all Standard Materials
  23894. StandardMaterial.DiffuseTextureEnabled = true;
  23895. StandardMaterial.AmbientTextureEnabled = true;
  23896. StandardMaterial.OpacityTextureEnabled = true;
  23897. StandardMaterial.ReflectionTextureEnabled = true;
  23898. StandardMaterial.EmissiveTextureEnabled = true;
  23899. StandardMaterial.SpecularTextureEnabled = true;
  23900. StandardMaterial.BumpTextureEnabled = true;
  23901. StandardMaterial.FresnelEnabled = true;
  23902. StandardMaterial.LightmapTextureEnabled = true;
  23903. StandardMaterial.RefractionTextureEnabled = true;
  23904. __decorate([
  23905. BABYLON.serializeAsTexture()
  23906. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23907. __decorate([
  23908. BABYLON.serializeAsTexture()
  23909. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23910. __decorate([
  23911. BABYLON.serializeAsTexture()
  23912. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23913. __decorate([
  23914. BABYLON.serializeAsTexture()
  23915. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23916. __decorate([
  23917. BABYLON.serializeAsTexture()
  23918. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23919. __decorate([
  23920. BABYLON.serializeAsTexture()
  23921. ], StandardMaterial.prototype, "specularTexture", void 0);
  23922. __decorate([
  23923. BABYLON.serializeAsTexture()
  23924. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23925. __decorate([
  23926. BABYLON.serializeAsTexture()
  23927. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23928. __decorate([
  23929. BABYLON.serializeAsTexture()
  23930. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23931. __decorate([
  23932. BABYLON.serializeAsColor3("ambient")
  23933. ], StandardMaterial.prototype, "ambientColor", void 0);
  23934. __decorate([
  23935. BABYLON.serializeAsColor3("diffuse")
  23936. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23937. __decorate([
  23938. BABYLON.serializeAsColor3("specular")
  23939. ], StandardMaterial.prototype, "specularColor", void 0);
  23940. __decorate([
  23941. BABYLON.serializeAsColor3("emissive")
  23942. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23943. __decorate([
  23944. BABYLON.serialize()
  23945. ], StandardMaterial.prototype, "specularPower", void 0);
  23946. __decorate([
  23947. BABYLON.serialize()
  23948. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23949. __decorate([
  23950. BABYLON.serialize()
  23951. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23952. __decorate([
  23953. BABYLON.serialize()
  23954. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23955. __decorate([
  23956. BABYLON.serialize()
  23957. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23958. __decorate([
  23959. BABYLON.serialize()
  23960. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23961. __decorate([
  23962. BABYLON.serialize()
  23963. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23964. __decorate([
  23965. BABYLON.serialize()
  23966. ], StandardMaterial.prototype, "disableLighting", void 0);
  23967. __decorate([
  23968. BABYLON.serialize()
  23969. ], StandardMaterial.prototype, "useParallax", void 0);
  23970. __decorate([
  23971. BABYLON.serialize()
  23972. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23973. __decorate([
  23974. BABYLON.serialize()
  23975. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23976. __decorate([
  23977. BABYLON.serialize()
  23978. ], StandardMaterial.prototype, "roughness", void 0);
  23979. __decorate([
  23980. BABYLON.serialize()
  23981. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23982. __decorate([
  23983. BABYLON.serialize()
  23984. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23985. __decorate([
  23986. BABYLON.serialize()
  23987. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23988. __decorate([
  23989. BABYLON.serializeAsFresnelParameters()
  23990. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23991. __decorate([
  23992. BABYLON.serializeAsFresnelParameters()
  23993. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23994. __decorate([
  23995. BABYLON.serializeAsFresnelParameters()
  23996. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23997. __decorate([
  23998. BABYLON.serializeAsFresnelParameters()
  23999. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  24000. __decorate([
  24001. BABYLON.serializeAsFresnelParameters()
  24002. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  24003. __decorate([
  24004. BABYLON.serialize()
  24005. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  24006. __decorate([
  24007. BABYLON.serialize()
  24008. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  24009. __decorate([
  24010. BABYLON.serialize()
  24011. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  24012. __decorate([
  24013. BABYLON.serialize()
  24014. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  24015. __decorate([
  24016. BABYLON.serialize()
  24017. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  24018. return StandardMaterial;
  24019. })(BABYLON.Material);
  24020. BABYLON.StandardMaterial = StandardMaterial;
  24021. })(BABYLON || (BABYLON = {}));
  24022. var BABYLON;
  24023. (function (BABYLON) {
  24024. var MultiMaterial = (function (_super) {
  24025. __extends(MultiMaterial, _super);
  24026. function MultiMaterial(name, scene) {
  24027. _super.call(this, name, scene, true);
  24028. this.subMaterials = new Array();
  24029. scene.multiMaterials.push(this);
  24030. }
  24031. // Properties
  24032. MultiMaterial.prototype.getSubMaterial = function (index) {
  24033. if (index < 0 || index >= this.subMaterials.length) {
  24034. return this.getScene().defaultMaterial;
  24035. }
  24036. return this.subMaterials[index];
  24037. };
  24038. // Methods
  24039. MultiMaterial.prototype.isReady = function (mesh) {
  24040. for (var index = 0; index < this.subMaterials.length; index++) {
  24041. var subMaterial = this.subMaterials[index];
  24042. if (subMaterial) {
  24043. if (!this.subMaterials[index].isReady(mesh)) {
  24044. return false;
  24045. }
  24046. }
  24047. }
  24048. return true;
  24049. };
  24050. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  24051. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  24052. for (var index = 0; index < this.subMaterials.length; index++) {
  24053. var subMaterial = null;
  24054. if (cloneChildren) {
  24055. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  24056. }
  24057. else {
  24058. subMaterial = this.subMaterials[index];
  24059. }
  24060. newMultiMaterial.subMaterials.push(subMaterial);
  24061. }
  24062. return newMultiMaterial;
  24063. };
  24064. MultiMaterial.prototype.serialize = function () {
  24065. var serializationObject = {};
  24066. serializationObject.name = this.name;
  24067. serializationObject.id = this.id;
  24068. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24069. serializationObject.materials = [];
  24070. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  24071. var subMat = this.subMaterials[matIndex];
  24072. if (subMat) {
  24073. serializationObject.materials.push(subMat.id);
  24074. }
  24075. else {
  24076. serializationObject.materials.push(null);
  24077. }
  24078. }
  24079. return serializationObject;
  24080. };
  24081. return MultiMaterial;
  24082. })(BABYLON.Material);
  24083. BABYLON.MultiMaterial = MultiMaterial;
  24084. })(BABYLON || (BABYLON = {}));
  24085. var BABYLON;
  24086. (function (BABYLON) {
  24087. var SceneLoader = (function () {
  24088. function SceneLoader() {
  24089. }
  24090. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  24091. get: function () {
  24092. return 0;
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  24098. get: function () {
  24099. return 1;
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  24105. get: function () {
  24106. return 2;
  24107. },
  24108. enumerable: true,
  24109. configurable: true
  24110. });
  24111. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  24112. get: function () {
  24113. return 3;
  24114. },
  24115. enumerable: true,
  24116. configurable: true
  24117. });
  24118. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  24119. get: function () {
  24120. return SceneLoader._ForceFullSceneLoadingForIncremental;
  24121. },
  24122. set: function (value) {
  24123. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  24129. get: function () {
  24130. return SceneLoader._ShowLoadingScreen;
  24131. },
  24132. set: function (value) {
  24133. SceneLoader._ShowLoadingScreen = value;
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Object.defineProperty(SceneLoader, "loggingLevel", {
  24139. get: function () {
  24140. return SceneLoader._loggingLevel;
  24141. },
  24142. set: function (value) {
  24143. SceneLoader._loggingLevel = value;
  24144. },
  24145. enumerable: true,
  24146. configurable: true
  24147. });
  24148. SceneLoader._getPluginForFilename = function (sceneFilename) {
  24149. var dotPosition = sceneFilename.lastIndexOf(".");
  24150. var queryStringPosition = sceneFilename.indexOf("?");
  24151. if (queryStringPosition === -1) {
  24152. queryStringPosition = sceneFilename.length;
  24153. }
  24154. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  24155. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24156. var plugin = this._registeredPlugins[index];
  24157. if (plugin.extensions.indexOf(extension) !== -1) {
  24158. return plugin;
  24159. }
  24160. }
  24161. return this._registeredPlugins[0];
  24162. };
  24163. // Public functions
  24164. SceneLoader.GetPluginForExtension = function (extension) {
  24165. for (var index = 0; index < this._registeredPlugins.length; index++) {
  24166. var plugin = this._registeredPlugins[index];
  24167. if (plugin.extensions.indexOf(extension) !== -1) {
  24168. return plugin;
  24169. }
  24170. }
  24171. return null;
  24172. };
  24173. SceneLoader.RegisterPlugin = function (plugin) {
  24174. plugin.extensions = plugin.extensions.toLowerCase();
  24175. SceneLoader._registeredPlugins.push(plugin);
  24176. };
  24177. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24178. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24179. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24180. return;
  24181. }
  24182. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24183. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24184. return;
  24185. }
  24186. var loadingToken = {};
  24187. scene._addPendingData(loadingToken);
  24188. var manifestChecked = function (success) {
  24189. scene.database = database;
  24190. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  24191. var importMeshFromData = function (data) {
  24192. var meshes = [];
  24193. var particleSystems = [];
  24194. var skeletons = [];
  24195. try {
  24196. if (plugin.importMesh) {
  24197. var syncedPlugin = plugin;
  24198. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  24199. if (onerror) {
  24200. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24201. }
  24202. scene._removePendingData(loadingToken);
  24203. return;
  24204. }
  24205. if (onsuccess) {
  24206. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24207. onsuccess(meshes, particleSystems, skeletons);
  24208. scene._removePendingData(loadingToken);
  24209. }
  24210. }
  24211. else {
  24212. var asyncedPlugin = plugin;
  24213. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  24214. if (onsuccess) {
  24215. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  24216. onsuccess(meshes, particleSystems, skeletons);
  24217. scene._removePendingData(loadingToken);
  24218. }
  24219. }, function () {
  24220. if (onerror) {
  24221. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  24222. }
  24223. scene._removePendingData(loadingToken);
  24224. });
  24225. }
  24226. }
  24227. catch (e) {
  24228. if (onerror) {
  24229. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  24230. }
  24231. scene._removePendingData(loadingToken);
  24232. }
  24233. };
  24234. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24235. // Direct load
  24236. importMeshFromData(sceneFilename.substr(5));
  24237. return;
  24238. }
  24239. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  24240. importMeshFromData(data);
  24241. }, progressCallBack, database);
  24242. };
  24243. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  24244. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24245. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24246. }
  24247. else {
  24248. // If the scene is a data stream or offline support is not enabled, it's a direct load
  24249. manifestChecked(true);
  24250. }
  24251. };
  24252. /**
  24253. * Load a scene
  24254. * @param rootUrl a string that defines the root url for scene and resources
  24255. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24256. * @param engine is the instance of BABYLON.Engine to use to create the scene
  24257. */
  24258. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  24259. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  24260. };
  24261. /**
  24262. * Append a scene
  24263. * @param rootUrl a string that defines the root url for scene and resources
  24264. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  24265. * @param scene is the instance of BABYLON.Scene to append to
  24266. */
  24267. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  24268. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  24269. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  24270. return;
  24271. }
  24272. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  24273. var database;
  24274. var loadingToken = {};
  24275. scene._addPendingData(loadingToken);
  24276. if (SceneLoader.ShowLoadingScreen) {
  24277. scene.getEngine().displayLoadingUI();
  24278. }
  24279. var loadSceneFromData = function (data) {
  24280. scene.database = database;
  24281. if (plugin.load) {
  24282. var syncedPlugin = plugin;
  24283. if (!syncedPlugin.load(scene, data, rootUrl)) {
  24284. if (onerror) {
  24285. onerror(scene);
  24286. }
  24287. scene._removePendingData(loadingToken);
  24288. scene.getEngine().hideLoadingUI();
  24289. return;
  24290. }
  24291. if (onsuccess) {
  24292. onsuccess(scene);
  24293. }
  24294. scene._removePendingData(loadingToken);
  24295. }
  24296. else {
  24297. var asyncedPlugin = plugin;
  24298. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  24299. if (onsuccess) {
  24300. onsuccess(scene);
  24301. }
  24302. }, function () {
  24303. if (onerror) {
  24304. onerror(scene);
  24305. }
  24306. scene._removePendingData(loadingToken);
  24307. scene.getEngine().hideLoadingUI();
  24308. });
  24309. }
  24310. if (SceneLoader.ShowLoadingScreen) {
  24311. scene.executeWhenReady(function () {
  24312. scene.getEngine().hideLoadingUI();
  24313. });
  24314. }
  24315. };
  24316. var manifestChecked = function (success) {
  24317. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  24318. };
  24319. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  24320. // Direct load
  24321. loadSceneFromData(sceneFilename.substr(5));
  24322. return;
  24323. }
  24324. if (rootUrl.indexOf("file:") === -1) {
  24325. if (scene.getEngine().enableOfflineSupport) {
  24326. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  24327. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  24328. }
  24329. else {
  24330. manifestChecked(true);
  24331. }
  24332. }
  24333. else {
  24334. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  24335. }
  24336. };
  24337. // Flags
  24338. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  24339. SceneLoader._ShowLoadingScreen = true;
  24340. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  24341. // Members
  24342. SceneLoader._registeredPlugins = new Array();
  24343. return SceneLoader;
  24344. })();
  24345. BABYLON.SceneLoader = SceneLoader;
  24346. ;
  24347. })(BABYLON || (BABYLON = {}));
  24348. var BABYLON;
  24349. (function (BABYLON) {
  24350. var Internals;
  24351. (function (Internals) {
  24352. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  24353. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24354. var parsedMaterial = parsedData.materials[index];
  24355. if (parsedMaterial.id === id) {
  24356. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24357. }
  24358. }
  24359. return null;
  24360. };
  24361. var isDescendantOf = function (mesh, names, hierarchyIds) {
  24362. names = (names instanceof Array) ? names : [names];
  24363. for (var i in names) {
  24364. if (mesh.name === names[i]) {
  24365. hierarchyIds.push(mesh.id);
  24366. return true;
  24367. }
  24368. }
  24369. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  24370. hierarchyIds.push(mesh.id);
  24371. return true;
  24372. }
  24373. return false;
  24374. };
  24375. var logOperation = function (operation, producer) {
  24376. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  24377. };
  24378. BABYLON.SceneLoader.RegisterPlugin({
  24379. extensions: ".babylon",
  24380. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  24381. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24382. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24383. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24384. // and avoid problems with multiple concurrent .babylon loads.
  24385. var log = "importMesh has failed JSON parse";
  24386. try {
  24387. var parsedData = JSON.parse(data);
  24388. log = "";
  24389. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24390. var loadedSkeletonsIds = [];
  24391. var loadedMaterialsIds = [];
  24392. var hierarchyIds = [];
  24393. var index;
  24394. var cache;
  24395. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24396. var parsedMesh = parsedData.meshes[index];
  24397. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  24398. if (meshesNames instanceof Array) {
  24399. // Remove found mesh name from list.
  24400. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  24401. }
  24402. //Geometry?
  24403. if (parsedMesh.geometryId) {
  24404. //does the file contain geometries?
  24405. if (parsedData.geometries) {
  24406. //find the correct geometry and add it to the scene
  24407. var found = false;
  24408. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  24409. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  24410. return;
  24411. }
  24412. else {
  24413. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  24414. if (parsedGeometryData.id === parsedMesh.geometryId) {
  24415. switch (geometryType) {
  24416. case "boxes":
  24417. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  24418. break;
  24419. case "spheres":
  24420. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  24421. break;
  24422. case "cylinders":
  24423. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  24424. break;
  24425. case "toruses":
  24426. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  24427. break;
  24428. case "grounds":
  24429. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  24430. break;
  24431. case "planes":
  24432. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  24433. break;
  24434. case "torusKnots":
  24435. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  24436. break;
  24437. case "vertexData":
  24438. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  24439. break;
  24440. }
  24441. found = true;
  24442. }
  24443. });
  24444. }
  24445. });
  24446. if (!found) {
  24447. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24448. }
  24449. }
  24450. }
  24451. // Material ?
  24452. if (parsedMesh.materialId) {
  24453. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24454. if (!materialFound && parsedData.multiMaterials) {
  24455. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24456. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24457. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24458. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24459. var subMatId = parsedMultiMaterial.materials[matIndex];
  24460. loadedMaterialsIds.push(subMatId);
  24461. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24462. log += "\n\tMaterial " + mat.toString(fullDetails);
  24463. }
  24464. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24465. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24466. materialFound = true;
  24467. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24468. break;
  24469. }
  24470. }
  24471. }
  24472. if (!materialFound) {
  24473. loadedMaterialsIds.push(parsedMesh.materialId);
  24474. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24475. if (!mat) {
  24476. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24477. }
  24478. else {
  24479. log += "\n\tMaterial " + mat.toString(fullDetails);
  24480. }
  24481. }
  24482. }
  24483. // Skeleton ?
  24484. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24485. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24486. if (!skeletonAlreadyLoaded) {
  24487. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24488. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24489. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24490. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24491. skeletons.push(skeleton);
  24492. loadedSkeletonsIds.push(parsedSkeleton.id);
  24493. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24494. }
  24495. }
  24496. }
  24497. }
  24498. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24499. meshes.push(mesh);
  24500. log += "\n\tMesh " + mesh.toString(fullDetails);
  24501. }
  24502. }
  24503. // Connecting parents
  24504. var currentMesh;
  24505. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24506. currentMesh = scene.meshes[index];
  24507. if (currentMesh._waitingParentId) {
  24508. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24509. currentMesh._waitingParentId = undefined;
  24510. }
  24511. }
  24512. // freeze and compute world matrix application
  24513. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24514. currentMesh = scene.meshes[index];
  24515. if (currentMesh._waitingFreezeWorldMatrix) {
  24516. currentMesh.freezeWorldMatrix();
  24517. currentMesh._waitingFreezeWorldMatrix = undefined;
  24518. }
  24519. else {
  24520. currentMesh.computeWorldMatrix(true);
  24521. }
  24522. }
  24523. // Particles
  24524. if (parsedData.particleSystems) {
  24525. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24526. var parsedParticleSystem = parsedData.particleSystems[index];
  24527. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24528. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24529. }
  24530. }
  24531. }
  24532. return true;
  24533. }
  24534. catch (err) {
  24535. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24536. log = null;
  24537. throw err;
  24538. }
  24539. finally {
  24540. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24541. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24542. }
  24543. }
  24544. },
  24545. load: function (scene, data, rootUrl) {
  24546. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24547. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24548. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24549. // and avoid problems with multiple concurrent .babylon loads.
  24550. var log = "importScene has failed JSON parse";
  24551. try {
  24552. var parsedData = JSON.parse(data);
  24553. log = "";
  24554. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24555. // Scene
  24556. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24557. scene.autoClear = parsedData.autoClear;
  24558. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24559. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24560. if (parsedData.gravity) {
  24561. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24562. }
  24563. // Fog
  24564. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24565. scene.fogMode = parsedData.fogMode;
  24566. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24567. scene.fogStart = parsedData.fogStart;
  24568. scene.fogEnd = parsedData.fogEnd;
  24569. scene.fogDensity = parsedData.fogDensity;
  24570. log += "\tFog mode for scene: ";
  24571. switch (scene.fogMode) {
  24572. // getters not compiling, so using hardcoded
  24573. case 1:
  24574. log += "exp\n";
  24575. break;
  24576. case 2:
  24577. log += "exp2\n";
  24578. break;
  24579. case 3:
  24580. log += "linear\n";
  24581. break;
  24582. }
  24583. }
  24584. //Physics
  24585. if (parsedData.physicsEnabled) {
  24586. var physicsPlugin;
  24587. if (parsedData.physicsEngine === "cannon") {
  24588. physicsPlugin = new BABYLON.CannonJSPlugin();
  24589. }
  24590. else if (parsedData.physicsEngine === "oimo") {
  24591. physicsPlugin = new BABYLON.OimoJSPlugin();
  24592. }
  24593. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24594. //else - default engine, which is currently oimo
  24595. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24596. scene.enablePhysics(physicsGravity, physicsPlugin);
  24597. }
  24598. //collisions, if defined. otherwise, default is true
  24599. if (parsedData.collisionsEnabled != undefined) {
  24600. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24601. }
  24602. scene.workerCollisions = !!parsedData.workerCollisions;
  24603. var index;
  24604. var cache;
  24605. // Lights
  24606. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24607. var parsedLight = parsedData.lights[index];
  24608. var light = BABYLON.Light.Parse(parsedLight, scene);
  24609. log += (index === 0 ? "\n\tLights:" : "");
  24610. log += "\n\t\t" + light.toString(fullDetails);
  24611. }
  24612. // Animations
  24613. if (parsedData.animations) {
  24614. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24615. var parsedAnimation = parsedData.animations[index];
  24616. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24617. scene.animations.push(animation);
  24618. log += (index === 0 ? "\n\tAnimations:" : "");
  24619. log += "\n\t\t" + animation.toString(fullDetails);
  24620. }
  24621. }
  24622. if (parsedData.autoAnimate) {
  24623. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24624. }
  24625. // Materials
  24626. if (parsedData.materials) {
  24627. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24628. var parsedMaterial = parsedData.materials[index];
  24629. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24630. log += (index === 0 ? "\n\tMaterials:" : "");
  24631. log += "\n\t\t" + mat.toString(fullDetails);
  24632. }
  24633. }
  24634. if (parsedData.multiMaterials) {
  24635. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24636. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24637. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24638. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24639. log += "\n\t\t" + mmat.toString(fullDetails);
  24640. }
  24641. }
  24642. // Skeletons
  24643. if (parsedData.skeletons) {
  24644. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24645. var parsedSkeleton = parsedData.skeletons[index];
  24646. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24647. log += (index === 0 ? "\n\tSkeletons:" : "");
  24648. log += "\n\t\t" + skeleton.toString(fullDetails);
  24649. }
  24650. }
  24651. // Geometries
  24652. var geometries = parsedData.geometries;
  24653. if (geometries) {
  24654. // Boxes
  24655. var boxes = geometries.boxes;
  24656. if (boxes) {
  24657. for (index = 0, cache = boxes.length; index < cache; index++) {
  24658. var parsedBox = boxes[index];
  24659. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24660. }
  24661. }
  24662. // Spheres
  24663. var spheres = geometries.spheres;
  24664. if (spheres) {
  24665. for (index = 0, cache = spheres.length; index < cache; index++) {
  24666. var parsedSphere = spheres[index];
  24667. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24668. }
  24669. }
  24670. // Cylinders
  24671. var cylinders = geometries.cylinders;
  24672. if (cylinders) {
  24673. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24674. var parsedCylinder = cylinders[index];
  24675. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24676. }
  24677. }
  24678. // Toruses
  24679. var toruses = geometries.toruses;
  24680. if (toruses) {
  24681. for (index = 0, cache = toruses.length; index < cache; index++) {
  24682. var parsedTorus = toruses[index];
  24683. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24684. }
  24685. }
  24686. // Grounds
  24687. var grounds = geometries.grounds;
  24688. if (grounds) {
  24689. for (index = 0, cache = grounds.length; index < cache; index++) {
  24690. var parsedGround = grounds[index];
  24691. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24692. }
  24693. }
  24694. // Planes
  24695. var planes = geometries.planes;
  24696. if (planes) {
  24697. for (index = 0, cache = planes.length; index < cache; index++) {
  24698. var parsedPlane = planes[index];
  24699. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24700. }
  24701. }
  24702. // TorusKnots
  24703. var torusKnots = geometries.torusKnots;
  24704. if (torusKnots) {
  24705. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24706. var parsedTorusKnot = torusKnots[index];
  24707. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24708. }
  24709. }
  24710. // VertexData
  24711. var vertexData = geometries.vertexData;
  24712. if (vertexData) {
  24713. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24714. var parsedVertexData = vertexData[index];
  24715. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24716. }
  24717. }
  24718. }
  24719. // Meshes
  24720. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24721. var parsedMesh = parsedData.meshes[index];
  24722. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24723. log += (index === 0 ? "\n\tMeshes:" : "");
  24724. log += "\n\t\t" + mesh.toString(fullDetails);
  24725. }
  24726. // Cameras
  24727. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24728. var parsedCamera = parsedData.cameras[index];
  24729. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24730. log += (index === 0 ? "\n\tCameras:" : "");
  24731. log += "\n\t\t" + camera.toString(fullDetails);
  24732. }
  24733. if (parsedData.activeCameraID) {
  24734. scene.setActiveCameraByID(parsedData.activeCameraID);
  24735. }
  24736. // Browsing all the graph to connect the dots
  24737. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24738. var camera = scene.cameras[index];
  24739. if (camera._waitingParentId) {
  24740. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24741. camera._waitingParentId = undefined;
  24742. }
  24743. }
  24744. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24745. var light = scene.lights[index];
  24746. if (light._waitingParentId) {
  24747. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24748. light._waitingParentId = undefined;
  24749. }
  24750. }
  24751. // Sounds
  24752. var loadedSounds = [];
  24753. var loadedSound;
  24754. if (BABYLON.AudioEngine && parsedData.sounds) {
  24755. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24756. var parsedSound = parsedData.sounds[index];
  24757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24758. if (!parsedSound.url)
  24759. parsedSound.url = parsedSound.name;
  24760. if (!loadedSounds[parsedSound.url]) {
  24761. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24762. loadedSounds[parsedSound.url] = loadedSound;
  24763. }
  24764. else {
  24765. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24766. }
  24767. }
  24768. else {
  24769. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24770. }
  24771. }
  24772. }
  24773. loadedSounds = [];
  24774. // Connect parents & children and parse actions
  24775. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24776. var mesh = scene.meshes[index];
  24777. if (mesh._waitingParentId) {
  24778. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24779. mesh._waitingParentId = undefined;
  24780. }
  24781. if (mesh._waitingActions) {
  24782. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24783. mesh._waitingActions = undefined;
  24784. }
  24785. }
  24786. // freeze world matrix application
  24787. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24788. var currentMesh = scene.meshes[index];
  24789. if (currentMesh._waitingFreezeWorldMatrix) {
  24790. currentMesh.freezeWorldMatrix();
  24791. currentMesh._waitingFreezeWorldMatrix = undefined;
  24792. }
  24793. else {
  24794. currentMesh.computeWorldMatrix(true);
  24795. }
  24796. }
  24797. // Particles Systems
  24798. if (parsedData.particleSystems) {
  24799. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24800. var parsedParticleSystem = parsedData.particleSystems[index];
  24801. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24802. }
  24803. }
  24804. // Lens flares
  24805. if (parsedData.lensFlareSystems) {
  24806. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24807. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24808. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24809. }
  24810. }
  24811. // Shadows
  24812. if (parsedData.shadowGenerators) {
  24813. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24814. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24815. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24816. }
  24817. }
  24818. // Actions (scene)
  24819. if (parsedData.actions) {
  24820. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24821. }
  24822. // Finish
  24823. return true;
  24824. }
  24825. catch (err) {
  24826. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24827. log = null;
  24828. throw err;
  24829. }
  24830. finally {
  24831. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24832. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24833. }
  24834. }
  24835. }
  24836. });
  24837. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24838. })(BABYLON || (BABYLON = {}));
  24839. var BABYLON;
  24840. (function (BABYLON) {
  24841. var SpriteManager = (function () {
  24842. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24844. this.name = name;
  24845. this.cellSize = cellSize;
  24846. this.sprites = new Array();
  24847. this.renderingGroupId = 0;
  24848. this.layerMask = 0x0FFFFFFF;
  24849. this.fogEnabled = true;
  24850. this.isPickable = false;
  24851. /**
  24852. * An event triggered when the manager is disposed.
  24853. * @type {BABYLON.Observable}
  24854. */
  24855. this.onDisposeObservable = new BABYLON.Observable();
  24856. this._vertexDeclaration = [4, 4, 4, 4];
  24857. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24858. this._capacity = capacity;
  24859. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24860. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24861. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24862. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24863. this._scene = scene;
  24864. this._scene.spriteManagers.push(this);
  24865. // VBO
  24866. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24867. var indices = [];
  24868. var index = 0;
  24869. for (var count = 0; count < capacity; count++) {
  24870. indices.push(index);
  24871. indices.push(index + 1);
  24872. indices.push(index + 2);
  24873. indices.push(index);
  24874. indices.push(index + 2);
  24875. indices.push(index + 3);
  24876. index += 4;
  24877. }
  24878. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24879. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24880. // Effects
  24881. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24882. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24883. }
  24884. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  24885. set: function (callback) {
  24886. if (this._onDisposeObserver) {
  24887. this.onDisposeObservable.remove(this._onDisposeObserver);
  24888. }
  24889. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24890. },
  24891. enumerable: true,
  24892. configurable: true
  24893. });
  24894. Object.defineProperty(SpriteManager.prototype, "texture", {
  24895. get: function () {
  24896. return this._spriteTexture;
  24897. },
  24898. set: function (value) {
  24899. this._spriteTexture = value;
  24900. },
  24901. enumerable: true,
  24902. configurable: true
  24903. });
  24904. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24905. var arrayOffset = index * 16;
  24906. if (offsetX === 0)
  24907. offsetX = this._epsilon;
  24908. else if (offsetX === 1)
  24909. offsetX = 1 - this._epsilon;
  24910. if (offsetY === 0)
  24911. offsetY = this._epsilon;
  24912. else if (offsetY === 1)
  24913. offsetY = 1 - this._epsilon;
  24914. this._vertices[arrayOffset] = sprite.position.x;
  24915. this._vertices[arrayOffset + 1] = sprite.position.y;
  24916. this._vertices[arrayOffset + 2] = sprite.position.z;
  24917. this._vertices[arrayOffset + 3] = sprite.angle;
  24918. this._vertices[arrayOffset + 4] = sprite.width;
  24919. this._vertices[arrayOffset + 5] = sprite.height;
  24920. this._vertices[arrayOffset + 6] = offsetX;
  24921. this._vertices[arrayOffset + 7] = offsetY;
  24922. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24923. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24924. var offset = (sprite.cellIndex / rowSize) >> 0;
  24925. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24926. this._vertices[arrayOffset + 11] = offset;
  24927. // Color
  24928. this._vertices[arrayOffset + 12] = sprite.color.r;
  24929. this._vertices[arrayOffset + 13] = sprite.color.g;
  24930. this._vertices[arrayOffset + 14] = sprite.color.b;
  24931. this._vertices[arrayOffset + 15] = sprite.color.a;
  24932. };
  24933. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24934. var count = Math.min(this._capacity, this.sprites.length);
  24935. var min = BABYLON.Vector3.Zero();
  24936. var max = BABYLON.Vector3.Zero();
  24937. var distance = Number.MAX_VALUE;
  24938. var currentSprite;
  24939. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24940. var cameraView = camera.getViewMatrix();
  24941. for (var index = 0; index < count; index++) {
  24942. var sprite = this.sprites[index];
  24943. if (!sprite) {
  24944. continue;
  24945. }
  24946. if (predicate) {
  24947. if (!predicate(sprite)) {
  24948. continue;
  24949. }
  24950. }
  24951. else if (!sprite.isPickable) {
  24952. continue;
  24953. }
  24954. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24955. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24956. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24957. if (ray.intersectsBoxMinMax(min, max)) {
  24958. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24959. if (distance > currentDistance) {
  24960. distance = currentDistance;
  24961. currentSprite = sprite;
  24962. if (fastCheck) {
  24963. break;
  24964. }
  24965. }
  24966. }
  24967. }
  24968. if (currentSprite) {
  24969. var result = new BABYLON.PickingInfo();
  24970. result.hit = true;
  24971. result.pickedSprite = currentSprite;
  24972. result.distance = distance;
  24973. return result;
  24974. }
  24975. return null;
  24976. };
  24977. SpriteManager.prototype.render = function () {
  24978. // Check
  24979. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24980. return;
  24981. var engine = this._scene.getEngine();
  24982. var baseSize = this._spriteTexture.getBaseSize();
  24983. // Sprites
  24984. var deltaTime = engine.getDeltaTime();
  24985. var max = Math.min(this._capacity, this.sprites.length);
  24986. var rowSize = baseSize.width / this.cellSize;
  24987. var offset = 0;
  24988. for (var index = 0; index < max; index++) {
  24989. var sprite = this.sprites[index];
  24990. if (!sprite) {
  24991. continue;
  24992. }
  24993. sprite._animate(deltaTime);
  24994. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24995. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24996. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24997. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24998. }
  24999. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25000. // Render
  25001. var effect = this._effectBase;
  25002. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25003. effect = this._effectFog;
  25004. }
  25005. engine.enableEffect(effect);
  25006. var viewMatrix = this._scene.getViewMatrix();
  25007. effect.setTexture("diffuseSampler", this._spriteTexture);
  25008. effect.setMatrix("view", viewMatrix);
  25009. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25010. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  25011. // Fog
  25012. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25013. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  25014. effect.setColor3("vFogColor", this._scene.fogColor);
  25015. }
  25016. // VBOs
  25017. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25018. // Draw order
  25019. engine.setDepthFunctionToLessOrEqual();
  25020. effect.setBool("alphaTest", true);
  25021. engine.setColorWrite(false);
  25022. engine.draw(true, 0, max * 6);
  25023. engine.setColorWrite(true);
  25024. effect.setBool("alphaTest", false);
  25025. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25026. engine.draw(true, 0, max * 6);
  25027. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25028. };
  25029. SpriteManager.prototype.dispose = function () {
  25030. if (this._vertexBuffer) {
  25031. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25032. this._vertexBuffer = null;
  25033. }
  25034. if (this._indexBuffer) {
  25035. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25036. this._indexBuffer = null;
  25037. }
  25038. if (this._spriteTexture) {
  25039. this._spriteTexture.dispose();
  25040. this._spriteTexture = null;
  25041. }
  25042. // Remove from scene
  25043. var index = this._scene.spriteManagers.indexOf(this);
  25044. this._scene.spriteManagers.splice(index, 1);
  25045. // Callback
  25046. this.onDisposeObservable.notifyObservers(this);
  25047. this.onDisposeObservable.clear();
  25048. };
  25049. return SpriteManager;
  25050. })();
  25051. BABYLON.SpriteManager = SpriteManager;
  25052. })(BABYLON || (BABYLON = {}));
  25053. var BABYLON;
  25054. (function (BABYLON) {
  25055. var Sprite = (function () {
  25056. function Sprite(name, manager) {
  25057. this.name = name;
  25058. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25059. this.width = 1.0;
  25060. this.height = 1.0;
  25061. this.angle = 0;
  25062. this.cellIndex = 0;
  25063. this.invertU = 0;
  25064. this.invertV = 0;
  25065. this.animations = new Array();
  25066. this.isPickable = false;
  25067. this._animationStarted = false;
  25068. this._loopAnimation = false;
  25069. this._fromIndex = 0;
  25070. this._toIndex = 0;
  25071. this._delay = 0;
  25072. this._direction = 1;
  25073. this._frameCount = 0;
  25074. this._time = 0;
  25075. this._manager = manager;
  25076. this._manager.sprites.push(this);
  25077. this.position = BABYLON.Vector3.Zero();
  25078. }
  25079. Object.defineProperty(Sprite.prototype, "size", {
  25080. get: function () {
  25081. return this.width;
  25082. },
  25083. set: function (value) {
  25084. this.width = value;
  25085. this.height = value;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  25091. this._fromIndex = from;
  25092. this._toIndex = to;
  25093. this._loopAnimation = loop;
  25094. this._delay = delay;
  25095. this._animationStarted = true;
  25096. this._direction = from < to ? 1 : -1;
  25097. this.cellIndex = from;
  25098. this._time = 0;
  25099. };
  25100. Sprite.prototype.stopAnimation = function () {
  25101. this._animationStarted = false;
  25102. };
  25103. Sprite.prototype._animate = function (deltaTime) {
  25104. if (!this._animationStarted)
  25105. return;
  25106. this._time += deltaTime;
  25107. if (this._time > this._delay) {
  25108. this._time = this._time % this._delay;
  25109. this.cellIndex += this._direction;
  25110. if (this.cellIndex == this._toIndex) {
  25111. if (this._loopAnimation) {
  25112. this.cellIndex = this._fromIndex;
  25113. }
  25114. else {
  25115. this._animationStarted = false;
  25116. if (this.disposeWhenFinishedAnimating) {
  25117. this.dispose();
  25118. }
  25119. }
  25120. }
  25121. }
  25122. };
  25123. Sprite.prototype.dispose = function () {
  25124. for (var i = 0; i < this._manager.sprites.length; i++) {
  25125. if (this._manager.sprites[i] == this) {
  25126. this._manager.sprites.splice(i, 1);
  25127. }
  25128. }
  25129. };
  25130. return Sprite;
  25131. })();
  25132. BABYLON.Sprite = Sprite;
  25133. })(BABYLON || (BABYLON = {}));
  25134. var BABYLON;
  25135. (function (BABYLON) {
  25136. var Layer = (function () {
  25137. function Layer(name, imgUrl, scene, isBackground, color) {
  25138. this.name = name;
  25139. this.scale = new BABYLON.Vector2(1, 1);
  25140. this.offset = new BABYLON.Vector2(0, 0);
  25141. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  25142. this._vertexDeclaration = [2];
  25143. this._vertexStrideSize = 2 * 4;
  25144. // Events
  25145. /**
  25146. * An event triggered when the layer is disposed.
  25147. * @type {BABYLON.Observable}
  25148. */
  25149. this.onDisposeObservable = new BABYLON.Observable();
  25150. /**
  25151. * An event triggered before rendering the scene
  25152. * @type {BABYLON.Observable}
  25153. */
  25154. this.onBeforeRenderObservable = new BABYLON.Observable();
  25155. /**
  25156. * An event triggered after rendering the scene
  25157. * @type {BABYLON.Observable}
  25158. */
  25159. this.onAfterRenderObservable = new BABYLON.Observable();
  25160. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  25161. this.isBackground = isBackground === undefined ? true : isBackground;
  25162. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  25163. this._scene = scene;
  25164. this._scene.layers.push(this);
  25165. // VBO
  25166. var vertices = [];
  25167. vertices.push(1, 1);
  25168. vertices.push(-1, 1);
  25169. vertices.push(-1, -1);
  25170. vertices.push(1, -1);
  25171. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  25172. // Indices
  25173. var indices = [];
  25174. indices.push(0);
  25175. indices.push(1);
  25176. indices.push(2);
  25177. indices.push(0);
  25178. indices.push(2);
  25179. indices.push(3);
  25180. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25181. // Effects
  25182. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  25183. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  25184. }
  25185. Object.defineProperty(Layer.prototype, "onDispose", {
  25186. set: function (callback) {
  25187. if (this._onDisposeObserver) {
  25188. this.onDisposeObservable.remove(this._onDisposeObserver);
  25189. }
  25190. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25191. },
  25192. enumerable: true,
  25193. configurable: true
  25194. });
  25195. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  25196. set: function (callback) {
  25197. if (this._onBeforeRenderObserver) {
  25198. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25199. }
  25200. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25201. },
  25202. enumerable: true,
  25203. configurable: true
  25204. });
  25205. Object.defineProperty(Layer.prototype, "onAfterRender", {
  25206. set: function (callback) {
  25207. if (this._onAfterRenderObserver) {
  25208. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25209. }
  25210. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25211. },
  25212. enumerable: true,
  25213. configurable: true
  25214. });
  25215. Layer.prototype.render = function () {
  25216. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  25217. // Check
  25218. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  25219. return;
  25220. var engine = this._scene.getEngine();
  25221. this.onBeforeRenderObservable.notifyObservers(this);
  25222. // Render
  25223. engine.enableEffect(currentEffect);
  25224. engine.setState(false);
  25225. // Texture
  25226. currentEffect.setTexture("textureSampler", this.texture);
  25227. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  25228. // Color
  25229. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  25230. // Scale / offset
  25231. currentEffect.setVector2("offset", this.offset);
  25232. currentEffect.setVector2("scale", this.scale);
  25233. // VBOs
  25234. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  25235. // Draw order
  25236. if (!this._alphaTestEffect) {
  25237. engine.setAlphaMode(this.alphaBlendingMode);
  25238. engine.draw(true, 0, 6);
  25239. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25240. }
  25241. else {
  25242. engine.draw(true, 0, 6);
  25243. }
  25244. this.onAfterRenderObservable.notifyObservers(this);
  25245. };
  25246. Layer.prototype.dispose = function () {
  25247. if (this._vertexBuffer) {
  25248. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25249. this._vertexBuffer = null;
  25250. }
  25251. if (this._indexBuffer) {
  25252. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25253. this._indexBuffer = null;
  25254. }
  25255. if (this.texture) {
  25256. this.texture.dispose();
  25257. this.texture = null;
  25258. }
  25259. // Remove from scene
  25260. var index = this._scene.layers.indexOf(this);
  25261. this._scene.layers.splice(index, 1);
  25262. // Callback
  25263. this.onDisposeObservable.notifyObservers(this);
  25264. this.onDisposeObservable.clear();
  25265. this.onAfterRenderObservable.clear();
  25266. this.onBeforeRenderObservable.clear();
  25267. };
  25268. return Layer;
  25269. })();
  25270. BABYLON.Layer = Layer;
  25271. })(BABYLON || (BABYLON = {}));
  25272. var BABYLON;
  25273. (function (BABYLON) {
  25274. var Particle = (function () {
  25275. function Particle() {
  25276. this.position = BABYLON.Vector3.Zero();
  25277. this.direction = BABYLON.Vector3.Zero();
  25278. this.color = new BABYLON.Color4(0, 0, 0, 0);
  25279. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  25280. this.lifeTime = 1.0;
  25281. this.age = 0;
  25282. this.size = 0;
  25283. this.angle = 0;
  25284. this.angularSpeed = 0;
  25285. }
  25286. Particle.prototype.copyTo = function (other) {
  25287. other.position.copyFrom(this.position);
  25288. other.direction.copyFrom(this.direction);
  25289. other.color.copyFrom(this.color);
  25290. other.colorStep.copyFrom(this.colorStep);
  25291. other.lifeTime = this.lifeTime;
  25292. other.age = this.age;
  25293. other.size = this.size;
  25294. other.angle = this.angle;
  25295. other.angularSpeed = this.angularSpeed;
  25296. };
  25297. return Particle;
  25298. })();
  25299. BABYLON.Particle = Particle;
  25300. })(BABYLON || (BABYLON = {}));
  25301. var BABYLON;
  25302. (function (BABYLON) {
  25303. var randomNumber = function (min, max) {
  25304. if (min === max) {
  25305. return (min);
  25306. }
  25307. var random = Math.random();
  25308. return ((random * (max - min)) + min);
  25309. };
  25310. var ParticleSystem = (function () {
  25311. function ParticleSystem(name, capacity, scene, customEffect) {
  25312. var _this = this;
  25313. this.name = name;
  25314. // Members
  25315. this.animations = [];
  25316. this.renderingGroupId = 0;
  25317. this.emitter = null;
  25318. this.emitRate = 10;
  25319. this.manualEmitCount = -1;
  25320. this.updateSpeed = 0.01;
  25321. this.targetStopDuration = 0;
  25322. this.disposeOnStop = false;
  25323. this.minEmitPower = 1;
  25324. this.maxEmitPower = 1;
  25325. this.minLifeTime = 1;
  25326. this.maxLifeTime = 1;
  25327. this.minSize = 1;
  25328. this.maxSize = 1;
  25329. this.minAngularSpeed = 0;
  25330. this.maxAngularSpeed = 0;
  25331. this.layerMask = 0x0FFFFFFF;
  25332. /**
  25333. * An event triggered when the system is disposed.
  25334. * @type {BABYLON.Observable}
  25335. */
  25336. this.onDisposeObservable = new BABYLON.Observable();
  25337. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  25338. this.forceDepthWrite = false;
  25339. this.gravity = BABYLON.Vector3.Zero();
  25340. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  25341. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  25342. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  25343. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  25344. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25345. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25346. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  25347. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  25348. this.particles = new Array();
  25349. this._vertexDeclaration = [3, 4, 4];
  25350. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  25351. this._stockParticles = new Array();
  25352. this._newPartsExcess = 0;
  25353. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  25354. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  25355. this._scaledDirection = BABYLON.Vector3.Zero();
  25356. this._scaledGravity = BABYLON.Vector3.Zero();
  25357. this._currentRenderId = -1;
  25358. this._started = false;
  25359. this._stopped = false;
  25360. this._actualFrame = 0;
  25361. this.id = name;
  25362. this._capacity = capacity;
  25363. this._scene = scene;
  25364. this._customEffect = customEffect;
  25365. scene.particleSystems.push(this);
  25366. // VBO
  25367. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  25368. var indices = [];
  25369. var index = 0;
  25370. for (var count = 0; count < capacity; count++) {
  25371. indices.push(index);
  25372. indices.push(index + 1);
  25373. indices.push(index + 2);
  25374. indices.push(index);
  25375. indices.push(index + 2);
  25376. indices.push(index + 3);
  25377. index += 4;
  25378. }
  25379. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25380. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  25381. // Default behaviors
  25382. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  25383. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  25384. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  25385. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  25386. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  25387. };
  25388. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  25389. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  25390. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  25391. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  25392. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  25393. };
  25394. this.updateFunction = function (particles) {
  25395. for (var index = 0; index < particles.length; index++) {
  25396. var particle = particles[index];
  25397. particle.age += _this._scaledUpdateSpeed;
  25398. if (particle.age >= particle.lifeTime) {
  25399. _this.recycleParticle(particle);
  25400. index--;
  25401. continue;
  25402. }
  25403. else {
  25404. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  25405. particle.color.addInPlace(_this._scaledColorStep);
  25406. if (particle.color.a < 0)
  25407. particle.color.a = 0;
  25408. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  25409. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  25410. particle.position.addInPlace(_this._scaledDirection);
  25411. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  25412. particle.direction.addInPlace(_this._scaledGravity);
  25413. }
  25414. }
  25415. };
  25416. }
  25417. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  25418. set: function (callback) {
  25419. if (this._onDisposeObserver) {
  25420. this.onDisposeObservable.remove(this._onDisposeObserver);
  25421. }
  25422. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25423. },
  25424. enumerable: true,
  25425. configurable: true
  25426. });
  25427. ParticleSystem.prototype.recycleParticle = function (particle) {
  25428. var lastParticle = this.particles.pop();
  25429. if (lastParticle !== particle) {
  25430. lastParticle.copyTo(particle);
  25431. this._stockParticles.push(lastParticle);
  25432. }
  25433. };
  25434. ParticleSystem.prototype.getCapacity = function () {
  25435. return this._capacity;
  25436. };
  25437. ParticleSystem.prototype.isAlive = function () {
  25438. return this._alive;
  25439. };
  25440. ParticleSystem.prototype.isStarted = function () {
  25441. return this._started;
  25442. };
  25443. ParticleSystem.prototype.start = function () {
  25444. this._started = true;
  25445. this._stopped = false;
  25446. this._actualFrame = 0;
  25447. };
  25448. ParticleSystem.prototype.stop = function () {
  25449. this._stopped = true;
  25450. };
  25451. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  25452. var offset = index * 11;
  25453. this._vertices[offset] = particle.position.x;
  25454. this._vertices[offset + 1] = particle.position.y;
  25455. this._vertices[offset + 2] = particle.position.z;
  25456. this._vertices[offset + 3] = particle.color.r;
  25457. this._vertices[offset + 4] = particle.color.g;
  25458. this._vertices[offset + 5] = particle.color.b;
  25459. this._vertices[offset + 6] = particle.color.a;
  25460. this._vertices[offset + 7] = particle.angle;
  25461. this._vertices[offset + 8] = particle.size;
  25462. this._vertices[offset + 9] = offsetX;
  25463. this._vertices[offset + 10] = offsetY;
  25464. };
  25465. ParticleSystem.prototype._update = function (newParticles) {
  25466. // Update current
  25467. this._alive = this.particles.length > 0;
  25468. this.updateFunction(this.particles);
  25469. // Add new ones
  25470. var worldMatrix;
  25471. if (this.emitter.position) {
  25472. worldMatrix = this.emitter.getWorldMatrix();
  25473. }
  25474. else {
  25475. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  25476. }
  25477. var particle;
  25478. for (var index = 0; index < newParticles; index++) {
  25479. if (this.particles.length === this._capacity) {
  25480. break;
  25481. }
  25482. if (this._stockParticles.length !== 0) {
  25483. particle = this._stockParticles.pop();
  25484. particle.age = 0;
  25485. }
  25486. else {
  25487. particle = new BABYLON.Particle();
  25488. }
  25489. this.particles.push(particle);
  25490. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  25491. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  25492. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  25493. particle.size = randomNumber(this.minSize, this.maxSize);
  25494. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  25495. this.startPositionFunction(worldMatrix, particle.position, particle);
  25496. var step = randomNumber(0, 1.0);
  25497. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  25498. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  25499. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  25500. }
  25501. };
  25502. ParticleSystem.prototype._getEffect = function () {
  25503. if (this._customEffect) {
  25504. return this._customEffect;
  25505. }
  25506. ;
  25507. var defines = [];
  25508. if (this._scene.clipPlane) {
  25509. defines.push("#define CLIPPLANE");
  25510. }
  25511. // Effect
  25512. var join = defines.join("\n");
  25513. if (this._cachedDefines !== join) {
  25514. this._cachedDefines = join;
  25515. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25516. }
  25517. return this._effect;
  25518. };
  25519. ParticleSystem.prototype.animate = function () {
  25520. if (!this._started)
  25521. return;
  25522. var effect = this._getEffect();
  25523. // Check
  25524. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25525. return;
  25526. if (this._currentRenderId === this._scene.getRenderId()) {
  25527. return;
  25528. }
  25529. this._currentRenderId = this._scene.getRenderId();
  25530. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25531. // determine the number of particles we need to create
  25532. var newParticles;
  25533. if (this.manualEmitCount > -1) {
  25534. newParticles = this.manualEmitCount;
  25535. this._newPartsExcess = 0;
  25536. this.manualEmitCount = 0;
  25537. }
  25538. else {
  25539. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25540. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25541. }
  25542. if (this._newPartsExcess > 1.0) {
  25543. newParticles += this._newPartsExcess >> 0;
  25544. this._newPartsExcess -= this._newPartsExcess >> 0;
  25545. }
  25546. this._alive = false;
  25547. if (!this._stopped) {
  25548. this._actualFrame += this._scaledUpdateSpeed;
  25549. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25550. this.stop();
  25551. }
  25552. else {
  25553. newParticles = 0;
  25554. }
  25555. this._update(newParticles);
  25556. // Stopped?
  25557. if (this._stopped) {
  25558. if (!this._alive) {
  25559. this._started = false;
  25560. if (this.disposeOnStop) {
  25561. this._scene._toBeDisposed.push(this);
  25562. }
  25563. }
  25564. }
  25565. // Update VBO
  25566. var offset = 0;
  25567. for (var index = 0; index < this.particles.length; index++) {
  25568. var particle = this.particles[index];
  25569. this._appendParticleVertex(offset++, particle, 0, 0);
  25570. this._appendParticleVertex(offset++, particle, 1, 0);
  25571. this._appendParticleVertex(offset++, particle, 1, 1);
  25572. this._appendParticleVertex(offset++, particle, 0, 1);
  25573. }
  25574. var engine = this._scene.getEngine();
  25575. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25576. };
  25577. ParticleSystem.prototype.render = function () {
  25578. var effect = this._getEffect();
  25579. // Check
  25580. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25581. return 0;
  25582. var engine = this._scene.getEngine();
  25583. // Render
  25584. engine.enableEffect(effect);
  25585. engine.setState(false);
  25586. var viewMatrix = this._scene.getViewMatrix();
  25587. effect.setTexture("diffuseSampler", this.particleTexture);
  25588. effect.setMatrix("view", viewMatrix);
  25589. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25590. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25591. if (this._scene.clipPlane) {
  25592. var clipPlane = this._scene.clipPlane;
  25593. var invView = viewMatrix.clone();
  25594. invView.invert();
  25595. effect.setMatrix("invView", invView);
  25596. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25597. }
  25598. // VBOs
  25599. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25600. // Draw order
  25601. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25602. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25603. }
  25604. else {
  25605. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25606. }
  25607. if (this.forceDepthWrite) {
  25608. engine.setDepthWrite(true);
  25609. }
  25610. engine.draw(true, 0, this.particles.length * 6);
  25611. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25612. return this.particles.length;
  25613. };
  25614. ParticleSystem.prototype.dispose = function () {
  25615. if (this._vertexBuffer) {
  25616. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25617. this._vertexBuffer = null;
  25618. }
  25619. if (this._indexBuffer) {
  25620. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25621. this._indexBuffer = null;
  25622. }
  25623. if (this.particleTexture) {
  25624. this.particleTexture.dispose();
  25625. this.particleTexture = null;
  25626. }
  25627. // Remove from scene
  25628. var index = this._scene.particleSystems.indexOf(this);
  25629. this._scene.particleSystems.splice(index, 1);
  25630. // Callback
  25631. this.onDisposeObservable.notifyObservers(this);
  25632. this.onDisposeObservable.clear();
  25633. };
  25634. // Clone
  25635. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25636. var result = new ParticleSystem(name, this._capacity, this._scene);
  25637. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  25638. if (newEmitter === undefined) {
  25639. newEmitter = this.emitter;
  25640. }
  25641. result.emitter = newEmitter;
  25642. if (this.particleTexture) {
  25643. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25644. }
  25645. result.start();
  25646. return result;
  25647. };
  25648. ParticleSystem.prototype.serialize = function () {
  25649. var serializationObject = {};
  25650. serializationObject.name = this.name;
  25651. serializationObject.id = this.id;
  25652. // Emitter
  25653. if (this.emitter.position) {
  25654. serializationObject.emitterId = this.emitter.id;
  25655. }
  25656. else {
  25657. serializationObject.emitter = this.emitter.asArray();
  25658. }
  25659. serializationObject.capacity = this.getCapacity();
  25660. if (this.particleTexture) {
  25661. serializationObject.textureName = this.particleTexture.name;
  25662. }
  25663. // Animations
  25664. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25665. // Particle system
  25666. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25667. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25668. serializationObject.minSize = this.minSize;
  25669. serializationObject.maxSize = this.maxSize;
  25670. serializationObject.minEmitPower = this.minEmitPower;
  25671. serializationObject.maxEmitPower = this.maxEmitPower;
  25672. serializationObject.minLifeTime = this.minLifeTime;
  25673. serializationObject.maxLifeTime = this.maxLifeTime;
  25674. serializationObject.emitRate = this.emitRate;
  25675. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25676. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  25677. serializationObject.gravity = this.gravity.asArray();
  25678. serializationObject.direction1 = this.direction1.asArray();
  25679. serializationObject.direction2 = this.direction2.asArray();
  25680. serializationObject.color1 = this.color1.asArray();
  25681. serializationObject.color2 = this.color2.asArray();
  25682. serializationObject.colorDead = this.colorDead.asArray();
  25683. serializationObject.updateSpeed = this.updateSpeed;
  25684. serializationObject.targetStopDuration = this.targetStopDuration;
  25685. serializationObject.textureMask = this.textureMask.asArray();
  25686. serializationObject.blendMode = this.blendMode;
  25687. return serializationObject;
  25688. };
  25689. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  25690. var name = parsedParticleSystem.name;
  25691. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  25692. if (parsedParticleSystem.id) {
  25693. particleSystem.id = parsedParticleSystem.id;
  25694. }
  25695. // Texture
  25696. if (parsedParticleSystem.textureName) {
  25697. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  25698. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  25699. }
  25700. // Emitter
  25701. if (parsedParticleSystem.emitterId) {
  25702. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  25703. }
  25704. else {
  25705. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  25706. }
  25707. // Animations
  25708. if (parsedParticleSystem.animations) {
  25709. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25710. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25711. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25712. }
  25713. }
  25714. if (parsedParticleSystem.autoAnimate) {
  25715. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25716. }
  25717. // Particle system
  25718. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25719. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25720. particleSystem.minSize = parsedParticleSystem.minSize;
  25721. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25722. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25723. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25724. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25725. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25726. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25727. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25728. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25729. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25730. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25731. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25732. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25733. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25734. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25735. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25736. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25737. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25738. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25739. if (!parsedParticleSystem.preventAutoStart) {
  25740. particleSystem.start();
  25741. }
  25742. return particleSystem;
  25743. };
  25744. // Statics
  25745. ParticleSystem.BLENDMODE_ONEONE = 0;
  25746. ParticleSystem.BLENDMODE_STANDARD = 1;
  25747. return ParticleSystem;
  25748. })();
  25749. BABYLON.ParticleSystem = ParticleSystem;
  25750. })(BABYLON || (BABYLON = {}));
  25751. var BABYLON;
  25752. (function (BABYLON) {
  25753. var AnimationRange = (function () {
  25754. function AnimationRange(name, from, to) {
  25755. this.name = name;
  25756. this.from = from;
  25757. this.to = to;
  25758. }
  25759. AnimationRange.prototype.clone = function () {
  25760. return new AnimationRange(this.name, this.from, this.to);
  25761. };
  25762. return AnimationRange;
  25763. })();
  25764. BABYLON.AnimationRange = AnimationRange;
  25765. /**
  25766. * Composed of a frame, and an action function
  25767. */
  25768. var AnimationEvent = (function () {
  25769. function AnimationEvent(frame, action, onlyOnce) {
  25770. this.frame = frame;
  25771. this.action = action;
  25772. this.onlyOnce = onlyOnce;
  25773. this.isDone = false;
  25774. }
  25775. return AnimationEvent;
  25776. })();
  25777. BABYLON.AnimationEvent = AnimationEvent;
  25778. var PathCursor = (function () {
  25779. function PathCursor(path) {
  25780. this.path = path;
  25781. this._onchange = new Array();
  25782. this.value = 0;
  25783. this.animations = new Array();
  25784. }
  25785. PathCursor.prototype.getPoint = function () {
  25786. var point = this.path.getPointAtLengthPosition(this.value);
  25787. return new BABYLON.Vector3(point.x, 0, point.y);
  25788. };
  25789. PathCursor.prototype.moveAhead = function (step) {
  25790. if (step === void 0) { step = 0.002; }
  25791. this.move(step);
  25792. return this;
  25793. };
  25794. PathCursor.prototype.moveBack = function (step) {
  25795. if (step === void 0) { step = 0.002; }
  25796. this.move(-step);
  25797. return this;
  25798. };
  25799. PathCursor.prototype.move = function (step) {
  25800. if (Math.abs(step) > 1) {
  25801. throw "step size should be less than 1.";
  25802. }
  25803. this.value += step;
  25804. this.ensureLimits();
  25805. this.raiseOnChange();
  25806. return this;
  25807. };
  25808. PathCursor.prototype.ensureLimits = function () {
  25809. while (this.value > 1) {
  25810. this.value -= 1;
  25811. }
  25812. while (this.value < 0) {
  25813. this.value += 1;
  25814. }
  25815. return this;
  25816. };
  25817. // used by animation engine
  25818. PathCursor.prototype.markAsDirty = function (propertyName) {
  25819. this.ensureLimits();
  25820. this.raiseOnChange();
  25821. return this;
  25822. };
  25823. PathCursor.prototype.raiseOnChange = function () {
  25824. var _this = this;
  25825. this._onchange.forEach(function (f) { return f(_this); });
  25826. return this;
  25827. };
  25828. PathCursor.prototype.onchange = function (f) {
  25829. this._onchange.push(f);
  25830. return this;
  25831. };
  25832. return PathCursor;
  25833. })();
  25834. BABYLON.PathCursor = PathCursor;
  25835. var Animation = (function () {
  25836. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25837. this.name = name;
  25838. this.targetProperty = targetProperty;
  25839. this.framePerSecond = framePerSecond;
  25840. this.dataType = dataType;
  25841. this.loopMode = loopMode;
  25842. this.enableBlending = enableBlending;
  25843. this._offsetsCache = {};
  25844. this._highLimitsCache = {};
  25845. this._stopped = false;
  25846. this._blendingFactor = 0;
  25847. // The set of event that will be linked to this animation
  25848. this._events = new Array();
  25849. this.allowMatricesInterpolation = false;
  25850. this.blendingSpeed = 0.01;
  25851. this._ranges = {};
  25852. this.targetPropertyPath = targetProperty.split(".");
  25853. this.dataType = dataType;
  25854. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25855. }
  25856. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25857. var dataType = undefined;
  25858. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25859. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25860. }
  25861. else if (from instanceof BABYLON.Quaternion) {
  25862. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25863. }
  25864. else if (from instanceof BABYLON.Vector3) {
  25865. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25866. }
  25867. else if (from instanceof BABYLON.Vector2) {
  25868. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25869. }
  25870. else if (from instanceof BABYLON.Color3) {
  25871. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25872. }
  25873. else if (from instanceof BABYLON.Size) {
  25874. dataType = Animation.ANIMATIONTYPE_SIZE;
  25875. }
  25876. if (dataType == undefined) {
  25877. return null;
  25878. }
  25879. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25880. var keys = [];
  25881. keys.push({ frame: 0, value: from });
  25882. keys.push({ frame: totalFrame, value: to });
  25883. animation.setKeys(keys);
  25884. if (easingFunction !== undefined) {
  25885. animation.setEasingFunction(easingFunction);
  25886. }
  25887. return animation;
  25888. };
  25889. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25890. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25891. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25892. };
  25893. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25894. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25895. node.animations.push(animation);
  25896. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25897. };
  25898. // Methods
  25899. /**
  25900. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25901. */
  25902. Animation.prototype.toString = function (fullDetails) {
  25903. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25904. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25905. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25906. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25907. if (fullDetails) {
  25908. ret += ", Ranges: {";
  25909. var first = true;
  25910. for (var name in this._ranges) {
  25911. if (first) {
  25912. ret += ", ";
  25913. first = false;
  25914. }
  25915. ret += name;
  25916. }
  25917. ret += "}";
  25918. }
  25919. return ret;
  25920. };
  25921. /**
  25922. * Add an event to this animation.
  25923. */
  25924. Animation.prototype.addEvent = function (event) {
  25925. this._events.push(event);
  25926. };
  25927. /**
  25928. * Remove all events found at the given frame
  25929. * @param frame
  25930. */
  25931. Animation.prototype.removeEvents = function (frame) {
  25932. for (var index = 0; index < this._events.length; index++) {
  25933. if (this._events[index].frame === frame) {
  25934. this._events.splice(index, 1);
  25935. index--;
  25936. }
  25937. }
  25938. };
  25939. Animation.prototype.createRange = function (name, from, to) {
  25940. // check name not already in use; could happen for bones after serialized
  25941. if (!this._ranges[name]) {
  25942. this._ranges[name] = new AnimationRange(name, from, to);
  25943. }
  25944. };
  25945. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25946. if (deleteFrames === void 0) { deleteFrames = true; }
  25947. if (this._ranges[name]) {
  25948. if (deleteFrames) {
  25949. var from = this._ranges[name].from;
  25950. var to = this._ranges[name].to;
  25951. // this loop MUST go high to low for multiple splices to work
  25952. for (var key = this._keys.length - 1; key >= 0; key--) {
  25953. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25954. this._keys.splice(key, 1);
  25955. }
  25956. }
  25957. }
  25958. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25959. }
  25960. };
  25961. Animation.prototype.getRange = function (name) {
  25962. return this._ranges[name];
  25963. };
  25964. Animation.prototype.reset = function () {
  25965. this._offsetsCache = {};
  25966. this._highLimitsCache = {};
  25967. this.currentFrame = 0;
  25968. this._blendingFactor = 0;
  25969. this._originalBlendValue = null;
  25970. };
  25971. Animation.prototype.isStopped = function () {
  25972. return this._stopped;
  25973. };
  25974. Animation.prototype.getKeys = function () {
  25975. return this._keys;
  25976. };
  25977. Animation.prototype.getHighestFrame = function () {
  25978. var ret = 0;
  25979. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25980. if (ret < this._keys[key].frame) {
  25981. ret = this._keys[key].frame;
  25982. }
  25983. }
  25984. return ret;
  25985. };
  25986. Animation.prototype.getEasingFunction = function () {
  25987. return this._easingFunction;
  25988. };
  25989. Animation.prototype.setEasingFunction = function (easingFunction) {
  25990. this._easingFunction = easingFunction;
  25991. };
  25992. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25993. return startValue + (endValue - startValue) * gradient;
  25994. };
  25995. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25996. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25997. };
  25998. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25999. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  26000. };
  26001. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  26002. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  26003. };
  26004. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  26005. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  26006. };
  26007. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  26008. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  26009. };
  26010. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  26011. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  26012. };
  26013. Animation.prototype.clone = function () {
  26014. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  26015. if (this._keys) {
  26016. clone.setKeys(this._keys);
  26017. }
  26018. if (this._ranges) {
  26019. clone._ranges = {};
  26020. for (var name in this._ranges) {
  26021. clone._ranges[name] = this._ranges[name].clone();
  26022. }
  26023. }
  26024. return clone;
  26025. };
  26026. Animation.prototype.setKeys = function (values) {
  26027. this._keys = values.slice(0);
  26028. this._offsetsCache = {};
  26029. this._highLimitsCache = {};
  26030. };
  26031. Animation.prototype._getKeyValue = function (value) {
  26032. if (typeof value === "function") {
  26033. return value();
  26034. }
  26035. return value;
  26036. };
  26037. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  26038. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  26039. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  26040. }
  26041. this.currentFrame = currentFrame;
  26042. // Try to get a hash to find the right key
  26043. 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));
  26044. if (this._keys[startKey].frame >= currentFrame) {
  26045. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  26046. startKey--;
  26047. }
  26048. }
  26049. for (var key = startKey; key < this._keys.length; key++) {
  26050. if (this._keys[key + 1].frame >= currentFrame) {
  26051. var startValue = this._getKeyValue(this._keys[key].value);
  26052. var endValue = this._getKeyValue(this._keys[key + 1].value);
  26053. // gradient : percent of currentFrame between the frame inf and the frame sup
  26054. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  26055. // check for easingFunction and correction of gradient
  26056. if (this._easingFunction != null) {
  26057. gradient = this._easingFunction.ease(gradient);
  26058. }
  26059. switch (this.dataType) {
  26060. // Float
  26061. case Animation.ANIMATIONTYPE_FLOAT:
  26062. switch (loopMode) {
  26063. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26064. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26065. return this.floatInterpolateFunction(startValue, endValue, gradient);
  26066. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26067. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  26068. }
  26069. break;
  26070. // Quaternion
  26071. case Animation.ANIMATIONTYPE_QUATERNION:
  26072. var quaternion = null;
  26073. switch (loopMode) {
  26074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26076. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  26077. break;
  26078. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26079. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26080. break;
  26081. }
  26082. return quaternion;
  26083. // Vector3
  26084. case Animation.ANIMATIONTYPE_VECTOR3:
  26085. switch (loopMode) {
  26086. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26087. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26088. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  26089. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26090. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26091. }
  26092. // Vector2
  26093. case Animation.ANIMATIONTYPE_VECTOR2:
  26094. switch (loopMode) {
  26095. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26096. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26097. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  26098. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26099. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26100. }
  26101. // Size
  26102. case Animation.ANIMATIONTYPE_SIZE:
  26103. switch (loopMode) {
  26104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26106. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  26107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26108. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26109. }
  26110. // Color3
  26111. case Animation.ANIMATIONTYPE_COLOR3:
  26112. switch (loopMode) {
  26113. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26114. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26115. return this.color3InterpolateFunction(startValue, endValue, gradient);
  26116. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26117. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  26118. }
  26119. // Matrix
  26120. case Animation.ANIMATIONTYPE_MATRIX:
  26121. switch (loopMode) {
  26122. case Animation.ANIMATIONLOOPMODE_CYCLE:
  26123. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  26124. if (this.allowMatricesInterpolation) {
  26125. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  26126. }
  26127. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  26128. return startValue;
  26129. }
  26130. default:
  26131. break;
  26132. }
  26133. break;
  26134. }
  26135. }
  26136. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  26137. };
  26138. Animation.prototype.setValue = function (currentValue, blend) {
  26139. if (blend === void 0) { blend = false; }
  26140. // Set value
  26141. var path;
  26142. var destination;
  26143. if (this.targetPropertyPath.length > 1) {
  26144. var property = this._target[this.targetPropertyPath[0]];
  26145. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  26146. property = property[this.targetPropertyPath[index]];
  26147. }
  26148. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  26149. destination = property;
  26150. }
  26151. else {
  26152. path = this.targetPropertyPath[0];
  26153. destination = this._target;
  26154. }
  26155. // Blending
  26156. if (this.enableBlending && this._blendingFactor <= 1.0) {
  26157. if (!this._originalBlendValue) {
  26158. if (destination[path].clone) {
  26159. this._originalBlendValue = destination[path].clone();
  26160. }
  26161. else {
  26162. this._originalBlendValue = destination[path];
  26163. }
  26164. }
  26165. if (this._originalBlendValue.prototype) {
  26166. if (this._originalBlendValue.prototype.Lerp) {
  26167. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  26168. }
  26169. else {
  26170. destination[path] = currentValue;
  26171. }
  26172. }
  26173. else if (this._originalBlendValue.m) {
  26174. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  26175. }
  26176. else {
  26177. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  26178. }
  26179. this._blendingFactor += this.blendingSpeed;
  26180. }
  26181. else {
  26182. destination[path] = currentValue;
  26183. }
  26184. if (this._target.markAsDirty) {
  26185. this._target.markAsDirty(this.targetProperty);
  26186. }
  26187. };
  26188. Animation.prototype.goToFrame = function (frame) {
  26189. if (frame < this._keys[0].frame) {
  26190. frame = this._keys[0].frame;
  26191. }
  26192. else if (frame > this._keys[this._keys.length - 1].frame) {
  26193. frame = this._keys[this._keys.length - 1].frame;
  26194. }
  26195. var currentValue = this._interpolate(frame, 0, this.loopMode);
  26196. this.setValue(currentValue);
  26197. };
  26198. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  26199. if (blend === void 0) { blend = false; }
  26200. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  26201. this._stopped = true;
  26202. return false;
  26203. }
  26204. var returnValue = true;
  26205. // Adding a start key at frame 0 if missing
  26206. if (this._keys[0].frame !== 0) {
  26207. var newKey = { frame: 0, value: this._keys[0].value };
  26208. this._keys.splice(0, 0, newKey);
  26209. }
  26210. // Check limits
  26211. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  26212. from = this._keys[0].frame;
  26213. }
  26214. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  26215. to = this._keys[this._keys.length - 1].frame;
  26216. }
  26217. // Compute ratio
  26218. var range = to - from;
  26219. var offsetValue;
  26220. // ratio represents the frame delta between from and to
  26221. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  26222. var highLimitValue = 0;
  26223. if (ratio > range && !loop) {
  26224. returnValue = false;
  26225. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  26226. }
  26227. else {
  26228. // Get max value if required
  26229. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  26230. var keyOffset = to.toString() + from.toString();
  26231. if (!this._offsetsCache[keyOffset]) {
  26232. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26233. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  26234. switch (this.dataType) {
  26235. // Float
  26236. case Animation.ANIMATIONTYPE_FLOAT:
  26237. this._offsetsCache[keyOffset] = toValue - fromValue;
  26238. break;
  26239. // Quaternion
  26240. case Animation.ANIMATIONTYPE_QUATERNION:
  26241. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26242. break;
  26243. // Vector3
  26244. case Animation.ANIMATIONTYPE_VECTOR3:
  26245. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26246. // Vector2
  26247. case Animation.ANIMATIONTYPE_VECTOR2:
  26248. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26249. // Size
  26250. case Animation.ANIMATIONTYPE_SIZE:
  26251. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26252. // Color3
  26253. case Animation.ANIMATIONTYPE_COLOR3:
  26254. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  26255. default:
  26256. break;
  26257. }
  26258. this._highLimitsCache[keyOffset] = toValue;
  26259. }
  26260. highLimitValue = this._highLimitsCache[keyOffset];
  26261. offsetValue = this._offsetsCache[keyOffset];
  26262. }
  26263. }
  26264. if (offsetValue === undefined) {
  26265. switch (this.dataType) {
  26266. // Float
  26267. case Animation.ANIMATIONTYPE_FLOAT:
  26268. offsetValue = 0;
  26269. break;
  26270. // Quaternion
  26271. case Animation.ANIMATIONTYPE_QUATERNION:
  26272. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  26273. break;
  26274. // Vector3
  26275. case Animation.ANIMATIONTYPE_VECTOR3:
  26276. offsetValue = BABYLON.Vector3.Zero();
  26277. break;
  26278. // Vector2
  26279. case Animation.ANIMATIONTYPE_VECTOR2:
  26280. offsetValue = BABYLON.Vector2.Zero();
  26281. break;
  26282. // Size
  26283. case Animation.ANIMATIONTYPE_SIZE:
  26284. offsetValue = BABYLON.Size.Zero();
  26285. break;
  26286. // Color3
  26287. case Animation.ANIMATIONTYPE_COLOR3:
  26288. offsetValue = BABYLON.Color3.Black();
  26289. }
  26290. }
  26291. // Compute value
  26292. var repeatCount = (ratio / range) >> 0;
  26293. var currentFrame = returnValue ? from + ratio % range : to;
  26294. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  26295. // Set value
  26296. this.setValue(currentValue);
  26297. // Check events
  26298. for (var index = 0; index < this._events.length; index++) {
  26299. if (currentFrame >= this._events[index].frame) {
  26300. var event = this._events[index];
  26301. if (!event.isDone) {
  26302. // If event should be done only once, remove it.
  26303. if (event.onlyOnce) {
  26304. this._events.splice(index, 1);
  26305. index--;
  26306. }
  26307. event.isDone = true;
  26308. event.action();
  26309. } // Don't do anything if the event has already be done.
  26310. }
  26311. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  26312. // reset event, the animation is looping
  26313. this._events[index].isDone = false;
  26314. }
  26315. }
  26316. if (!returnValue) {
  26317. this._stopped = true;
  26318. }
  26319. return returnValue;
  26320. };
  26321. Animation.prototype.serialize = function () {
  26322. var serializationObject = {};
  26323. serializationObject.name = this.name;
  26324. serializationObject.property = this.targetProperty;
  26325. serializationObject.framePerSecond = this.framePerSecond;
  26326. serializationObject.dataType = this.dataType;
  26327. serializationObject.loopBehavior = this.loopMode;
  26328. var dataType = this.dataType;
  26329. serializationObject.keys = [];
  26330. var keys = this.getKeys();
  26331. for (var index = 0; index < keys.length; index++) {
  26332. var animationKey = keys[index];
  26333. var key = {};
  26334. key.frame = animationKey.frame;
  26335. switch (dataType) {
  26336. case Animation.ANIMATIONTYPE_FLOAT:
  26337. key.values = [animationKey.value];
  26338. break;
  26339. case Animation.ANIMATIONTYPE_QUATERNION:
  26340. case Animation.ANIMATIONTYPE_MATRIX:
  26341. case Animation.ANIMATIONTYPE_VECTOR3:
  26342. case Animation.ANIMATIONTYPE_COLOR3:
  26343. key.values = animationKey.value.asArray();
  26344. break;
  26345. }
  26346. serializationObject.keys.push(key);
  26347. }
  26348. serializationObject.ranges = [];
  26349. for (var name in this._ranges) {
  26350. var range = {};
  26351. range.name = name;
  26352. range.from = this._ranges[name].from;
  26353. range.to = this._ranges[name].to;
  26354. serializationObject.ranges.push(range);
  26355. }
  26356. return serializationObject;
  26357. };
  26358. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  26359. get: function () {
  26360. return Animation._ANIMATIONTYPE_FLOAT;
  26361. },
  26362. enumerable: true,
  26363. configurable: true
  26364. });
  26365. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  26366. get: function () {
  26367. return Animation._ANIMATIONTYPE_VECTOR3;
  26368. },
  26369. enumerable: true,
  26370. configurable: true
  26371. });
  26372. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  26373. get: function () {
  26374. return Animation._ANIMATIONTYPE_VECTOR2;
  26375. },
  26376. enumerable: true,
  26377. configurable: true
  26378. });
  26379. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  26380. get: function () {
  26381. return Animation._ANIMATIONTYPE_SIZE;
  26382. },
  26383. enumerable: true,
  26384. configurable: true
  26385. });
  26386. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  26387. get: function () {
  26388. return Animation._ANIMATIONTYPE_QUATERNION;
  26389. },
  26390. enumerable: true,
  26391. configurable: true
  26392. });
  26393. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  26394. get: function () {
  26395. return Animation._ANIMATIONTYPE_MATRIX;
  26396. },
  26397. enumerable: true,
  26398. configurable: true
  26399. });
  26400. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  26401. get: function () {
  26402. return Animation._ANIMATIONTYPE_COLOR3;
  26403. },
  26404. enumerable: true,
  26405. configurable: true
  26406. });
  26407. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  26408. get: function () {
  26409. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  26410. },
  26411. enumerable: true,
  26412. configurable: true
  26413. });
  26414. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  26415. get: function () {
  26416. return Animation._ANIMATIONLOOPMODE_CYCLE;
  26417. },
  26418. enumerable: true,
  26419. configurable: true
  26420. });
  26421. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  26422. get: function () {
  26423. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  26424. },
  26425. enumerable: true,
  26426. configurable: true
  26427. });
  26428. Animation.Parse = function (parsedAnimation) {
  26429. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  26430. var dataType = parsedAnimation.dataType;
  26431. var keys = [];
  26432. var data;
  26433. var index;
  26434. for (index = 0; index < parsedAnimation.keys.length; index++) {
  26435. var key = parsedAnimation.keys[index];
  26436. switch (dataType) {
  26437. case Animation.ANIMATIONTYPE_FLOAT:
  26438. data = key.values[0];
  26439. break;
  26440. case Animation.ANIMATIONTYPE_QUATERNION:
  26441. data = BABYLON.Quaternion.FromArray(key.values);
  26442. break;
  26443. case Animation.ANIMATIONTYPE_MATRIX:
  26444. data = BABYLON.Matrix.FromArray(key.values);
  26445. break;
  26446. case Animation.ANIMATIONTYPE_COLOR3:
  26447. data = BABYLON.Color3.FromArray(key.values);
  26448. break;
  26449. case Animation.ANIMATIONTYPE_VECTOR3:
  26450. default:
  26451. data = BABYLON.Vector3.FromArray(key.values);
  26452. break;
  26453. }
  26454. keys.push({
  26455. frame: key.frame,
  26456. value: data
  26457. });
  26458. }
  26459. animation.setKeys(keys);
  26460. if (parsedAnimation.ranges) {
  26461. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  26462. data = parsedAnimation.ranges[index];
  26463. animation.createRange(data.name, data.from, data.to);
  26464. }
  26465. }
  26466. return animation;
  26467. };
  26468. Animation.AppendSerializedAnimations = function (source, destination) {
  26469. if (source.animations) {
  26470. destination.animations = [];
  26471. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  26472. var animation = source.animations[animationIndex];
  26473. destination.animations.push(animation.serialize());
  26474. }
  26475. }
  26476. };
  26477. // Statics
  26478. Animation._ANIMATIONTYPE_FLOAT = 0;
  26479. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  26480. Animation._ANIMATIONTYPE_QUATERNION = 2;
  26481. Animation._ANIMATIONTYPE_MATRIX = 3;
  26482. Animation._ANIMATIONTYPE_COLOR3 = 4;
  26483. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  26484. Animation._ANIMATIONTYPE_SIZE = 6;
  26485. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  26486. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  26487. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  26488. return Animation;
  26489. })();
  26490. BABYLON.Animation = Animation;
  26491. })(BABYLON || (BABYLON = {}));
  26492. var BABYLON;
  26493. (function (BABYLON) {
  26494. var Animatable = (function () {
  26495. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  26496. if (fromFrame === void 0) { fromFrame = 0; }
  26497. if (toFrame === void 0) { toFrame = 100; }
  26498. if (loopAnimation === void 0) { loopAnimation = false; }
  26499. if (speedRatio === void 0) { speedRatio = 1.0; }
  26500. this.target = target;
  26501. this.fromFrame = fromFrame;
  26502. this.toFrame = toFrame;
  26503. this.loopAnimation = loopAnimation;
  26504. this.speedRatio = speedRatio;
  26505. this.onAnimationEnd = onAnimationEnd;
  26506. this._animations = new Array();
  26507. this._paused = false;
  26508. this.animationStarted = false;
  26509. if (animations) {
  26510. this.appendAnimations(target, animations);
  26511. }
  26512. this._scene = scene;
  26513. scene._activeAnimatables.push(this);
  26514. }
  26515. // Methods
  26516. Animatable.prototype.getAnimations = function () {
  26517. return this._animations;
  26518. };
  26519. Animatable.prototype.appendAnimations = function (target, animations) {
  26520. for (var index = 0; index < animations.length; index++) {
  26521. var animation = animations[index];
  26522. animation._target = target;
  26523. this._animations.push(animation);
  26524. }
  26525. };
  26526. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  26527. var animations = this._animations;
  26528. for (var index = 0; index < animations.length; index++) {
  26529. if (animations[index].targetProperty === property) {
  26530. return animations[index];
  26531. }
  26532. }
  26533. return null;
  26534. };
  26535. Animatable.prototype.reset = function () {
  26536. var animations = this._animations;
  26537. for (var index = 0; index < animations.length; index++) {
  26538. animations[index].reset();
  26539. }
  26540. this._localDelayOffset = null;
  26541. this._pausedDelay = null;
  26542. };
  26543. Animatable.prototype.enableBlending = function (blendingSpeed) {
  26544. var animations = this._animations;
  26545. for (var index = 0; index < animations.length; index++) {
  26546. animations[index].enableBlending = true;
  26547. animations[index].blendingSpeed = blendingSpeed;
  26548. }
  26549. };
  26550. Animatable.prototype.disableBlending = function () {
  26551. var animations = this._animations;
  26552. for (var index = 0; index < animations.length; index++) {
  26553. animations[index].enableBlending = false;
  26554. }
  26555. };
  26556. Animatable.prototype.goToFrame = function (frame) {
  26557. var animations = this._animations;
  26558. for (var index = 0; index < animations.length; index++) {
  26559. animations[index].goToFrame(frame);
  26560. }
  26561. };
  26562. Animatable.prototype.pause = function () {
  26563. if (this._paused) {
  26564. return;
  26565. }
  26566. this._paused = true;
  26567. };
  26568. Animatable.prototype.restart = function () {
  26569. this._paused = false;
  26570. };
  26571. Animatable.prototype.stop = function () {
  26572. var index = this._scene._activeAnimatables.indexOf(this);
  26573. if (index > -1) {
  26574. this._scene._activeAnimatables.splice(index, 1);
  26575. var animations = this._animations;
  26576. for (var index = 0; index < animations.length; index++) {
  26577. animations[index].reset();
  26578. }
  26579. if (this.onAnimationEnd) {
  26580. this.onAnimationEnd();
  26581. }
  26582. }
  26583. };
  26584. Animatable.prototype._animate = function (delay) {
  26585. if (this._paused) {
  26586. this.animationStarted = false;
  26587. if (!this._pausedDelay) {
  26588. this._pausedDelay = delay;
  26589. }
  26590. return true;
  26591. }
  26592. if (!this._localDelayOffset) {
  26593. this._localDelayOffset = delay;
  26594. }
  26595. else if (this._pausedDelay) {
  26596. this._localDelayOffset += delay - this._pausedDelay;
  26597. this._pausedDelay = null;
  26598. }
  26599. // Animating
  26600. var running = false;
  26601. var animations = this._animations;
  26602. var index;
  26603. for (index = 0; index < animations.length; index++) {
  26604. var animation = animations[index];
  26605. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26606. running = running || isRunning;
  26607. }
  26608. this.animationStarted = running;
  26609. if (!running) {
  26610. // Remove from active animatables
  26611. index = this._scene._activeAnimatables.indexOf(this);
  26612. this._scene._activeAnimatables.splice(index, 1);
  26613. }
  26614. if (!running && this.onAnimationEnd) {
  26615. this.onAnimationEnd();
  26616. this.onAnimationEnd = null;
  26617. }
  26618. return running;
  26619. };
  26620. return Animatable;
  26621. })();
  26622. BABYLON.Animatable = Animatable;
  26623. })(BABYLON || (BABYLON = {}));
  26624. var BABYLON;
  26625. (function (BABYLON) {
  26626. var EasingFunction = (function () {
  26627. function EasingFunction() {
  26628. // Properties
  26629. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26630. }
  26631. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26632. get: function () {
  26633. return EasingFunction._EASINGMODE_EASEIN;
  26634. },
  26635. enumerable: true,
  26636. configurable: true
  26637. });
  26638. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26639. get: function () {
  26640. return EasingFunction._EASINGMODE_EASEOUT;
  26641. },
  26642. enumerable: true,
  26643. configurable: true
  26644. });
  26645. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26646. get: function () {
  26647. return EasingFunction._EASINGMODE_EASEINOUT;
  26648. },
  26649. enumerable: true,
  26650. configurable: true
  26651. });
  26652. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26653. var n = Math.min(Math.max(easingMode, 0), 2);
  26654. this._easingMode = n;
  26655. };
  26656. EasingFunction.prototype.getEasingMode = function () {
  26657. return this._easingMode;
  26658. };
  26659. EasingFunction.prototype.easeInCore = function (gradient) {
  26660. throw new Error('You must implement this method');
  26661. };
  26662. EasingFunction.prototype.ease = function (gradient) {
  26663. switch (this._easingMode) {
  26664. case EasingFunction.EASINGMODE_EASEIN:
  26665. return this.easeInCore(gradient);
  26666. case EasingFunction.EASINGMODE_EASEOUT:
  26667. return (1 - this.easeInCore(1 - gradient));
  26668. }
  26669. if (gradient >= 0.5) {
  26670. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26671. }
  26672. return (this.easeInCore(gradient * 2) * 0.5);
  26673. };
  26674. //Statics
  26675. EasingFunction._EASINGMODE_EASEIN = 0;
  26676. EasingFunction._EASINGMODE_EASEOUT = 1;
  26677. EasingFunction._EASINGMODE_EASEINOUT = 2;
  26678. return EasingFunction;
  26679. })();
  26680. BABYLON.EasingFunction = EasingFunction;
  26681. var CircleEase = (function (_super) {
  26682. __extends(CircleEase, _super);
  26683. function CircleEase() {
  26684. _super.apply(this, arguments);
  26685. }
  26686. CircleEase.prototype.easeInCore = function (gradient) {
  26687. gradient = Math.max(0, Math.min(1, gradient));
  26688. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  26689. };
  26690. return CircleEase;
  26691. })(EasingFunction);
  26692. BABYLON.CircleEase = CircleEase;
  26693. var BackEase = (function (_super) {
  26694. __extends(BackEase, _super);
  26695. function BackEase(amplitude) {
  26696. if (amplitude === void 0) { amplitude = 1; }
  26697. _super.call(this);
  26698. this.amplitude = amplitude;
  26699. }
  26700. BackEase.prototype.easeInCore = function (gradient) {
  26701. var num = Math.max(0, this.amplitude);
  26702. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  26703. };
  26704. return BackEase;
  26705. })(EasingFunction);
  26706. BABYLON.BackEase = BackEase;
  26707. var BounceEase = (function (_super) {
  26708. __extends(BounceEase, _super);
  26709. function BounceEase(bounces, bounciness) {
  26710. if (bounces === void 0) { bounces = 3; }
  26711. if (bounciness === void 0) { bounciness = 2; }
  26712. _super.call(this);
  26713. this.bounces = bounces;
  26714. this.bounciness = bounciness;
  26715. }
  26716. BounceEase.prototype.easeInCore = function (gradient) {
  26717. var y = Math.max(0.0, this.bounces);
  26718. var bounciness = this.bounciness;
  26719. if (bounciness <= 1.0) {
  26720. bounciness = 1.001;
  26721. }
  26722. var num9 = Math.pow(bounciness, y);
  26723. var num5 = 1.0 - bounciness;
  26724. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  26725. var num15 = gradient * num4;
  26726. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  26727. var num3 = Math.floor(num65);
  26728. var num13 = num3 + 1.0;
  26729. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  26730. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  26731. var num7 = (num8 + num12) * 0.5;
  26732. var num6 = gradient - num7;
  26733. var num2 = num7 - num8;
  26734. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  26735. };
  26736. return BounceEase;
  26737. })(EasingFunction);
  26738. BABYLON.BounceEase = BounceEase;
  26739. var CubicEase = (function (_super) {
  26740. __extends(CubicEase, _super);
  26741. function CubicEase() {
  26742. _super.apply(this, arguments);
  26743. }
  26744. CubicEase.prototype.easeInCore = function (gradient) {
  26745. return (gradient * gradient * gradient);
  26746. };
  26747. return CubicEase;
  26748. })(EasingFunction);
  26749. BABYLON.CubicEase = CubicEase;
  26750. var ElasticEase = (function (_super) {
  26751. __extends(ElasticEase, _super);
  26752. function ElasticEase(oscillations, springiness) {
  26753. if (oscillations === void 0) { oscillations = 3; }
  26754. if (springiness === void 0) { springiness = 3; }
  26755. _super.call(this);
  26756. this.oscillations = oscillations;
  26757. this.springiness = springiness;
  26758. }
  26759. ElasticEase.prototype.easeInCore = function (gradient) {
  26760. var num2;
  26761. var num3 = Math.max(0.0, this.oscillations);
  26762. var num = Math.max(0.0, this.springiness);
  26763. if (num == 0) {
  26764. num2 = gradient;
  26765. }
  26766. else {
  26767. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26768. }
  26769. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26770. };
  26771. return ElasticEase;
  26772. })(EasingFunction);
  26773. BABYLON.ElasticEase = ElasticEase;
  26774. var ExponentialEase = (function (_super) {
  26775. __extends(ExponentialEase, _super);
  26776. function ExponentialEase(exponent) {
  26777. if (exponent === void 0) { exponent = 2; }
  26778. _super.call(this);
  26779. this.exponent = exponent;
  26780. }
  26781. ExponentialEase.prototype.easeInCore = function (gradient) {
  26782. if (this.exponent <= 0) {
  26783. return gradient;
  26784. }
  26785. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26786. };
  26787. return ExponentialEase;
  26788. })(EasingFunction);
  26789. BABYLON.ExponentialEase = ExponentialEase;
  26790. var PowerEase = (function (_super) {
  26791. __extends(PowerEase, _super);
  26792. function PowerEase(power) {
  26793. if (power === void 0) { power = 2; }
  26794. _super.call(this);
  26795. this.power = power;
  26796. }
  26797. PowerEase.prototype.easeInCore = function (gradient) {
  26798. var y = Math.max(0.0, this.power);
  26799. return Math.pow(gradient, y);
  26800. };
  26801. return PowerEase;
  26802. })(EasingFunction);
  26803. BABYLON.PowerEase = PowerEase;
  26804. var QuadraticEase = (function (_super) {
  26805. __extends(QuadraticEase, _super);
  26806. function QuadraticEase() {
  26807. _super.apply(this, arguments);
  26808. }
  26809. QuadraticEase.prototype.easeInCore = function (gradient) {
  26810. return (gradient * gradient);
  26811. };
  26812. return QuadraticEase;
  26813. })(EasingFunction);
  26814. BABYLON.QuadraticEase = QuadraticEase;
  26815. var QuarticEase = (function (_super) {
  26816. __extends(QuarticEase, _super);
  26817. function QuarticEase() {
  26818. _super.apply(this, arguments);
  26819. }
  26820. QuarticEase.prototype.easeInCore = function (gradient) {
  26821. return (gradient * gradient * gradient * gradient);
  26822. };
  26823. return QuarticEase;
  26824. })(EasingFunction);
  26825. BABYLON.QuarticEase = QuarticEase;
  26826. var QuinticEase = (function (_super) {
  26827. __extends(QuinticEase, _super);
  26828. function QuinticEase() {
  26829. _super.apply(this, arguments);
  26830. }
  26831. QuinticEase.prototype.easeInCore = function (gradient) {
  26832. return (gradient * gradient * gradient * gradient * gradient);
  26833. };
  26834. return QuinticEase;
  26835. })(EasingFunction);
  26836. BABYLON.QuinticEase = QuinticEase;
  26837. var SineEase = (function (_super) {
  26838. __extends(SineEase, _super);
  26839. function SineEase() {
  26840. _super.apply(this, arguments);
  26841. }
  26842. SineEase.prototype.easeInCore = function (gradient) {
  26843. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26844. };
  26845. return SineEase;
  26846. })(EasingFunction);
  26847. BABYLON.SineEase = SineEase;
  26848. var BezierCurveEase = (function (_super) {
  26849. __extends(BezierCurveEase, _super);
  26850. function BezierCurveEase(x1, y1, x2, y2) {
  26851. if (x1 === void 0) { x1 = 0; }
  26852. if (y1 === void 0) { y1 = 0; }
  26853. if (x2 === void 0) { x2 = 1; }
  26854. if (y2 === void 0) { y2 = 1; }
  26855. _super.call(this);
  26856. this.x1 = x1;
  26857. this.y1 = y1;
  26858. this.x2 = x2;
  26859. this.y2 = y2;
  26860. }
  26861. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26862. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26863. };
  26864. return BezierCurveEase;
  26865. })(EasingFunction);
  26866. BABYLON.BezierCurveEase = BezierCurveEase;
  26867. })(BABYLON || (BABYLON = {}));
  26868. var BABYLON;
  26869. (function (BABYLON) {
  26870. var Bone = (function (_super) {
  26871. __extends(Bone, _super);
  26872. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26873. _super.call(this, name, skeleton.getScene());
  26874. this.name = name;
  26875. this.children = new Array();
  26876. this.animations = new Array();
  26877. this._worldTransform = new BABYLON.Matrix();
  26878. this._absoluteTransform = new BABYLON.Matrix();
  26879. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26880. this._skeleton = skeleton;
  26881. this._matrix = matrix;
  26882. this._baseMatrix = matrix;
  26883. this._restPose = restPose ? restPose : matrix.clone();
  26884. skeleton.bones.push(this);
  26885. if (parentBone) {
  26886. this._parent = parentBone;
  26887. parentBone.children.push(this);
  26888. }
  26889. else {
  26890. this._parent = null;
  26891. }
  26892. this._updateDifferenceMatrix();
  26893. }
  26894. // Members
  26895. Bone.prototype.getParent = function () {
  26896. return this._parent;
  26897. };
  26898. Bone.prototype.getLocalMatrix = function () {
  26899. return this._matrix;
  26900. };
  26901. Bone.prototype.getBaseMatrix = function () {
  26902. return this._baseMatrix;
  26903. };
  26904. Bone.prototype.getRestPose = function () {
  26905. return this._restPose;
  26906. };
  26907. Bone.prototype.returnToRest = function () {
  26908. this.updateMatrix(this._restPose.clone());
  26909. };
  26910. Bone.prototype.getWorldMatrix = function () {
  26911. return this._worldTransform;
  26912. };
  26913. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26914. return this._invertedAbsoluteTransform;
  26915. };
  26916. Bone.prototype.getAbsoluteTransform = function () {
  26917. return this._absoluteTransform;
  26918. };
  26919. // Methods
  26920. Bone.prototype.updateMatrix = function (matrix) {
  26921. this._baseMatrix = matrix.clone();
  26922. this._matrix = matrix.clone();
  26923. this._skeleton._markAsDirty();
  26924. this._updateDifferenceMatrix();
  26925. };
  26926. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26927. if (!rootMatrix) {
  26928. rootMatrix = this._baseMatrix;
  26929. }
  26930. if (this._parent) {
  26931. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26932. }
  26933. else {
  26934. this._absoluteTransform.copyFrom(rootMatrix);
  26935. }
  26936. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26937. for (var index = 0; index < this.children.length; index++) {
  26938. this.children[index]._updateDifferenceMatrix();
  26939. }
  26940. };
  26941. Bone.prototype.markAsDirty = function () {
  26942. this._currentRenderId++;
  26943. this._skeleton._markAsDirty();
  26944. };
  26945. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26946. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26947. // all animation may be coming from a library skeleton, so may need to create animation
  26948. if (this.animations.length === 0) {
  26949. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26950. this.animations[0].setKeys([]);
  26951. }
  26952. // get animation info / verify there is such a range from the source bone
  26953. var sourceRange = source.animations[0].getRange(rangeName);
  26954. if (!sourceRange) {
  26955. return false;
  26956. }
  26957. var from = sourceRange.from;
  26958. var to = sourceRange.to;
  26959. var sourceKeys = source.animations[0].getKeys();
  26960. // rescaling prep
  26961. var sourceBoneLength = source.length;
  26962. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26963. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26964. var destKeys = this.animations[0].getKeys();
  26965. // loop vars declaration / initialization
  26966. var orig;
  26967. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26968. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26969. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26970. var mat;
  26971. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26972. orig = sourceKeys[key];
  26973. if (orig.frame >= from && orig.frame <= to) {
  26974. if (scalingReqd) {
  26975. orig.value.decompose(origScale, origRotation, origTranslation);
  26976. origTranslation.scaleInPlace(ratio);
  26977. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26978. }
  26979. else {
  26980. mat = orig.value;
  26981. }
  26982. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26983. }
  26984. }
  26985. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26986. return true;
  26987. };
  26988. return Bone;
  26989. })(BABYLON.Node);
  26990. BABYLON.Bone = Bone;
  26991. })(BABYLON || (BABYLON = {}));
  26992. var BABYLON;
  26993. (function (BABYLON) {
  26994. var Skeleton = (function () {
  26995. function Skeleton(name, id, scene) {
  26996. this.name = name;
  26997. this.id = id;
  26998. this.bones = new Array();
  26999. this.needInitialSkinMatrix = false;
  27000. this._isDirty = true;
  27001. this._meshesWithPoseMatrix = new Array();
  27002. this._identity = BABYLON.Matrix.Identity();
  27003. this._ranges = {};
  27004. this.bones = [];
  27005. this._scene = scene;
  27006. scene.skeletons.push(this);
  27007. //make sure it will recalculate the matrix next time prepare is called.
  27008. this._isDirty = true;
  27009. }
  27010. // Members
  27011. Skeleton.prototype.getTransformMatrices = function (mesh) {
  27012. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  27013. return mesh._bonesTransformMatrices;
  27014. }
  27015. return this._transformMatrices;
  27016. };
  27017. Skeleton.prototype.getScene = function () {
  27018. return this._scene;
  27019. };
  27020. // Methods
  27021. /**
  27022. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27023. */
  27024. Skeleton.prototype.toString = function (fullDetails) {
  27025. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  27026. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27027. if (fullDetails) {
  27028. ret += ", Ranges: {";
  27029. var first = true;
  27030. for (var name_1 in this._ranges) {
  27031. if (first) {
  27032. ret += ", ";
  27033. first = false;
  27034. }
  27035. ret += name_1;
  27036. }
  27037. ret += "}";
  27038. }
  27039. return ret;
  27040. };
  27041. /**
  27042. * Get bone's index searching by name
  27043. * @param {string} name is bone's name to search for
  27044. * @return {number} Indice of the bone. Returns -1 if not found
  27045. */
  27046. Skeleton.prototype.getBoneIndexByName = function (name) {
  27047. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  27048. if (this.bones[boneIndex].name === name) {
  27049. return boneIndex;
  27050. }
  27051. }
  27052. return -1;
  27053. };
  27054. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  27055. // check name not already in use
  27056. if (!this._ranges[name]) {
  27057. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  27058. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27059. if (this.bones[i].animations[0]) {
  27060. this.bones[i].animations[0].createRange(name, from, to);
  27061. }
  27062. }
  27063. }
  27064. };
  27065. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  27066. if (deleteFrames === void 0) { deleteFrames = true; }
  27067. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27068. if (this.bones[i].animations[0]) {
  27069. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  27070. }
  27071. }
  27072. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27073. };
  27074. Skeleton.prototype.getAnimationRange = function (name) {
  27075. return this._ranges[name];
  27076. };
  27077. /**
  27078. * Returns as an Array, all AnimationRanges defined on this skeleton
  27079. */
  27080. Skeleton.prototype.getAnimationRanges = function () {
  27081. var animationRanges = [];
  27082. var name;
  27083. var i = 0;
  27084. for (name in this._ranges) {
  27085. animationRanges[i] = this._ranges[name];
  27086. i++;
  27087. }
  27088. return animationRanges;
  27089. };
  27090. /**
  27091. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  27092. */
  27093. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  27094. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  27095. if (this._ranges[name] || !source.getAnimationRange(name)) {
  27096. return false;
  27097. }
  27098. var ret = true;
  27099. var frameOffset = this._getHighestAnimationFrame() + 1;
  27100. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  27101. var boneDict = {};
  27102. var sourceBones = source.bones;
  27103. var nBones;
  27104. var i;
  27105. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  27106. boneDict[sourceBones[i].name] = sourceBones[i];
  27107. }
  27108. if (this.bones.length !== sourceBones.length) {
  27109. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  27110. ret = false;
  27111. }
  27112. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  27113. var boneName = this.bones[i].name;
  27114. var sourceBone = boneDict[boneName];
  27115. if (sourceBone) {
  27116. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  27117. }
  27118. else {
  27119. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  27120. ret = false;
  27121. }
  27122. }
  27123. // do not call createAnimationRange(), since it also is done to bones, which was already done
  27124. var range = source.getAnimationRange(name);
  27125. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  27126. return ret;
  27127. };
  27128. Skeleton.prototype.returnToRest = function () {
  27129. for (var index = 0; index < this.bones.length; index++) {
  27130. this.bones[index].returnToRest();
  27131. }
  27132. };
  27133. Skeleton.prototype._getHighestAnimationFrame = function () {
  27134. var ret = 0;
  27135. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  27136. if (this.bones[i].animations[0]) {
  27137. var highest = this.bones[i].animations[0].getHighestFrame();
  27138. if (ret < highest) {
  27139. ret = highest;
  27140. }
  27141. }
  27142. }
  27143. return ret;
  27144. };
  27145. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  27146. var range = this.getAnimationRange(name);
  27147. if (!range) {
  27148. return null;
  27149. }
  27150. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  27151. };
  27152. Skeleton.prototype._markAsDirty = function () {
  27153. this._isDirty = true;
  27154. };
  27155. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  27156. this._meshesWithPoseMatrix.push(mesh);
  27157. };
  27158. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  27159. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  27160. if (index > -1) {
  27161. this._meshesWithPoseMatrix.splice(index, 1);
  27162. }
  27163. };
  27164. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  27165. for (var index = 0; index < this.bones.length; index++) {
  27166. var bone = this.bones[index];
  27167. var parentBone = bone.getParent();
  27168. if (parentBone) {
  27169. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  27170. }
  27171. else {
  27172. if (initialSkinMatrix) {
  27173. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  27174. }
  27175. else {
  27176. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  27177. }
  27178. }
  27179. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  27180. }
  27181. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  27182. };
  27183. Skeleton.prototype.prepare = function () {
  27184. if (!this._isDirty) {
  27185. return;
  27186. }
  27187. if (this.needInitialSkinMatrix) {
  27188. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  27189. var mesh = this._meshesWithPoseMatrix[index];
  27190. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  27191. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27192. }
  27193. var poseMatrix = mesh.getPoseMatrix();
  27194. // Prepare bones
  27195. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  27196. var bone = this.bones[boneIndex];
  27197. if (!bone.getParent()) {
  27198. var matrix = bone.getBaseMatrix();
  27199. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  27200. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  27201. }
  27202. }
  27203. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  27204. }
  27205. }
  27206. else {
  27207. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  27208. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  27209. }
  27210. this._computeTransformMatrices(this._transformMatrices, null);
  27211. }
  27212. this._isDirty = false;
  27213. this._scene._activeBones += this.bones.length;
  27214. };
  27215. Skeleton.prototype.getAnimatables = function () {
  27216. if (!this._animatables || this._animatables.length !== this.bones.length) {
  27217. this._animatables = [];
  27218. for (var index = 0; index < this.bones.length; index++) {
  27219. this._animatables.push(this.bones[index]);
  27220. }
  27221. }
  27222. return this._animatables;
  27223. };
  27224. Skeleton.prototype.clone = function (name, id) {
  27225. var result = new Skeleton(name, id || name, this._scene);
  27226. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27227. for (var index = 0; index < this.bones.length; index++) {
  27228. var source = this.bones[index];
  27229. var parentBone = null;
  27230. if (source.getParent()) {
  27231. var parentIndex = this.bones.indexOf(source.getParent());
  27232. parentBone = result.bones[parentIndex];
  27233. }
  27234. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  27235. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  27236. }
  27237. if (this._ranges) {
  27238. result._ranges = {};
  27239. for (var rangeName in this._ranges) {
  27240. result._ranges[rangeName] = this._ranges[rangeName].clone();
  27241. }
  27242. }
  27243. this._isDirty = true;
  27244. return result;
  27245. };
  27246. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  27247. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  27248. this.bones.forEach(function (bone) {
  27249. bone.animations.forEach(function (animation) {
  27250. animation.enableBlending = true;
  27251. animation.blendingSpeed = blendingSpeed;
  27252. });
  27253. });
  27254. };
  27255. Skeleton.prototype.dispose = function () {
  27256. this._meshesWithPoseMatrix = [];
  27257. // Animations
  27258. this.getScene().stopAnimation(this);
  27259. // Remove from scene
  27260. this.getScene().removeSkeleton(this);
  27261. };
  27262. Skeleton.prototype.serialize = function () {
  27263. var serializationObject = {};
  27264. serializationObject.name = this.name;
  27265. serializationObject.id = this.id;
  27266. serializationObject.bones = [];
  27267. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  27268. for (var index = 0; index < this.bones.length; index++) {
  27269. var bone = this.bones[index];
  27270. var serializedBone = {
  27271. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  27272. name: bone.name,
  27273. matrix: bone.getLocalMatrix().toArray(),
  27274. rest: bone.getRestPose().toArray()
  27275. };
  27276. serializationObject.bones.push(serializedBone);
  27277. if (bone.length) {
  27278. serializedBone.length = bone.length;
  27279. }
  27280. if (bone.animations && bone.animations.length > 0) {
  27281. serializedBone.animation = bone.animations[0].serialize();
  27282. }
  27283. serializationObject.ranges = [];
  27284. for (var name in this._ranges) {
  27285. var range = {};
  27286. range.name = name;
  27287. range.from = this._ranges[name].from;
  27288. range.to = this._ranges[name].to;
  27289. serializationObject.ranges.push(range);
  27290. }
  27291. }
  27292. return serializationObject;
  27293. };
  27294. Skeleton.Parse = function (parsedSkeleton, scene) {
  27295. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  27296. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  27297. var index;
  27298. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  27299. var parsedBone = parsedSkeleton.bones[index];
  27300. var parentBone = null;
  27301. if (parsedBone.parentBoneIndex > -1) {
  27302. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  27303. }
  27304. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  27305. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  27306. if (parsedBone.length) {
  27307. bone.length = parsedBone.length;
  27308. }
  27309. if (parsedBone.animation) {
  27310. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  27311. }
  27312. }
  27313. // placed after bones, so createAnimationRange can cascade down
  27314. if (parsedSkeleton.ranges) {
  27315. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  27316. var data = parsedSkeleton.ranges[index];
  27317. skeleton.createAnimationRange(data.name, data.from, data.to);
  27318. }
  27319. }
  27320. return skeleton;
  27321. };
  27322. return Skeleton;
  27323. })();
  27324. BABYLON.Skeleton = Skeleton;
  27325. })(BABYLON || (BABYLON = {}));
  27326. var BABYLON;
  27327. (function (BABYLON) {
  27328. var PostProcess = (function () {
  27329. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  27330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  27331. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27332. this.name = name;
  27333. this.width = -1;
  27334. this.height = -1;
  27335. /*
  27336. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  27337. Can only be used on a single postprocess or on the last one of a chain.
  27338. */
  27339. this.enablePixelPerfectMode = false;
  27340. this._reusable = false;
  27341. this._textures = new BABYLON.SmartArray(2);
  27342. this._currentRenderTextureInd = 0;
  27343. this._scaleRatio = new BABYLON.Vector2(1, 1);
  27344. // Events
  27345. /**
  27346. * An event triggered when the postprocess is activated.
  27347. * @type {BABYLON.Observable}
  27348. */
  27349. this.onActivateObservable = new BABYLON.Observable();
  27350. /**
  27351. * An event triggered when the postprocess changes its size.
  27352. * @type {BABYLON.Observable}
  27353. */
  27354. this.onSizeChangedObservable = new BABYLON.Observable();
  27355. /**
  27356. * An event triggered when the postprocess applies its effect.
  27357. * @type {BABYLON.Observable}
  27358. */
  27359. this.onApplyObservable = new BABYLON.Observable();
  27360. /**
  27361. * An event triggered before rendering the postprocess
  27362. * @type {BABYLON.Observable}
  27363. */
  27364. this.onBeforeRenderObservable = new BABYLON.Observable();
  27365. /**
  27366. * An event triggered after rendering the postprocess
  27367. * @type {BABYLON.Observable}
  27368. */
  27369. this.onAfterRenderObservable = new BABYLON.Observable();
  27370. if (camera != null) {
  27371. this._camera = camera;
  27372. this._scene = camera.getScene();
  27373. camera.attachPostProcess(this);
  27374. this._engine = this._scene.getEngine();
  27375. }
  27376. else {
  27377. this._engine = engine;
  27378. }
  27379. this._renderRatio = ratio;
  27380. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  27381. this._reusable = reusable || false;
  27382. this._textureType = textureType;
  27383. this._samplers = samplers || [];
  27384. this._samplers.push("textureSampler");
  27385. this._fragmentUrl = fragmentUrl;
  27386. this._parameters = parameters || [];
  27387. this._parameters.push("scale");
  27388. this.updateEffect(defines);
  27389. }
  27390. Object.defineProperty(PostProcess.prototype, "onActivate", {
  27391. set: function (callback) {
  27392. if (this._onActivateObserver) {
  27393. this.onActivateObservable.remove(this._onActivateObserver);
  27394. }
  27395. this._onActivateObserver = this.onActivateObservable.add(callback);
  27396. },
  27397. enumerable: true,
  27398. configurable: true
  27399. });
  27400. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  27401. set: function (callback) {
  27402. if (this._onSizeChangedObserver) {
  27403. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  27404. }
  27405. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  27406. },
  27407. enumerable: true,
  27408. configurable: true
  27409. });
  27410. Object.defineProperty(PostProcess.prototype, "onApply", {
  27411. set: function (callback) {
  27412. if (this._onApplyObserver) {
  27413. this.onApplyObservable.remove(this._onApplyObserver);
  27414. }
  27415. this._onApplyObserver = this.onApplyObservable.add(callback);
  27416. },
  27417. enumerable: true,
  27418. configurable: true
  27419. });
  27420. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  27421. set: function (callback) {
  27422. if (this._onBeforeRenderObserver) {
  27423. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27424. }
  27425. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27426. },
  27427. enumerable: true,
  27428. configurable: true
  27429. });
  27430. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  27431. set: function (callback) {
  27432. if (this._onAfterRenderObserver) {
  27433. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27434. }
  27435. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27436. },
  27437. enumerable: true,
  27438. configurable: true
  27439. });
  27440. PostProcess.prototype.updateEffect = function (defines) {
  27441. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  27442. };
  27443. PostProcess.prototype.isReusable = function () {
  27444. return this._reusable;
  27445. };
  27446. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  27447. PostProcess.prototype.markTextureDirty = function () {
  27448. this.width = -1;
  27449. };
  27450. PostProcess.prototype.activate = function (camera, sourceTexture) {
  27451. camera = camera || this._camera;
  27452. var scene = camera.getScene();
  27453. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  27454. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  27455. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  27456. var desiredWidth = this._renderRatio.width || requiredWidth;
  27457. var desiredHeight = this._renderRatio.height || requiredHeight;
  27458. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27459. if (!this._renderRatio.width) {
  27460. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  27461. }
  27462. if (!this._renderRatio.height) {
  27463. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  27464. }
  27465. }
  27466. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  27467. if (this._textures.length > 0) {
  27468. for (var i = 0; i < this._textures.length; i++) {
  27469. this._engine._releaseTexture(this._textures.data[i]);
  27470. }
  27471. this._textures.reset();
  27472. }
  27473. this.width = desiredWidth;
  27474. this.height = desiredHeight;
  27475. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  27476. if (this._reusable) {
  27477. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === 0, samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  27478. }
  27479. this.onSizeChangedObservable.notifyObservers(this);
  27480. }
  27481. if (this.enablePixelPerfectMode) {
  27482. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  27483. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  27484. }
  27485. else {
  27486. this._scaleRatio.copyFromFloats(1, 1);
  27487. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  27488. }
  27489. this.onActivateObservable.notifyObservers(camera);
  27490. // Clear
  27491. if (this.clearColor) {
  27492. this._engine.clear(this.clearColor, true, true);
  27493. }
  27494. else {
  27495. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  27496. }
  27497. if (this._reusable) {
  27498. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  27499. }
  27500. };
  27501. Object.defineProperty(PostProcess.prototype, "isSupported", {
  27502. get: function () {
  27503. return this._effect.isSupported;
  27504. },
  27505. enumerable: true,
  27506. configurable: true
  27507. });
  27508. PostProcess.prototype.apply = function () {
  27509. // Check
  27510. if (!this._effect.isReady())
  27511. return null;
  27512. // States
  27513. this._engine.enableEffect(this._effect);
  27514. this._engine.setState(false);
  27515. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27516. this._engine.setDepthBuffer(false);
  27517. this._engine.setDepthWrite(false);
  27518. // Texture
  27519. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  27520. // Parameters
  27521. this._effect.setVector2("scale", this._scaleRatio);
  27522. this.onApplyObservable.notifyObservers(this._effect);
  27523. return this._effect;
  27524. };
  27525. PostProcess.prototype.dispose = function (camera) {
  27526. camera = camera || this._camera;
  27527. if (this._textures.length > 0) {
  27528. for (var i = 0; i < this._textures.length; i++) {
  27529. this._engine._releaseTexture(this._textures.data[i]);
  27530. }
  27531. this._textures.reset();
  27532. }
  27533. if (!camera) {
  27534. return;
  27535. }
  27536. camera.detachPostProcess(this);
  27537. var index = camera._postProcesses.indexOf(this);
  27538. if (index === 0 && camera._postProcesses.length > 0) {
  27539. this._camera._postProcesses[0].markTextureDirty();
  27540. }
  27541. this.onActivateObservable.clear();
  27542. this.onAfterRenderObservable.clear();
  27543. this.onApplyObservable.clear();
  27544. this.onBeforeRenderObservable.clear();
  27545. this.onSizeChangedObservable.clear();
  27546. };
  27547. return PostProcess;
  27548. })();
  27549. BABYLON.PostProcess = PostProcess;
  27550. })(BABYLON || (BABYLON = {}));
  27551. var BABYLON;
  27552. (function (BABYLON) {
  27553. var PostProcessManager = (function () {
  27554. function PostProcessManager(scene) {
  27555. this._vertexDeclaration = [2];
  27556. this._vertexStrideSize = 2 * 4;
  27557. this._scene = scene;
  27558. }
  27559. PostProcessManager.prototype._prepareBuffers = function () {
  27560. if (this._vertexBuffer) {
  27561. return;
  27562. }
  27563. // VBO
  27564. var vertices = [];
  27565. vertices.push(1, 1);
  27566. vertices.push(-1, 1);
  27567. vertices.push(-1, -1);
  27568. vertices.push(1, -1);
  27569. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  27570. // Indices
  27571. var indices = [];
  27572. indices.push(0);
  27573. indices.push(1);
  27574. indices.push(2);
  27575. indices.push(0);
  27576. indices.push(2);
  27577. indices.push(3);
  27578. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27579. };
  27580. // Methods
  27581. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27582. var postProcesses = this._scene.activeCamera._postProcesses;
  27583. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27584. return false;
  27585. }
  27586. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27587. return true;
  27588. };
  27589. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27590. var engine = this._scene.getEngine();
  27591. for (var index = 0; index < postProcesses.length; index++) {
  27592. if (index < postProcesses.length - 1) {
  27593. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27594. }
  27595. else {
  27596. if (targetTexture) {
  27597. engine.bindFramebuffer(targetTexture);
  27598. }
  27599. else {
  27600. engine.restoreDefaultFramebuffer();
  27601. }
  27602. }
  27603. var pp = postProcesses[index];
  27604. var effect = pp.apply();
  27605. if (effect) {
  27606. pp.onBeforeRenderObservable.notifyObservers(effect);
  27607. // VBOs
  27608. this._prepareBuffers();
  27609. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27610. // Draw order
  27611. engine.draw(true, 0, 6);
  27612. pp.onAfterRenderObservable.notifyObservers(effect);
  27613. }
  27614. }
  27615. // Restore depth buffer
  27616. engine.setDepthBuffer(true);
  27617. engine.setDepthWrite(true);
  27618. };
  27619. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27620. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27621. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27622. return;
  27623. }
  27624. var engine = this._scene.getEngine();
  27625. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27626. if (index < len - 1) {
  27627. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27628. }
  27629. else {
  27630. if (targetTexture) {
  27631. engine.bindFramebuffer(targetTexture, faceIndex);
  27632. }
  27633. else {
  27634. engine.restoreDefaultFramebuffer();
  27635. }
  27636. }
  27637. if (doNotPresent) {
  27638. break;
  27639. }
  27640. var pp = postProcesses[index];
  27641. var effect = pp.apply();
  27642. if (effect) {
  27643. pp.onBeforeRenderObservable.notifyObservers(effect);
  27644. // VBOs
  27645. this._prepareBuffers();
  27646. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27647. // Draw order
  27648. engine.draw(true, 0, 6);
  27649. pp.onAfterRenderObservable.notifyObservers(effect);
  27650. }
  27651. }
  27652. // Restore depth buffer
  27653. engine.setDepthBuffer(true);
  27654. engine.setDepthWrite(true);
  27655. };
  27656. PostProcessManager.prototype.dispose = function () {
  27657. if (this._vertexBuffer) {
  27658. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  27659. this._vertexBuffer = null;
  27660. }
  27661. if (this._indexBuffer) {
  27662. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27663. this._indexBuffer = null;
  27664. }
  27665. };
  27666. return PostProcessManager;
  27667. })();
  27668. BABYLON.PostProcessManager = PostProcessManager;
  27669. })(BABYLON || (BABYLON = {}));
  27670. var BABYLON;
  27671. (function (BABYLON) {
  27672. var PassPostProcess = (function (_super) {
  27673. __extends(PassPostProcess, _super);
  27674. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27675. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  27676. }
  27677. return PassPostProcess;
  27678. })(BABYLON.PostProcess);
  27679. BABYLON.PassPostProcess = PassPostProcess;
  27680. })(BABYLON || (BABYLON = {}));
  27681. var BABYLON;
  27682. (function (BABYLON) {
  27683. /**
  27684. * This is a holder class for the physics joint created by the physics plugin.
  27685. * It holds a set of functions to control the underlying joint.
  27686. */
  27687. var PhysicsJoint = (function () {
  27688. function PhysicsJoint(type, jointData) {
  27689. this.type = type;
  27690. this.jointData = jointData;
  27691. jointData.nativeParams = jointData.nativeParams || {};
  27692. }
  27693. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  27694. get: function () {
  27695. return this._physicsJoint;
  27696. },
  27697. set: function (newJoint) {
  27698. if (this._physicsJoint) {
  27699. }
  27700. this._physicsJoint = newJoint;
  27701. },
  27702. enumerable: true,
  27703. configurable: true
  27704. });
  27705. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  27706. set: function (physicsPlugin) {
  27707. this._physicsPlugin = physicsPlugin;
  27708. },
  27709. enumerable: true,
  27710. configurable: true
  27711. });
  27712. /**
  27713. * Execute a function that is physics-plugin specific.
  27714. * @param {Function} func the function that will be executed.
  27715. * It accepts two parameters: the physics world and the physics joint.
  27716. */
  27717. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  27718. func(this._physicsPlugin.world, this._physicsJoint);
  27719. };
  27720. //TODO check if the native joints are the same
  27721. //Joint Types
  27722. PhysicsJoint.DistanceJoint = 0;
  27723. PhysicsJoint.HingeJoint = 1;
  27724. PhysicsJoint.BallAndSocketJoint = 2;
  27725. PhysicsJoint.WheelJoint = 3;
  27726. PhysicsJoint.SliderJoint = 4;
  27727. //OIMO
  27728. PhysicsJoint.PrismaticJoint = 5;
  27729. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  27730. PhysicsJoint.UniversalJoint = 6;
  27731. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  27732. //Cannon
  27733. //Similar to a Ball-Joint. Different in params
  27734. PhysicsJoint.PointToPointJoint = 8;
  27735. //Cannon only at the moment
  27736. PhysicsJoint.SpringJoint = 9;
  27737. return PhysicsJoint;
  27738. })();
  27739. BABYLON.PhysicsJoint = PhysicsJoint;
  27740. /**
  27741. * A class representing a physics distance joint.
  27742. */
  27743. var DistanceJoint = (function (_super) {
  27744. __extends(DistanceJoint, _super);
  27745. function DistanceJoint(jointData) {
  27746. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  27747. }
  27748. /**
  27749. * Update the predefined distance.
  27750. */
  27751. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  27752. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  27753. };
  27754. return DistanceJoint;
  27755. })(PhysicsJoint);
  27756. BABYLON.DistanceJoint = DistanceJoint;
  27757. var MotorEnabledJoint = (function (_super) {
  27758. __extends(MotorEnabledJoint, _super);
  27759. function MotorEnabledJoint(type, jointData) {
  27760. _super.call(this, type, jointData);
  27761. }
  27762. /**
  27763. * Set the motor values.
  27764. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27765. * @param {number} force the force to apply
  27766. * @param {number} maxForce max force for this motor.
  27767. */
  27768. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  27769. this._physicsPlugin.setMotor(this, force, maxForce);
  27770. };
  27771. /**
  27772. * Set the motor's limits.
  27773. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27774. */
  27775. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27776. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27777. };
  27778. return MotorEnabledJoint;
  27779. })(PhysicsJoint);
  27780. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  27781. /**
  27782. * This class represents a single hinge physics joint
  27783. */
  27784. var HingeJoint = (function (_super) {
  27785. __extends(HingeJoint, _super);
  27786. function HingeJoint(jointData) {
  27787. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  27788. }
  27789. /**
  27790. * Set the motor values.
  27791. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27792. * @param {number} force the force to apply
  27793. * @param {number} maxForce max force for this motor.
  27794. */
  27795. HingeJoint.prototype.setMotor = function (force, maxForce) {
  27796. this._physicsPlugin.setMotor(this, force, maxForce);
  27797. };
  27798. /**
  27799. * Set the motor's limits.
  27800. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27801. */
  27802. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27803. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27804. };
  27805. return HingeJoint;
  27806. })(MotorEnabledJoint);
  27807. BABYLON.HingeJoint = HingeJoint;
  27808. /**
  27809. * This class represents a dual hinge physics joint (same as wheel joint)
  27810. */
  27811. var Hinge2Joint = (function (_super) {
  27812. __extends(Hinge2Joint, _super);
  27813. function Hinge2Joint(jointData) {
  27814. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  27815. }
  27816. /**
  27817. * Set the motor values.
  27818. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27819. * @param {number} force the force to apply
  27820. * @param {number} maxForce max force for this motor.
  27821. * @param {motorIndex} the motor's index, 0 or 1.
  27822. */
  27823. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  27824. if (motorIndex === void 0) { motorIndex = 0; }
  27825. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  27826. };
  27827. /**
  27828. * Set the motor limits.
  27829. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27830. * @param {number} upperLimit the upper limit
  27831. * @param {number} lowerLimit lower limit
  27832. * @param {motorIndex} the motor's index, 0 or 1.
  27833. */
  27834. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  27835. if (motorIndex === void 0) { motorIndex = 0; }
  27836. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  27837. };
  27838. return Hinge2Joint;
  27839. })(MotorEnabledJoint);
  27840. BABYLON.Hinge2Joint = Hinge2Joint;
  27841. })(BABYLON || (BABYLON = {}));
  27842. var BABYLON;
  27843. (function (BABYLON) {
  27844. var PhysicsImpostor = (function () {
  27845. function PhysicsImpostor(object, type, _options, _scene) {
  27846. var _this = this;
  27847. if (_options === void 0) { _options = { mass: 0 }; }
  27848. this.object = object;
  27849. this.type = type;
  27850. this._options = _options;
  27851. this._scene = _scene;
  27852. this._bodyUpdateRequired = false;
  27853. this._onBeforePhysicsStepCallbacks = new Array();
  27854. this._onAfterPhysicsStepCallbacks = new Array();
  27855. this._onPhysicsCollideCallbacks = [];
  27856. this._deltaPosition = BABYLON.Vector3.Zero();
  27857. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  27858. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  27859. /**
  27860. * this function is executed by the physics engine.
  27861. */
  27862. this.beforeStep = function () {
  27863. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  27864. //conjugate deltaRotation
  27865. if (_this._deltaRotationConjugated) {
  27866. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  27867. }
  27868. else {
  27869. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  27870. }
  27871. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  27872. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  27873. func(_this);
  27874. });
  27875. };
  27876. /**
  27877. * this function is executed by the physics engine.
  27878. */
  27879. this.afterStep = function () {
  27880. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  27881. func(_this);
  27882. });
  27883. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  27884. _this.object.position.addInPlace(_this._deltaPosition);
  27885. if (_this._deltaRotation) {
  27886. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27887. }
  27888. };
  27889. //event and body object due to cannon's event-based architecture.
  27890. this.onCollide = function (e) {
  27891. if (!_this._onPhysicsCollideCallbacks.length)
  27892. return;
  27893. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27894. if (otherImpostor) {
  27895. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27896. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27897. }).forEach(function (obj) {
  27898. obj.callback(_this, otherImpostor);
  27899. });
  27900. }
  27901. };
  27902. //sanity check!
  27903. if (!this.object) {
  27904. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27905. return;
  27906. }
  27907. //legacy support for old syntax.
  27908. if (!this._scene && object.getScene) {
  27909. this._scene = object.getScene();
  27910. }
  27911. this._physicsEngine = this._scene.getPhysicsEngine();
  27912. if (!this._physicsEngine) {
  27913. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27914. }
  27915. else {
  27916. //set the object's quaternion, if not set
  27917. if (!this.object.rotationQuaternion) {
  27918. if (this.object.rotation) {
  27919. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27920. }
  27921. else {
  27922. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27923. }
  27924. }
  27925. //default options params
  27926. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27927. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27928. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27929. this._joints = [];
  27930. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27931. if (!this.object.parent) {
  27932. this._init();
  27933. }
  27934. }
  27935. }
  27936. /**
  27937. * This function will completly initialize this impostor.
  27938. * It will create a new body - but only if this mesh has no parent.
  27939. * If it has, this impostor will not be used other than to define the impostor
  27940. * of the child mesh.
  27941. */
  27942. PhysicsImpostor.prototype._init = function () {
  27943. this._physicsEngine.removeImpostor(this);
  27944. this.physicsBody = null;
  27945. this._parent = this._parent || this._getPhysicsParent();
  27946. if (!this.parent) {
  27947. this._physicsEngine.addImpostor(this);
  27948. }
  27949. };
  27950. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27951. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27952. var parentMesh = this.object.parent;
  27953. return parentMesh.physicsImpostor;
  27954. }
  27955. return;
  27956. };
  27957. /**
  27958. * Should a new body be generated.
  27959. */
  27960. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27961. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27962. };
  27963. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27964. this.forceUpdate();
  27965. };
  27966. /**
  27967. * Force a regeneration of this or the parent's impostor's body.
  27968. * Use under cautious - This will remove all joints already implemented.
  27969. */
  27970. PhysicsImpostor.prototype.forceUpdate = function () {
  27971. this._init();
  27972. if (this.parent) {
  27973. this.parent.forceUpdate();
  27974. }
  27975. };
  27976. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27977. /*public get mesh(): AbstractMesh {
  27978. return this._mesh;
  27979. }*/
  27980. /**
  27981. * Gets the body that holds this impostor. Either its own, or its parent.
  27982. */
  27983. get: function () {
  27984. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27985. },
  27986. /**
  27987. * Set the physics body. Used mainly by the physics engine/plugin
  27988. */
  27989. set: function (physicsBody) {
  27990. if (this._physicsBody) {
  27991. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27992. }
  27993. this._physicsBody = physicsBody;
  27994. this.resetUpdateFlags();
  27995. },
  27996. enumerable: true,
  27997. configurable: true
  27998. });
  27999. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  28000. get: function () {
  28001. return this._parent;
  28002. },
  28003. enumerable: true,
  28004. configurable: true
  28005. });
  28006. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  28007. this._bodyUpdateRequired = false;
  28008. };
  28009. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  28010. if (this.object.getBoundingInfo) {
  28011. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  28012. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  28013. }
  28014. else {
  28015. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  28016. }
  28017. };
  28018. PhysicsImpostor.prototype.getObjectCenter = function () {
  28019. if (this.object.getBoundingInfo) {
  28020. return this.object.getBoundingInfo().boundingBox.center;
  28021. }
  28022. else {
  28023. return this.object.position;
  28024. }
  28025. };
  28026. /**
  28027. * Get a specific parametes from the options parameter.
  28028. */
  28029. PhysicsImpostor.prototype.getParam = function (paramName) {
  28030. return this._options[paramName];
  28031. };
  28032. /**
  28033. * Sets a specific parameter in the options given to the physics plugin
  28034. */
  28035. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  28036. this._options[paramName] = value;
  28037. this._bodyUpdateRequired = true;
  28038. };
  28039. /**
  28040. * Specifically change the body's mass option. Won't recreate the physics body object
  28041. */
  28042. PhysicsImpostor.prototype.setMass = function (mass) {
  28043. if (this.getParam("mass") !== mass) {
  28044. this.setParam("mass", mass);
  28045. }
  28046. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  28047. };
  28048. PhysicsImpostor.prototype.getLinearVelocity = function () {
  28049. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  28050. };
  28051. /**
  28052. * Set the body's linear velocity.
  28053. */
  28054. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  28055. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  28056. };
  28057. PhysicsImpostor.prototype.getAngularVelocity = function () {
  28058. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  28059. };
  28060. /**
  28061. * Set the body's linear velocity.
  28062. */
  28063. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  28064. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  28065. };
  28066. /**
  28067. * Execute a function with the physics plugin native code.
  28068. * Provide a function the will have two variables - the world object and the physics body object.
  28069. */
  28070. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  28071. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  28072. };
  28073. /**
  28074. * Register a function that will be executed before the physics world is stepping forward.
  28075. */
  28076. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  28077. this._onBeforePhysicsStepCallbacks.push(func);
  28078. };
  28079. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  28080. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  28081. if (index > -1) {
  28082. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  28083. }
  28084. else {
  28085. BABYLON.Tools.Warn("Function to remove was not found");
  28086. }
  28087. };
  28088. /**
  28089. * Register a function that will be executed after the physics step
  28090. */
  28091. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  28092. this._onAfterPhysicsStepCallbacks.push(func);
  28093. };
  28094. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  28095. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  28096. if (index > -1) {
  28097. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  28098. }
  28099. else {
  28100. BABYLON.Tools.Warn("Function to remove was not found");
  28101. }
  28102. };
  28103. /**
  28104. * register a function that will be executed when this impostor collides against a different body.
  28105. */
  28106. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  28107. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28108. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  28109. };
  28110. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  28111. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  28112. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  28113. if (index > -1) {
  28114. this._onPhysicsCollideCallbacks.splice(index, 1);
  28115. }
  28116. else {
  28117. BABYLON.Tools.Warn("Function to remove was not found");
  28118. }
  28119. };
  28120. /**
  28121. * Apply a force
  28122. */
  28123. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  28124. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  28125. };
  28126. /**
  28127. * Apply an impulse
  28128. */
  28129. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  28130. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  28131. };
  28132. /**
  28133. * A help function to create a joint.
  28134. */
  28135. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  28136. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  28137. this.addJoint(otherImpostor, joint);
  28138. };
  28139. /**
  28140. * Add a joint to this impostor with a different impostor.
  28141. */
  28142. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  28143. this._joints.push({
  28144. otherImpostor: otherImpostor,
  28145. joint: joint
  28146. });
  28147. this._physicsEngine.addJoint(this, otherImpostor, joint);
  28148. };
  28149. /**
  28150. * Will keep this body still, in a sleep mode.
  28151. */
  28152. PhysicsImpostor.prototype.sleep = function () {
  28153. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  28154. };
  28155. /**
  28156. * Wake the body up.
  28157. */
  28158. PhysicsImpostor.prototype.wakeUp = function () {
  28159. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  28160. };
  28161. PhysicsImpostor.prototype.clone = function (newObject) {
  28162. if (!newObject)
  28163. return null;
  28164. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  28165. };
  28166. PhysicsImpostor.prototype.dispose = function () {
  28167. var _this = this;
  28168. //no dispose if no physics engine is available.
  28169. if (!this._physicsEngine) {
  28170. return;
  28171. }
  28172. this._joints.forEach(function (j) {
  28173. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  28174. });
  28175. //dispose the physics body
  28176. this._physicsEngine.removeImpostor(this);
  28177. if (this.parent) {
  28178. this.parent.forceUpdate();
  28179. }
  28180. else {
  28181. }
  28182. };
  28183. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  28184. this._deltaPosition.copyFrom(position);
  28185. };
  28186. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  28187. if (!this._deltaRotation) {
  28188. this._deltaRotation = new BABYLON.Quaternion();
  28189. }
  28190. this._deltaRotation.copyFrom(rotation);
  28191. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  28192. };
  28193. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  28194. //Impostor types
  28195. PhysicsImpostor.NoImpostor = 0;
  28196. PhysicsImpostor.SphereImpostor = 1;
  28197. PhysicsImpostor.BoxImpostor = 2;
  28198. PhysicsImpostor.PlaneImpostor = 3;
  28199. PhysicsImpostor.MeshImpostor = 4;
  28200. PhysicsImpostor.CylinderImpostor = 7;
  28201. PhysicsImpostor.ParticleImpostor = 8;
  28202. PhysicsImpostor.HeightmapImpostor = 9;
  28203. return PhysicsImpostor;
  28204. })();
  28205. BABYLON.PhysicsImpostor = PhysicsImpostor;
  28206. })(BABYLON || (BABYLON = {}));
  28207. var BABYLON;
  28208. (function (BABYLON) {
  28209. var PhysicsEngine = (function () {
  28210. function PhysicsEngine(gravity, _physicsPlugin) {
  28211. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  28212. this._physicsPlugin = _physicsPlugin;
  28213. //new methods and parameters
  28214. this._impostors = [];
  28215. this._joints = [];
  28216. if (!this._physicsPlugin.isSupported()) {
  28217. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  28218. + "Please make sure it is included.");
  28219. }
  28220. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  28221. this.setGravity(gravity);
  28222. this.setTimeStep();
  28223. }
  28224. PhysicsEngine.prototype.setGravity = function (gravity) {
  28225. this.gravity = gravity;
  28226. this._physicsPlugin.setGravity(this.gravity);
  28227. };
  28228. /**
  28229. * Set the time step of the physics engine.
  28230. * default is 1/60.
  28231. * To slow it down, enter 1/600 for example.
  28232. * To speed it up, 1/30
  28233. * @param {number} newTimeStep the new timestep to apply to this world.
  28234. */
  28235. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  28236. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  28237. this._physicsPlugin.setTimeStep(newTimeStep);
  28238. };
  28239. PhysicsEngine.prototype.dispose = function () {
  28240. this._impostors.forEach(function (impostor) {
  28241. impostor.dispose();
  28242. });
  28243. this._physicsPlugin.dispose();
  28244. };
  28245. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  28246. return this._physicsPlugin.name;
  28247. };
  28248. /**
  28249. * Adding a new impostor for the impostor tracking.
  28250. * This will be done by the impostor itself.
  28251. * @param {PhysicsImpostor} impostor the impostor to add
  28252. */
  28253. PhysicsEngine.prototype.addImpostor = function (impostor) {
  28254. impostor.uniqueId = this._impostors.push(impostor);
  28255. //if no parent, generate the body
  28256. if (!impostor.parent) {
  28257. this._physicsPlugin.generatePhysicsBody(impostor);
  28258. }
  28259. };
  28260. /**
  28261. * Remove an impostor from the engine.
  28262. * This impostor and its mesh will not longer be updated by the physics engine.
  28263. * @param {PhysicsImpostor} impostor the impostor to remove
  28264. */
  28265. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  28266. var index = this._impostors.indexOf(impostor);
  28267. if (index > -1) {
  28268. var removed = this._impostors.splice(index, 1);
  28269. //Is it needed?
  28270. if (removed.length) {
  28271. //this will also remove it from the world.
  28272. removed[0].physicsBody = null;
  28273. }
  28274. }
  28275. };
  28276. /**
  28277. * Add a joint to the physics engine
  28278. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  28279. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  28280. * @param {PhysicsJoint} the joint that will connect both impostors.
  28281. */
  28282. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  28283. var impostorJoint = {
  28284. mainImpostor: mainImpostor,
  28285. connectedImpostor: connectedImpostor,
  28286. joint: joint
  28287. };
  28288. joint.physicsPlugin = this._physicsPlugin;
  28289. this._joints.push(impostorJoint);
  28290. this._physicsPlugin.generateJoint(impostorJoint);
  28291. };
  28292. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  28293. var matchingJoints = this._joints.filter(function (impostorJoint) {
  28294. return (impostorJoint.connectedImpostor === connectedImpostor
  28295. && impostorJoint.joint === joint
  28296. && impostorJoint.mainImpostor === mainImpostor);
  28297. });
  28298. if (matchingJoints.length) {
  28299. this._physicsPlugin.removeJoint(matchingJoints[0]);
  28300. }
  28301. };
  28302. /**
  28303. * Called by the scene. no need to call it.
  28304. */
  28305. PhysicsEngine.prototype._step = function (delta) {
  28306. var _this = this;
  28307. //check if any mesh has no body / requires an update
  28308. this._impostors.forEach(function (impostor) {
  28309. if (impostor.isBodyInitRequired()) {
  28310. _this._physicsPlugin.generatePhysicsBody(impostor);
  28311. }
  28312. });
  28313. if (delta > 0.1) {
  28314. delta = 0.1;
  28315. }
  28316. else if (delta <= 0) {
  28317. delta = 1.0 / 60.0;
  28318. }
  28319. this._physicsPlugin.executeStep(delta, this._impostors);
  28320. };
  28321. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  28322. return this._physicsPlugin;
  28323. };
  28324. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  28325. for (var i = 0; i < this._impostors.length; ++i) {
  28326. if (this._impostors[i].object === object) {
  28327. return this._impostors[i];
  28328. }
  28329. }
  28330. };
  28331. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  28332. for (var i = 0; i < this._impostors.length; ++i) {
  28333. if (this._impostors[i].physicsBody === body) {
  28334. return this._impostors[i];
  28335. }
  28336. }
  28337. };
  28338. // Statics, Legacy support.
  28339. /**
  28340. * @Deprecated
  28341. *
  28342. */
  28343. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  28344. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  28345. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  28346. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  28347. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  28348. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  28349. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  28350. PhysicsEngine.CapsuleImpostor = -1;
  28351. PhysicsEngine.ConeImpostor = -1;
  28352. PhysicsEngine.ConvexHullImpostor = -1;
  28353. PhysicsEngine.Epsilon = 0.001;
  28354. return PhysicsEngine;
  28355. })();
  28356. BABYLON.PhysicsEngine = PhysicsEngine;
  28357. })(BABYLON || (BABYLON = {}));
  28358. var BABYLON;
  28359. (function (BABYLON) {
  28360. var VertexData = (function () {
  28361. function VertexData() {
  28362. }
  28363. VertexData.prototype.set = function (data, kind) {
  28364. switch (kind) {
  28365. case BABYLON.VertexBuffer.PositionKind:
  28366. this.positions = data;
  28367. break;
  28368. case BABYLON.VertexBuffer.NormalKind:
  28369. this.normals = data;
  28370. break;
  28371. case BABYLON.VertexBuffer.UVKind:
  28372. this.uvs = data;
  28373. break;
  28374. case BABYLON.VertexBuffer.UV2Kind:
  28375. this.uvs2 = data;
  28376. break;
  28377. case BABYLON.VertexBuffer.UV3Kind:
  28378. this.uvs3 = data;
  28379. break;
  28380. case BABYLON.VertexBuffer.UV4Kind:
  28381. this.uvs4 = data;
  28382. break;
  28383. case BABYLON.VertexBuffer.UV5Kind:
  28384. this.uvs5 = data;
  28385. break;
  28386. case BABYLON.VertexBuffer.UV6Kind:
  28387. this.uvs6 = data;
  28388. break;
  28389. case BABYLON.VertexBuffer.ColorKind:
  28390. this.colors = data;
  28391. break;
  28392. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28393. this.matricesIndices = data;
  28394. break;
  28395. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28396. this.matricesWeights = data;
  28397. break;
  28398. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28399. this.matricesIndicesExtra = data;
  28400. break;
  28401. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28402. this.matricesWeightsExtra = data;
  28403. break;
  28404. }
  28405. };
  28406. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28407. this._applyTo(mesh, updatable);
  28408. };
  28409. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28410. this._applyTo(geometry, updatable);
  28411. };
  28412. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28413. this._update(mesh);
  28414. };
  28415. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28416. this._update(geometry);
  28417. };
  28418. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28419. if (this.positions) {
  28420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28421. }
  28422. if (this.normals) {
  28423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28424. }
  28425. if (this.uvs) {
  28426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28427. }
  28428. if (this.uvs2) {
  28429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28430. }
  28431. if (this.uvs3) {
  28432. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28433. }
  28434. if (this.uvs4) {
  28435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28436. }
  28437. if (this.uvs5) {
  28438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28439. }
  28440. if (this.uvs6) {
  28441. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28442. }
  28443. if (this.colors) {
  28444. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28445. }
  28446. if (this.matricesIndices) {
  28447. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28448. }
  28449. if (this.matricesWeights) {
  28450. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28451. }
  28452. if (this.matricesIndicesExtra) {
  28453. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28454. }
  28455. if (this.matricesWeightsExtra) {
  28456. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28457. }
  28458. if (this.indices) {
  28459. meshOrGeometry.setIndices(this.indices);
  28460. }
  28461. };
  28462. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28463. if (this.positions) {
  28464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28465. }
  28466. if (this.normals) {
  28467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28468. }
  28469. if (this.uvs) {
  28470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28471. }
  28472. if (this.uvs2) {
  28473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28474. }
  28475. if (this.uvs3) {
  28476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28477. }
  28478. if (this.uvs4) {
  28479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28480. }
  28481. if (this.uvs5) {
  28482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28483. }
  28484. if (this.uvs6) {
  28485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28486. }
  28487. if (this.colors) {
  28488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28489. }
  28490. if (this.matricesIndices) {
  28491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28492. }
  28493. if (this.matricesWeights) {
  28494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28495. }
  28496. if (this.matricesIndicesExtra) {
  28497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28498. }
  28499. if (this.matricesWeightsExtra) {
  28500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28501. }
  28502. if (this.indices) {
  28503. meshOrGeometry.setIndices(this.indices);
  28504. }
  28505. };
  28506. VertexData.prototype.transform = function (matrix) {
  28507. var transformed = BABYLON.Vector3.Zero();
  28508. var index;
  28509. if (this.positions) {
  28510. var position = BABYLON.Vector3.Zero();
  28511. for (index = 0; index < this.positions.length; index += 3) {
  28512. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28513. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28514. this.positions[index] = transformed.x;
  28515. this.positions[index + 1] = transformed.y;
  28516. this.positions[index + 2] = transformed.z;
  28517. }
  28518. }
  28519. if (this.normals) {
  28520. var normal = BABYLON.Vector3.Zero();
  28521. for (index = 0; index < this.normals.length; index += 3) {
  28522. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28523. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28524. this.normals[index] = transformed.x;
  28525. this.normals[index + 1] = transformed.y;
  28526. this.normals[index + 2] = transformed.z;
  28527. }
  28528. }
  28529. };
  28530. VertexData.prototype.merge = function (other) {
  28531. if (other.indices) {
  28532. if (!this.indices) {
  28533. this.indices = [];
  28534. }
  28535. var offset = this.positions ? this.positions.length / 3 : 0;
  28536. for (var index = 0; index < other.indices.length; index++) {
  28537. //TODO check type - if Int32Array!
  28538. this.indices.push(other.indices[index] + offset);
  28539. }
  28540. }
  28541. this.positions = this._mergeElement(this.positions, other.positions);
  28542. this.normals = this._mergeElement(this.normals, other.normals);
  28543. this.uvs = this._mergeElement(this.uvs, other.uvs);
  28544. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  28545. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  28546. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  28547. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  28548. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  28549. this.colors = this._mergeElement(this.colors, other.colors);
  28550. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  28551. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  28552. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  28553. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  28554. };
  28555. VertexData.prototype._mergeElement = function (source, other) {
  28556. if (!other)
  28557. return source;
  28558. if (!source)
  28559. return other;
  28560. var len = other.length + source.length;
  28561. var isSrcTypedArray = source instanceof Float32Array;
  28562. var isOthTypedArray = other instanceof Float32Array;
  28563. // use non-loop method when the source is Float32Array
  28564. if (isSrcTypedArray) {
  28565. var ret32 = new Float32Array(len);
  28566. ret32.set(source);
  28567. ret32.set(other, source.length);
  28568. return ret32;
  28569. }
  28570. else if (!isOthTypedArray) {
  28571. return source.concat(other);
  28572. }
  28573. else {
  28574. var ret = source.slice(0); // copy source to a separate array
  28575. for (var i = 0, len = other.length; i < len; i++) {
  28576. ret.push(other[i]);
  28577. }
  28578. return ret;
  28579. }
  28580. };
  28581. VertexData.prototype.serialize = function () {
  28582. var serializationObject = this.serialize();
  28583. if (this.positions) {
  28584. serializationObject.positions = this.positions;
  28585. }
  28586. if (this.normals) {
  28587. serializationObject.normals = this.normals;
  28588. }
  28589. if (this.uvs) {
  28590. serializationObject.uvs = this.uvs;
  28591. }
  28592. if (this.uvs2) {
  28593. serializationObject.uvs2 = this.uvs2;
  28594. }
  28595. if (this.uvs3) {
  28596. serializationObject.uvs3 = this.uvs3;
  28597. }
  28598. if (this.uvs4) {
  28599. serializationObject.uvs4 = this.uvs4;
  28600. }
  28601. if (this.uvs5) {
  28602. serializationObject.uvs5 = this.uvs5;
  28603. }
  28604. if (this.uvs6) {
  28605. serializationObject.uvs6 = this.uvs6;
  28606. }
  28607. if (this.colors) {
  28608. serializationObject.colors = this.colors;
  28609. }
  28610. if (this.matricesIndices) {
  28611. serializationObject.matricesIndices = this.matricesIndices;
  28612. serializationObject.matricesIndices._isExpanded = true;
  28613. }
  28614. if (this.matricesWeights) {
  28615. serializationObject.matricesWeights = this.matricesWeights;
  28616. }
  28617. if (this.matricesIndicesExtra) {
  28618. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28619. serializationObject.matricesIndicesExtra._isExpanded = true;
  28620. }
  28621. if (this.matricesWeightsExtra) {
  28622. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28623. }
  28624. serializationObject.indices = this.indices;
  28625. return serializationObject;
  28626. };
  28627. // Statics
  28628. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  28629. return VertexData._ExtractFrom(mesh, copyWhenShared);
  28630. };
  28631. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28632. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28633. };
  28634. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28635. var result = new VertexData();
  28636. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28637. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  28638. }
  28639. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28640. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  28641. }
  28642. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28643. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  28644. }
  28645. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28646. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  28647. }
  28648. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28649. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  28650. }
  28651. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28652. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  28653. }
  28654. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28655. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  28656. }
  28657. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28658. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  28659. }
  28660. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28661. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  28662. }
  28663. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28664. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  28665. }
  28666. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28667. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  28668. }
  28669. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28670. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  28671. }
  28672. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28673. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  28674. }
  28675. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28676. return result;
  28677. };
  28678. VertexData.CreateRibbon = function (options) {
  28679. var pathArray = options.pathArray;
  28680. var closeArray = options.closeArray || false;
  28681. var closePath = options.closePath || false;
  28682. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28683. var offset = options.offset || defaultOffset;
  28684. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28686. var positions = [];
  28687. var indices = [];
  28688. var normals = [];
  28689. var uvs = [];
  28690. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28691. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28692. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28693. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28694. var minlg; // minimal length among all paths from pathArray
  28695. var lg = []; // array of path lengths : nb of vertex per path
  28696. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28697. var p; // path iterator
  28698. var i; // point iterator
  28699. var j; // point iterator
  28700. // if single path in pathArray
  28701. if (pathArray.length < 2) {
  28702. var ar1 = [];
  28703. var ar2 = [];
  28704. for (i = 0; i < pathArray[0].length - offset; i++) {
  28705. ar1.push(pathArray[0][i]);
  28706. ar2.push(pathArray[0][i + offset]);
  28707. }
  28708. pathArray = [ar1, ar2];
  28709. }
  28710. // positions and horizontal distances (u)
  28711. var idc = 0;
  28712. var closePathCorr = (closePath) ? 1 : 0;
  28713. var path;
  28714. var l;
  28715. minlg = pathArray[0].length;
  28716. var vectlg;
  28717. var dist;
  28718. for (p = 0; p < pathArray.length; p++) {
  28719. uTotalDistance[p] = 0;
  28720. us[p] = [0];
  28721. path = pathArray[p];
  28722. l = path.length;
  28723. minlg = (minlg < l) ? minlg : l;
  28724. j = 0;
  28725. while (j < l) {
  28726. positions.push(path[j].x, path[j].y, path[j].z);
  28727. if (j > 0) {
  28728. vectlg = path[j].subtract(path[j - 1]).length();
  28729. dist = vectlg + uTotalDistance[p];
  28730. us[p].push(dist);
  28731. uTotalDistance[p] = dist;
  28732. }
  28733. j++;
  28734. }
  28735. if (closePath) {
  28736. j--;
  28737. positions.push(path[0].x, path[0].y, path[0].z);
  28738. vectlg = path[j].subtract(path[0]).length();
  28739. dist = vectlg + uTotalDistance[p];
  28740. us[p].push(dist);
  28741. uTotalDistance[p] = dist;
  28742. }
  28743. lg[p] = l + closePathCorr;
  28744. idx[p] = idc;
  28745. idc += (l + closePathCorr);
  28746. }
  28747. // vertical distances (v)
  28748. var path1;
  28749. var path2;
  28750. var vertex1;
  28751. var vertex2;
  28752. for (i = 0; i < minlg + closePathCorr; i++) {
  28753. vTotalDistance[i] = 0;
  28754. vs[i] = [0];
  28755. for (p = 0; p < pathArray.length - 1; p++) {
  28756. path1 = pathArray[p];
  28757. path2 = pathArray[p + 1];
  28758. if (i === minlg) {
  28759. vertex1 = path1[0];
  28760. vertex2 = path2[0];
  28761. }
  28762. else {
  28763. vertex1 = path1[i];
  28764. vertex2 = path2[i];
  28765. }
  28766. vectlg = vertex2.subtract(vertex1).length();
  28767. dist = vectlg + vTotalDistance[i];
  28768. vs[i].push(dist);
  28769. vTotalDistance[i] = dist;
  28770. }
  28771. if (closeArray) {
  28772. path1 = pathArray[p];
  28773. path2 = pathArray[0];
  28774. if (i === minlg) {
  28775. vertex2 = path2[0];
  28776. }
  28777. vectlg = vertex2.subtract(vertex1).length();
  28778. dist = vectlg + vTotalDistance[i];
  28779. vTotalDistance[i] = dist;
  28780. }
  28781. }
  28782. // uvs
  28783. var u;
  28784. var v;
  28785. for (p = 0; p < pathArray.length; p++) {
  28786. for (i = 0; i < minlg + closePathCorr; i++) {
  28787. u = us[p][i] / uTotalDistance[p];
  28788. v = vs[i][p] / vTotalDistance[i];
  28789. uvs.push(u, v);
  28790. }
  28791. }
  28792. // indices
  28793. p = 0; // path index
  28794. var pi = 0; // positions array index
  28795. var l1 = lg[p] - 1; // path1 length
  28796. var l2 = lg[p + 1] - 1; // path2 length
  28797. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28798. var shft = idx[1] - idx[0]; // shift
  28799. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28800. while (pi <= min && p < path1nb) {
  28801. // 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
  28802. indices.push(pi, pi + shft, pi + 1);
  28803. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28804. pi += 1;
  28805. if (pi === min) {
  28806. p++;
  28807. if (p === lg.length - 1) {
  28808. shft = idx[0] - idx[p];
  28809. l1 = lg[p] - 1;
  28810. l2 = lg[0] - 1;
  28811. }
  28812. else {
  28813. shft = idx[p + 1] - idx[p];
  28814. l1 = lg[p] - 1;
  28815. l2 = lg[p + 1] - 1;
  28816. }
  28817. pi = idx[p];
  28818. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28819. }
  28820. }
  28821. // normals
  28822. VertexData.ComputeNormals(positions, indices, normals);
  28823. if (closePath) {
  28824. var indexFirst = 0;
  28825. var indexLast = 0;
  28826. for (p = 0; p < pathArray.length; p++) {
  28827. indexFirst = idx[p] * 3;
  28828. if (p + 1 < pathArray.length) {
  28829. indexLast = (idx[p + 1] - 1) * 3;
  28830. }
  28831. else {
  28832. indexLast = normals.length - 3;
  28833. }
  28834. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28835. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28836. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28837. normals[indexLast] = normals[indexFirst];
  28838. normals[indexLast + 1] = normals[indexFirst + 1];
  28839. normals[indexLast + 2] = normals[indexFirst + 2];
  28840. }
  28841. }
  28842. // sides
  28843. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28844. // Result
  28845. var vertexData = new VertexData();
  28846. vertexData.indices = indices;
  28847. vertexData.positions = positions;
  28848. vertexData.normals = normals;
  28849. vertexData.uvs = uvs;
  28850. if (closePath) {
  28851. vertexData._idx = idx;
  28852. }
  28853. return vertexData;
  28854. };
  28855. VertexData.CreateBox = function (options) {
  28856. var normalsSource = [
  28857. new BABYLON.Vector3(0, 0, 1),
  28858. new BABYLON.Vector3(0, 0, -1),
  28859. new BABYLON.Vector3(1, 0, 0),
  28860. new BABYLON.Vector3(-1, 0, 0),
  28861. new BABYLON.Vector3(0, 1, 0),
  28862. new BABYLON.Vector3(0, -1, 0)
  28863. ];
  28864. var indices = [];
  28865. var positions = [];
  28866. var normals = [];
  28867. var uvs = [];
  28868. var width = options.width || options.size || 1;
  28869. var height = options.height || options.size || 1;
  28870. var depth = options.depth || options.size || 1;
  28871. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28872. var faceUV = options.faceUV || new Array(6);
  28873. var faceColors = options.faceColors;
  28874. var colors = [];
  28875. // default face colors and UV if undefined
  28876. for (var f = 0; f < 6; f++) {
  28877. if (faceUV[f] === undefined) {
  28878. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28879. }
  28880. if (faceColors && faceColors[f] === undefined) {
  28881. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28882. }
  28883. }
  28884. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28885. // Create each face in turn.
  28886. for (var index = 0; index < normalsSource.length; index++) {
  28887. var normal = normalsSource[index];
  28888. // Get two vectors perpendicular to the face normal and to each other.
  28889. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28890. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28891. // Six indices (two triangles) per face.
  28892. var verticesLength = positions.length / 3;
  28893. indices.push(verticesLength);
  28894. indices.push(verticesLength + 1);
  28895. indices.push(verticesLength + 2);
  28896. indices.push(verticesLength);
  28897. indices.push(verticesLength + 2);
  28898. indices.push(verticesLength + 3);
  28899. // Four vertices per face.
  28900. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28901. positions.push(vertex.x, vertex.y, vertex.z);
  28902. normals.push(normal.x, normal.y, normal.z);
  28903. uvs.push(faceUV[index].z, faceUV[index].w);
  28904. if (faceColors) {
  28905. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28906. }
  28907. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28908. positions.push(vertex.x, vertex.y, vertex.z);
  28909. normals.push(normal.x, normal.y, normal.z);
  28910. uvs.push(faceUV[index].x, faceUV[index].w);
  28911. if (faceColors) {
  28912. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28913. }
  28914. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28915. positions.push(vertex.x, vertex.y, vertex.z);
  28916. normals.push(normal.x, normal.y, normal.z);
  28917. uvs.push(faceUV[index].x, faceUV[index].y);
  28918. if (faceColors) {
  28919. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28920. }
  28921. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28922. positions.push(vertex.x, vertex.y, vertex.z);
  28923. normals.push(normal.x, normal.y, normal.z);
  28924. uvs.push(faceUV[index].z, faceUV[index].y);
  28925. if (faceColors) {
  28926. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28927. }
  28928. }
  28929. // sides
  28930. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28931. // Result
  28932. var vertexData = new VertexData();
  28933. vertexData.indices = indices;
  28934. vertexData.positions = positions;
  28935. vertexData.normals = normals;
  28936. vertexData.uvs = uvs;
  28937. if (faceColors) {
  28938. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28939. vertexData.colors = totalColors;
  28940. }
  28941. return vertexData;
  28942. };
  28943. VertexData.CreateSphere = function (options) {
  28944. var segments = options.segments || 32;
  28945. var diameterX = options.diameterX || options.diameter || 1;
  28946. var diameterY = options.diameterY || options.diameter || 1;
  28947. var diameterZ = options.diameterZ || options.diameter || 1;
  28948. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28949. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28950. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28951. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28952. var totalZRotationSteps = 2 + segments;
  28953. var totalYRotationSteps = 2 * totalZRotationSteps;
  28954. var indices = [];
  28955. var positions = [];
  28956. var normals = [];
  28957. var uvs = [];
  28958. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28959. var normalizedZ = zRotationStep / totalZRotationSteps;
  28960. var angleZ = normalizedZ * Math.PI * slice;
  28961. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28962. var normalizedY = yRotationStep / totalYRotationSteps;
  28963. var angleY = normalizedY * Math.PI * 2 * arc;
  28964. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28965. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28966. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28967. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28968. var vertex = complete.multiply(radius);
  28969. var normal = complete.divide(radius).normalize();
  28970. positions.push(vertex.x, vertex.y, vertex.z);
  28971. normals.push(normal.x, normal.y, normal.z);
  28972. uvs.push(normalizedY, normalizedZ);
  28973. }
  28974. if (zRotationStep > 0) {
  28975. var verticesCount = positions.length / 3;
  28976. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28977. indices.push((firstIndex));
  28978. indices.push((firstIndex + 1));
  28979. indices.push(firstIndex + totalYRotationSteps + 1);
  28980. indices.push((firstIndex + totalYRotationSteps + 1));
  28981. indices.push((firstIndex + 1));
  28982. indices.push((firstIndex + totalYRotationSteps + 2));
  28983. }
  28984. }
  28985. }
  28986. // Sides
  28987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28988. // Result
  28989. var vertexData = new VertexData();
  28990. vertexData.indices = indices;
  28991. vertexData.positions = positions;
  28992. vertexData.normals = normals;
  28993. vertexData.uvs = uvs;
  28994. return vertexData;
  28995. };
  28996. // Cylinder and cone
  28997. VertexData.CreateCylinder = function (options) {
  28998. var height = options.height || 2;
  28999. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29000. var diameterBottom = options.diameterBottom || options.diameter || 1;
  29001. var tessellation = options.tessellation || 24;
  29002. var subdivisions = options.subdivisions || 1;
  29003. var hasRings = options.hasRings;
  29004. var enclose = options.enclose;
  29005. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29007. var faceUV = options.faceUV || new Array(3);
  29008. var faceColors = options.faceColors;
  29009. // default face colors and UV if undefined
  29010. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29011. var ringNb = (hasRings) ? subdivisions : 1;
  29012. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29013. var f;
  29014. for (f = 0; f < surfaceNb; f++) {
  29015. if (faceColors && faceColors[f] === undefined) {
  29016. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29017. }
  29018. }
  29019. for (f = 0; f < surfaceNb; f++) {
  29020. if (faceUV && faceUV[f] === undefined) {
  29021. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29022. }
  29023. }
  29024. var indices = [];
  29025. var positions = [];
  29026. var normals = [];
  29027. var uvs = [];
  29028. var colors = [];
  29029. var angle_step = Math.PI * 2 * arc / tessellation;
  29030. var angle;
  29031. var h;
  29032. var radius;
  29033. var tan = (diameterBottom - diameterTop) / 2 / height;
  29034. var ringVertex = BABYLON.Vector3.Zero();
  29035. var ringNormal = BABYLON.Vector3.Zero();
  29036. var ringFirstVertex = BABYLON.Vector3.Zero();
  29037. var ringFirstNormal = BABYLON.Vector3.Zero();
  29038. var quadNormal = BABYLON.Vector3.Zero();
  29039. var Y = BABYLON.Axis.Y;
  29040. // positions, normals, uvs
  29041. var i;
  29042. var j;
  29043. var r;
  29044. var ringIdx = 1;
  29045. var s = 1; // surface index
  29046. var cs = 0;
  29047. var v = 0;
  29048. for (i = 0; i <= subdivisions; i++) {
  29049. h = i / subdivisions;
  29050. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29051. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29052. for (r = 0; r < ringIdx; r++) {
  29053. if (hasRings) {
  29054. s += r;
  29055. }
  29056. if (enclose) {
  29057. s += 2 * r;
  29058. }
  29059. for (j = 0; j <= tessellation; j++) {
  29060. angle = j * angle_step;
  29061. // position
  29062. ringVertex.x = Math.cos(-angle) * radius;
  29063. ringVertex.y = -height / 2 + h * height;
  29064. ringVertex.z = Math.sin(-angle) * radius;
  29065. // normal
  29066. if (diameterTop === 0 && i === subdivisions) {
  29067. // if no top cap, reuse former normals
  29068. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29069. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29070. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29071. }
  29072. else {
  29073. ringNormal.x = ringVertex.x;
  29074. ringNormal.z = ringVertex.z;
  29075. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29076. ringNormal.normalize();
  29077. }
  29078. // keep first ring vertex values for enclose
  29079. if (j === 0) {
  29080. ringFirstVertex.copyFrom(ringVertex);
  29081. ringFirstNormal.copyFrom(ringNormal);
  29082. }
  29083. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29084. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29085. if (hasRings) {
  29086. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29087. }
  29088. else {
  29089. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29090. }
  29091. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29092. if (faceColors) {
  29093. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29094. }
  29095. }
  29096. // if enclose, add four vertices and their dedicated normals
  29097. if (arc !== 1 && enclose) {
  29098. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29099. positions.push(0, ringVertex.y, 0);
  29100. positions.push(0, ringVertex.y, 0);
  29101. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29102. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29103. quadNormal.normalize();
  29104. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29105. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29106. quadNormal.normalize();
  29107. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29108. if (hasRings) {
  29109. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29110. }
  29111. else {
  29112. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29113. }
  29114. uvs.push(faceUV[s + 1].x, v);
  29115. uvs.push(faceUV[s + 1].z, v);
  29116. if (hasRings) {
  29117. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29118. }
  29119. else {
  29120. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29121. }
  29122. uvs.push(faceUV[s + 2].x, v);
  29123. uvs.push(faceUV[s + 2].z, v);
  29124. if (faceColors) {
  29125. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29126. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29127. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29128. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29129. }
  29130. }
  29131. if (cs !== s) {
  29132. cs = s;
  29133. }
  29134. }
  29135. }
  29136. // indices
  29137. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29138. var s;
  29139. i = 0;
  29140. for (s = 0; s < subdivisions; s++) {
  29141. for (j = 0; j < tessellation; j++) {
  29142. var i0 = i * (e + 1) + j;
  29143. var i1 = (i + 1) * (e + 1) + j;
  29144. var i2 = i * (e + 1) + (j + 1);
  29145. var i3 = (i + 1) * (e + 1) + (j + 1);
  29146. indices.push(i0, i1, i2);
  29147. indices.push(i3, i2, i1);
  29148. }
  29149. if (arc !== 1 && enclose) {
  29150. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29151. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29152. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29153. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29154. }
  29155. i = (hasRings) ? (i + 2) : (i + 1);
  29156. }
  29157. // Caps
  29158. var createCylinderCap = function (isTop) {
  29159. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29160. if (radius === 0) {
  29161. return;
  29162. }
  29163. // Cap positions, normals & uvs
  29164. var angle;
  29165. var circleVector;
  29166. var i;
  29167. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29168. var c;
  29169. if (faceColors) {
  29170. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29171. }
  29172. // cap center
  29173. var vbase = positions.length / 3;
  29174. var offset = isTop ? height / 2 : -height / 2;
  29175. var center = new BABYLON.Vector3(0, offset, 0);
  29176. positions.push(center.x, center.y, center.z);
  29177. normals.push(0, isTop ? 1 : -1, 0);
  29178. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29179. if (faceColors) {
  29180. colors.push(c.r, c.g, c.b, c.a);
  29181. }
  29182. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29183. for (i = 0; i <= tessellation; i++) {
  29184. angle = Math.PI * 2 * i * arc / tessellation;
  29185. var cos = Math.cos(-angle);
  29186. var sin = Math.sin(-angle);
  29187. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29188. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29189. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29190. normals.push(0, isTop ? 1 : -1, 0);
  29191. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29192. if (faceColors) {
  29193. colors.push(c.r, c.g, c.b, c.a);
  29194. }
  29195. }
  29196. // Cap indices
  29197. for (i = 0; i < tessellation; i++) {
  29198. if (!isTop) {
  29199. indices.push(vbase);
  29200. indices.push(vbase + (i + 1));
  29201. indices.push(vbase + (i + 2));
  29202. }
  29203. else {
  29204. indices.push(vbase);
  29205. indices.push(vbase + (i + 2));
  29206. indices.push(vbase + (i + 1));
  29207. }
  29208. }
  29209. };
  29210. // add caps to geometry
  29211. createCylinderCap(false);
  29212. createCylinderCap(true);
  29213. // Sides
  29214. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29215. var vertexData = new VertexData();
  29216. vertexData.indices = indices;
  29217. vertexData.positions = positions;
  29218. vertexData.normals = normals;
  29219. vertexData.uvs = uvs;
  29220. if (faceColors) {
  29221. vertexData.colors = colors;
  29222. }
  29223. return vertexData;
  29224. };
  29225. VertexData.CreateTorus = function (options) {
  29226. var indices = [];
  29227. var positions = [];
  29228. var normals = [];
  29229. var uvs = [];
  29230. var diameter = options.diameter || 1;
  29231. var thickness = options.thickness || 0.5;
  29232. var tessellation = options.tessellation || 16;
  29233. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29234. var stride = tessellation + 1;
  29235. for (var i = 0; i <= tessellation; i++) {
  29236. var u = i / tessellation;
  29237. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29238. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29239. for (var j = 0; j <= tessellation; j++) {
  29240. var v = 1 - j / tessellation;
  29241. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29242. var dx = Math.cos(innerAngle);
  29243. var dy = Math.sin(innerAngle);
  29244. // Create a vertex.
  29245. var normal = new BABYLON.Vector3(dx, dy, 0);
  29246. var position = normal.scale(thickness / 2);
  29247. var textureCoordinate = new BABYLON.Vector2(u, v);
  29248. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29249. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29250. positions.push(position.x, position.y, position.z);
  29251. normals.push(normal.x, normal.y, normal.z);
  29252. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29253. // And create indices for two triangles.
  29254. var nextI = (i + 1) % stride;
  29255. var nextJ = (j + 1) % stride;
  29256. indices.push(i * stride + j);
  29257. indices.push(i * stride + nextJ);
  29258. indices.push(nextI * stride + j);
  29259. indices.push(i * stride + nextJ);
  29260. indices.push(nextI * stride + nextJ);
  29261. indices.push(nextI * stride + j);
  29262. }
  29263. }
  29264. // Sides
  29265. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29266. // Result
  29267. var vertexData = new VertexData();
  29268. vertexData.indices = indices;
  29269. vertexData.positions = positions;
  29270. vertexData.normals = normals;
  29271. vertexData.uvs = uvs;
  29272. return vertexData;
  29273. };
  29274. VertexData.CreateLineSystem = function (options) {
  29275. var indices = [];
  29276. var positions = [];
  29277. var lines = options.lines;
  29278. var idx = 0;
  29279. for (var l = 0; l < lines.length; l++) {
  29280. var points = lines[l];
  29281. for (var index = 0; index < points.length; index++) {
  29282. positions.push(points[index].x, points[index].y, points[index].z);
  29283. if (index > 0) {
  29284. indices.push(idx - 1);
  29285. indices.push(idx);
  29286. }
  29287. idx++;
  29288. }
  29289. }
  29290. var vertexData = new VertexData();
  29291. vertexData.indices = indices;
  29292. vertexData.positions = positions;
  29293. return vertexData;
  29294. };
  29295. VertexData.CreateDashedLines = function (options) {
  29296. var dashSize = options.dashSize || 3;
  29297. var gapSize = options.gapSize || 1;
  29298. var dashNb = options.dashNb || 200;
  29299. var points = options.points;
  29300. var positions = new Array();
  29301. var indices = new Array();
  29302. var curvect = BABYLON.Vector3.Zero();
  29303. var lg = 0;
  29304. var nb = 0;
  29305. var shft = 0;
  29306. var dashshft = 0;
  29307. var curshft = 0;
  29308. var idx = 0;
  29309. var i = 0;
  29310. for (i = 0; i < points.length - 1; i++) {
  29311. points[i + 1].subtractToRef(points[i], curvect);
  29312. lg += curvect.length();
  29313. }
  29314. shft = lg / dashNb;
  29315. dashshft = dashSize * shft / (dashSize + gapSize);
  29316. for (i = 0; i < points.length - 1; i++) {
  29317. points[i + 1].subtractToRef(points[i], curvect);
  29318. nb = Math.floor(curvect.length() / shft);
  29319. curvect.normalize();
  29320. for (var j = 0; j < nb; j++) {
  29321. curshft = shft * j;
  29322. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29323. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29324. indices.push(idx, idx + 1);
  29325. idx += 2;
  29326. }
  29327. }
  29328. // Result
  29329. var vertexData = new VertexData();
  29330. vertexData.positions = positions;
  29331. vertexData.indices = indices;
  29332. return vertexData;
  29333. };
  29334. VertexData.CreateGround = function (options) {
  29335. var indices = [];
  29336. var positions = [];
  29337. var normals = [];
  29338. var uvs = [];
  29339. var row, col;
  29340. var width = options.width || 1;
  29341. var height = options.height || 1;
  29342. var subdivisions = options.subdivisions || 1;
  29343. for (row = 0; row <= subdivisions; row++) {
  29344. for (col = 0; col <= subdivisions; col++) {
  29345. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  29346. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29347. positions.push(position.x, position.y, position.z);
  29348. normals.push(normal.x, normal.y, normal.z);
  29349. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  29350. }
  29351. }
  29352. for (row = 0; row < subdivisions; row++) {
  29353. for (col = 0; col < subdivisions; col++) {
  29354. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29355. indices.push(col + 1 + row * (subdivisions + 1));
  29356. indices.push(col + row * (subdivisions + 1));
  29357. indices.push(col + (row + 1) * (subdivisions + 1));
  29358. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  29359. indices.push(col + row * (subdivisions + 1));
  29360. }
  29361. }
  29362. // Result
  29363. var vertexData = new VertexData();
  29364. vertexData.indices = indices;
  29365. vertexData.positions = positions;
  29366. vertexData.normals = normals;
  29367. vertexData.uvs = uvs;
  29368. return vertexData;
  29369. };
  29370. VertexData.CreateTiledGround = function (options) {
  29371. var xmin = options.xmin;
  29372. var zmin = options.zmin;
  29373. var xmax = options.xmax;
  29374. var zmax = options.zmax;
  29375. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29376. var precision = options.precision || { w: 1, h: 1 };
  29377. var indices = [];
  29378. var positions = [];
  29379. var normals = [];
  29380. var uvs = [];
  29381. var row, col, tileRow, tileCol;
  29382. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  29383. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29384. precision.w = (precision.w < 1) ? 1 : precision.w;
  29385. precision.h = (precision.h < 1) ? 1 : precision.h;
  29386. var tileSize = {
  29387. 'w': (xmax - xmin) / subdivisions.w,
  29388. 'h': (zmax - zmin) / subdivisions.h
  29389. };
  29390. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29391. // Indices
  29392. var base = positions.length / 3;
  29393. var rowLength = precision.w + 1;
  29394. for (row = 0; row < precision.h; row++) {
  29395. for (col = 0; col < precision.w; col++) {
  29396. var square = [
  29397. base + col + row * rowLength,
  29398. base + (col + 1) + row * rowLength,
  29399. base + (col + 1) + (row + 1) * rowLength,
  29400. base + col + (row + 1) * rowLength
  29401. ];
  29402. indices.push(square[1]);
  29403. indices.push(square[2]);
  29404. indices.push(square[3]);
  29405. indices.push(square[0]);
  29406. indices.push(square[1]);
  29407. indices.push(square[3]);
  29408. }
  29409. }
  29410. // Position, normals and uvs
  29411. var position = BABYLON.Vector3.Zero();
  29412. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29413. for (row = 0; row <= precision.h; row++) {
  29414. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29415. for (col = 0; col <= precision.w; col++) {
  29416. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29417. position.y = 0;
  29418. positions.push(position.x, position.y, position.z);
  29419. normals.push(normal.x, normal.y, normal.z);
  29420. uvs.push(col / precision.w, row / precision.h);
  29421. }
  29422. }
  29423. }
  29424. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29425. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29426. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29427. }
  29428. }
  29429. // Result
  29430. var vertexData = new VertexData();
  29431. vertexData.indices = indices;
  29432. vertexData.positions = positions;
  29433. vertexData.normals = normals;
  29434. vertexData.uvs = uvs;
  29435. return vertexData;
  29436. };
  29437. VertexData.CreateGroundFromHeightMap = function (options) {
  29438. var indices = [];
  29439. var positions = [];
  29440. var normals = [];
  29441. var uvs = [];
  29442. var row, col;
  29443. // Vertices
  29444. for (row = 0; row <= options.subdivisions; row++) {
  29445. for (col = 0; col <= options.subdivisions; col++) {
  29446. 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));
  29447. // Compute height
  29448. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29449. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29450. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29451. var r = options.buffer[pos] / 255.0;
  29452. var g = options.buffer[pos + 1] / 255.0;
  29453. var b = options.buffer[pos + 2] / 255.0;
  29454. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29455. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29456. // Add vertex
  29457. positions.push(position.x, position.y, position.z);
  29458. normals.push(0, 0, 0);
  29459. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29460. }
  29461. }
  29462. // Indices
  29463. for (row = 0; row < options.subdivisions; row++) {
  29464. for (col = 0; col < options.subdivisions; col++) {
  29465. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29466. indices.push(col + 1 + row * (options.subdivisions + 1));
  29467. indices.push(col + row * (options.subdivisions + 1));
  29468. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29469. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29470. indices.push(col + row * (options.subdivisions + 1));
  29471. }
  29472. }
  29473. // Normals
  29474. VertexData.ComputeNormals(positions, indices, normals);
  29475. // Result
  29476. var vertexData = new VertexData();
  29477. vertexData.indices = indices;
  29478. vertexData.positions = positions;
  29479. vertexData.normals = normals;
  29480. vertexData.uvs = uvs;
  29481. return vertexData;
  29482. };
  29483. VertexData.CreatePlane = function (options) {
  29484. var indices = [];
  29485. var positions = [];
  29486. var normals = [];
  29487. var uvs = [];
  29488. var width = options.width || options.size || 1;
  29489. var height = options.height || options.size || 1;
  29490. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29491. // Vertices
  29492. var halfWidth = width / 2.0;
  29493. var halfHeight = height / 2.0;
  29494. positions.push(-halfWidth, -halfHeight, 0);
  29495. normals.push(0, 0, -1.0);
  29496. uvs.push(0.0, 0.0);
  29497. positions.push(halfWidth, -halfHeight, 0);
  29498. normals.push(0, 0, -1.0);
  29499. uvs.push(1.0, 0.0);
  29500. positions.push(halfWidth, halfHeight, 0);
  29501. normals.push(0, 0, -1.0);
  29502. uvs.push(1.0, 1.0);
  29503. positions.push(-halfWidth, halfHeight, 0);
  29504. normals.push(0, 0, -1.0);
  29505. uvs.push(0.0, 1.0);
  29506. // Indices
  29507. indices.push(0);
  29508. indices.push(1);
  29509. indices.push(2);
  29510. indices.push(0);
  29511. indices.push(2);
  29512. indices.push(3);
  29513. // Sides
  29514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29515. // Result
  29516. var vertexData = new VertexData();
  29517. vertexData.indices = indices;
  29518. vertexData.positions = positions;
  29519. vertexData.normals = normals;
  29520. vertexData.uvs = uvs;
  29521. return vertexData;
  29522. };
  29523. VertexData.CreateDisc = function (options) {
  29524. var positions = [];
  29525. var indices = [];
  29526. var normals = [];
  29527. var uvs = [];
  29528. var radius = options.radius || 0.5;
  29529. var tessellation = options.tessellation || 64;
  29530. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29531. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29532. // positions and uvs
  29533. positions.push(0, 0, 0); // disc center first
  29534. uvs.push(0.5, 0.5);
  29535. var theta = Math.PI * 2 * arc;
  29536. var step = theta / tessellation;
  29537. for (var a = 0; a < theta; a += step) {
  29538. var x = Math.cos(a);
  29539. var y = Math.sin(a);
  29540. var u = (x + 1) / 2;
  29541. var v = (1 - y) / 2;
  29542. positions.push(radius * x, radius * y, 0);
  29543. uvs.push(u, v);
  29544. }
  29545. if (arc === 1) {
  29546. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29547. uvs.push(uvs[2], uvs[3]);
  29548. }
  29549. //indices
  29550. var vertexNb = positions.length / 3;
  29551. for (var i = 1; i < vertexNb - 1; i++) {
  29552. indices.push(i + 1, 0, i);
  29553. }
  29554. // result
  29555. VertexData.ComputeNormals(positions, indices, normals);
  29556. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29557. var vertexData = new VertexData();
  29558. vertexData.indices = indices;
  29559. vertexData.positions = positions;
  29560. vertexData.normals = normals;
  29561. vertexData.uvs = uvs;
  29562. return vertexData;
  29563. };
  29564. VertexData.CreateIcoSphere = function (options) {
  29565. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29566. var radius = options.radius || 1;
  29567. var flat = (options.flat === undefined) ? true : options.flat;
  29568. var subdivisions = options.subdivisions || 4;
  29569. var radiusX = options.radiusX || radius;
  29570. var radiusY = options.radiusY || radius;
  29571. var radiusZ = options.radiusZ || radius;
  29572. var t = (1 + Math.sqrt(5)) / 2;
  29573. // 12 vertex x,y,z
  29574. var ico_vertices = [
  29575. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29576. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29577. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29578. ];
  29579. // index of 3 vertex makes a face of icopshere
  29580. var ico_indices = [
  29581. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29582. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29583. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29584. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29585. ];
  29586. // vertex for uv have aliased position, not for UV
  29587. var vertices_unalias_id = [
  29588. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29589. // vertex alias
  29590. 0,
  29591. 2,
  29592. 3,
  29593. 3,
  29594. 3,
  29595. 4,
  29596. 7,
  29597. 8,
  29598. 9,
  29599. 9,
  29600. 10,
  29601. 11 // 23: B + 12
  29602. ];
  29603. // uv as integer step (not pixels !)
  29604. var ico_vertexuv = [
  29605. 5, 1, 3, 1, 6, 4, 0, 0,
  29606. 5, 3, 4, 2, 2, 2, 4, 0,
  29607. 2, 0, 1, 1, 6, 0, 6, 2,
  29608. // vertex alias (for same vertex on different faces)
  29609. 0, 4,
  29610. 3, 3,
  29611. 4, 4,
  29612. 3, 1,
  29613. 4, 2,
  29614. 4, 4,
  29615. 0, 2,
  29616. 1, 1,
  29617. 2, 2,
  29618. 3, 3,
  29619. 1, 3,
  29620. 2, 4 // 23: B + 12
  29621. ];
  29622. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29623. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29624. // First island of uv mapping
  29625. // v = 4h 3+ 2
  29626. // v = 3h 9+ 4
  29627. // v = 2h 9+ 5 B
  29628. // v = 1h 9 1 0
  29629. // v = 0h 3 8 7 A
  29630. // u = 0 1 2 3 4 5 6 *a
  29631. // Second island of uv mapping
  29632. // v = 4h 0+ B+ 4+
  29633. // v = 3h A+ 2+
  29634. // v = 2h 7+ 6 3+
  29635. // v = 1h 8+ 3+
  29636. // v = 0h
  29637. // u = 0 1 2 3 4 5 6 *a
  29638. // Face layout on texture UV mapping
  29639. // ============
  29640. // \ 4 /\ 16 / ======
  29641. // \ / \ / /\ 11 /
  29642. // \/ 7 \/ / \ /
  29643. // ======= / 10 \/
  29644. // /\ 17 /\ =======
  29645. // / \ / \ \ 15 /\
  29646. // / 8 \/ 12 \ \ / \
  29647. // ============ \/ 6 \
  29648. // \ 18 /\ ============
  29649. // \ / \ \ 5 /\ 0 /
  29650. // \/ 13 \ \ / \ /
  29651. // ======= \/ 1 \/
  29652. // =============
  29653. // /\ 19 /\ 2 /\
  29654. // / \ / \ / \
  29655. // / 14 \/ 9 \/ 3 \
  29656. // ===================
  29657. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29658. var ustep = 138 / 1024;
  29659. var vstep = 239 / 1024;
  29660. var uoffset = 60 / 1024;
  29661. var voffset = 26 / 1024;
  29662. // Second island should have margin, not to touch the first island
  29663. // avoid any borderline artefact in pixel rounding
  29664. var island_u_offset = -40 / 1024;
  29665. var island_v_offset = +20 / 1024;
  29666. // face is either island 0 or 1 :
  29667. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29668. var island = [
  29669. 0, 0, 0, 0, 1,
  29670. 0, 0, 1, 1, 0,
  29671. 0, 0, 1, 1, 0,
  29672. 0, 1, 1, 1, 0 // 15 - 19
  29673. ];
  29674. var indices = [];
  29675. var positions = [];
  29676. var normals = [];
  29677. var uvs = [];
  29678. var current_indice = 0;
  29679. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29680. var face_vertex_pos = new Array(3);
  29681. var face_vertex_uv = new Array(3);
  29682. var v012;
  29683. for (v012 = 0; v012 < 3; v012++) {
  29684. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29685. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29686. }
  29687. // create all with normals
  29688. for (var face = 0; face < 20; face++) {
  29689. // 3 vertex per face
  29690. for (v012 = 0; v012 < 3; v012++) {
  29691. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29692. var v_id = ico_indices[3 * face + v012];
  29693. // vertex have 3D position (x,y,z)
  29694. 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]);
  29695. // Normalize to get normal, then scale to radius
  29696. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29697. // uv Coordinates from vertex ID
  29698. 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);
  29699. }
  29700. // Subdivide the face (interpolate pos, norm, uv)
  29701. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29702. // - norm is linear interpolation of vertex corner normal
  29703. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29704. // - uv is linear interpolation
  29705. //
  29706. // Topology is as below for sub-divide by 2
  29707. // vertex shown as v0,v1,v2
  29708. // interp index is i1 to progress in range [v0,v1[
  29709. // interp index is i2 to progress in range [v0,v2[
  29710. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29711. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29712. //
  29713. //
  29714. // i2 v2
  29715. // ^ ^
  29716. // / / \
  29717. // / / \
  29718. // / / \
  29719. // / / (0,1) \
  29720. // / #---------\
  29721. // / / \ (0,0)'/ \
  29722. // / / \ / \
  29723. // / / \ / \
  29724. // / / (0,0) \ / (1,0) \
  29725. // / #---------#---------\
  29726. // v0 v1
  29727. //
  29728. // --------------------> i1
  29729. //
  29730. // interp of (i1,i2):
  29731. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29732. // along i1 : lerp(x0,x1, i1/(S-i2))
  29733. //
  29734. // centroid of triangle is needed to get help normal computation
  29735. // (c1,c2) are used for centroid location
  29736. var interp_vertex = function (i1, i2, c1, c2) {
  29737. // vertex is interpolated from
  29738. // - face_vertex_pos[0..2]
  29739. // - face_vertex_uv[0..2]
  29740. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29741. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29742. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29743. pos_interp.normalize();
  29744. var vertex_normal;
  29745. if (flat) {
  29746. // in flat mode, recalculate normal as face centroid normal
  29747. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29748. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29749. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29750. }
  29751. else {
  29752. // in smooth mode, recalculate normal from each single vertex position
  29753. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29754. }
  29755. // Vertex normal need correction due to X,Y,Z radius scaling
  29756. vertex_normal.x /= radiusX;
  29757. vertex_normal.y /= radiusY;
  29758. vertex_normal.z /= radiusZ;
  29759. vertex_normal.normalize();
  29760. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29761. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29762. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29763. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29764. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29765. uvs.push(uv_interp.x, uv_interp.y);
  29766. // push each vertex has member of a face
  29767. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29768. indices.push(current_indice);
  29769. current_indice++;
  29770. };
  29771. for (var i2 = 0; i2 < subdivisions; i2++) {
  29772. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29773. // face : (i1,i2) for /\ :
  29774. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29775. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29776. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29777. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29778. if (i1 + i2 + 1 < subdivisions) {
  29779. // face : (i1,i2)' for \/ :
  29780. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29781. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29782. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29783. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29784. }
  29785. }
  29786. }
  29787. }
  29788. // Sides
  29789. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29790. // Result
  29791. var vertexData = new VertexData();
  29792. vertexData.indices = indices;
  29793. vertexData.positions = positions;
  29794. vertexData.normals = normals;
  29795. vertexData.uvs = uvs;
  29796. return vertexData;
  29797. };
  29798. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29799. VertexData.CreatePolyhedron = function (options) {
  29800. // provided polyhedron types :
  29801. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29802. // 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)
  29803. var polyhedra = [];
  29804. 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]] };
  29805. 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]] };
  29806. polyhedra[2] = {
  29807. 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]],
  29808. 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]]
  29809. };
  29810. polyhedra[3] = {
  29811. 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]],
  29812. 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]]
  29813. };
  29814. polyhedra[4] = {
  29815. 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]],
  29816. 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]]
  29817. };
  29818. 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]] };
  29819. 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]] };
  29820. 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]] };
  29821. 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]] };
  29822. 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]] };
  29823. 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]] };
  29824. 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]] };
  29825. 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]] };
  29826. 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]] };
  29827. polyhedra[14] = {
  29828. 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]],
  29829. 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]]
  29830. };
  29831. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29832. var size = options.size;
  29833. var sizeX = options.sizeX || size || 1;
  29834. var sizeY = options.sizeY || size || 1;
  29835. var sizeZ = options.sizeZ || size || 1;
  29836. var data = options.custom || polyhedra[type];
  29837. var nbfaces = data.face.length;
  29838. var faceUV = options.faceUV || new Array(nbfaces);
  29839. var faceColors = options.faceColors;
  29840. var flat = (options.flat === undefined) ? true : options.flat;
  29841. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29842. var positions = [];
  29843. var indices = [];
  29844. var normals = [];
  29845. var uvs = [];
  29846. var colors = [];
  29847. var index = 0;
  29848. var faceIdx = 0; // face cursor in the array "indexes"
  29849. var indexes = [];
  29850. var i = 0;
  29851. var f = 0;
  29852. var u, v, ang, x, y, tmp;
  29853. // default face colors and UV if undefined
  29854. if (flat) {
  29855. for (f = 0; f < nbfaces; f++) {
  29856. if (faceColors && faceColors[f] === undefined) {
  29857. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29858. }
  29859. if (faceUV && faceUV[f] === undefined) {
  29860. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29861. }
  29862. }
  29863. }
  29864. if (!flat) {
  29865. for (i = 0; i < data.vertex.length; i++) {
  29866. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29867. uvs.push(0, 0);
  29868. }
  29869. for (f = 0; f < nbfaces; f++) {
  29870. for (i = 0; i < data.face[f].length - 2; i++) {
  29871. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29872. }
  29873. }
  29874. }
  29875. else {
  29876. for (f = 0; f < nbfaces; f++) {
  29877. var fl = data.face[f].length; // number of vertices of the current face
  29878. ang = 2 * Math.PI / fl;
  29879. x = 0.5 * Math.tan(ang / 2);
  29880. y = 0.5;
  29881. // positions, uvs, colors
  29882. for (i = 0; i < fl; i++) {
  29883. // positions
  29884. 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);
  29885. indexes.push(index);
  29886. index++;
  29887. // uvs
  29888. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29889. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29890. uvs.push(u, v);
  29891. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29892. y = x * Math.sin(ang) + y * Math.cos(ang);
  29893. x = tmp;
  29894. // colors
  29895. if (faceColors) {
  29896. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29897. }
  29898. }
  29899. // indices from indexes
  29900. for (i = 0; i < fl - 2; i++) {
  29901. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29902. }
  29903. faceIdx += fl;
  29904. }
  29905. }
  29906. VertexData.ComputeNormals(positions, indices, normals);
  29907. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29908. var vertexData = new VertexData();
  29909. vertexData.positions = positions;
  29910. vertexData.indices = indices;
  29911. vertexData.normals = normals;
  29912. vertexData.uvs = uvs;
  29913. if (faceColors && flat) {
  29914. vertexData.colors = colors;
  29915. }
  29916. return vertexData;
  29917. };
  29918. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29919. VertexData.CreateTorusKnot = function (options) {
  29920. var indices = [];
  29921. var positions = [];
  29922. var normals = [];
  29923. var uvs = [];
  29924. var radius = options.radius || 2;
  29925. var tube = options.tube || 0.5;
  29926. var radialSegments = options.radialSegments || 32;
  29927. var tubularSegments = options.tubularSegments || 32;
  29928. var p = options.p || 2;
  29929. var q = options.q || 3;
  29930. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29931. // Helper
  29932. var getPos = function (angle) {
  29933. var cu = Math.cos(angle);
  29934. var su = Math.sin(angle);
  29935. var quOverP = q / p * angle;
  29936. var cs = Math.cos(quOverP);
  29937. var tx = radius * (2 + cs) * 0.5 * cu;
  29938. var ty = radius * (2 + cs) * su * 0.5;
  29939. var tz = radius * Math.sin(quOverP) * 0.5;
  29940. return new BABYLON.Vector3(tx, ty, tz);
  29941. };
  29942. // Vertices
  29943. var i;
  29944. var j;
  29945. for (i = 0; i <= radialSegments; i++) {
  29946. var modI = i % radialSegments;
  29947. var u = modI / radialSegments * 2 * p * Math.PI;
  29948. var p1 = getPos(u);
  29949. var p2 = getPos(u + 0.01);
  29950. var tang = p2.subtract(p1);
  29951. var n = p2.add(p1);
  29952. var bitan = BABYLON.Vector3.Cross(tang, n);
  29953. n = BABYLON.Vector3.Cross(bitan, tang);
  29954. bitan.normalize();
  29955. n.normalize();
  29956. for (j = 0; j < tubularSegments; j++) {
  29957. var modJ = j % tubularSegments;
  29958. var v = modJ / tubularSegments * 2 * Math.PI;
  29959. var cx = -tube * Math.cos(v);
  29960. var cy = tube * Math.sin(v);
  29961. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29962. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29963. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29964. uvs.push(i / radialSegments);
  29965. uvs.push(j / tubularSegments);
  29966. }
  29967. }
  29968. for (i = 0; i < radialSegments; i++) {
  29969. for (j = 0; j < tubularSegments; j++) {
  29970. var jNext = (j + 1) % tubularSegments;
  29971. var a = i * tubularSegments + j;
  29972. var b = (i + 1) * tubularSegments + j;
  29973. var c = (i + 1) * tubularSegments + jNext;
  29974. var d = i * tubularSegments + jNext;
  29975. indices.push(d);
  29976. indices.push(b);
  29977. indices.push(a);
  29978. indices.push(d);
  29979. indices.push(c);
  29980. indices.push(b);
  29981. }
  29982. }
  29983. // Normals
  29984. VertexData.ComputeNormals(positions, indices, normals);
  29985. // Sides
  29986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29987. // Result
  29988. var vertexData = new VertexData();
  29989. vertexData.indices = indices;
  29990. vertexData.positions = positions;
  29991. vertexData.normals = normals;
  29992. vertexData.uvs = uvs;
  29993. return vertexData;
  29994. };
  29995. // Tools
  29996. /**
  29997. * @param {any} - positions (number[] or Float32Array)
  29998. * @param {any} - indices (number[] or Uint16Array)
  29999. * @param {any} - normals (number[] or Float32Array)
  30000. */
  30001. VertexData.ComputeNormals = function (positions, indices, normals) {
  30002. var index = 0;
  30003. var p1p2x = 0.0;
  30004. var p1p2y = 0.0;
  30005. var p1p2z = 0.0;
  30006. var p3p2x = 0.0;
  30007. var p3p2y = 0.0;
  30008. var p3p2z = 0.0;
  30009. var faceNormalx = 0.0;
  30010. var faceNormaly = 0.0;
  30011. var faceNormalz = 0.0;
  30012. var length = 0.0;
  30013. var i1 = 0;
  30014. var i2 = 0;
  30015. var i3 = 0;
  30016. for (index = 0; index < positions.length; index++) {
  30017. normals[index] = 0.0;
  30018. }
  30019. // indice triplet = 1 face
  30020. var nbFaces = indices.length / 3;
  30021. for (index = 0; index < nbFaces; index++) {
  30022. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  30023. i2 = indices[index * 3 + 1];
  30024. i3 = indices[index * 3 + 2];
  30025. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  30026. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  30027. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  30028. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  30029. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  30030. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  30031. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  30032. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  30033. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  30034. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30035. length = (length === 0) ? 1.0 : length;
  30036. faceNormalx /= length; // normalize this normal
  30037. faceNormaly /= length;
  30038. faceNormalz /= length;
  30039. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  30040. normals[i1 * 3 + 1] += faceNormaly;
  30041. normals[i1 * 3 + 2] += faceNormalz;
  30042. normals[i2 * 3] += faceNormalx;
  30043. normals[i2 * 3 + 1] += faceNormaly;
  30044. normals[i2 * 3 + 2] += faceNormalz;
  30045. normals[i3 * 3] += faceNormalx;
  30046. normals[i3 * 3 + 1] += faceNormaly;
  30047. normals[i3 * 3 + 2] += faceNormalz;
  30048. }
  30049. // last normalization of each normal
  30050. for (index = 0; index < normals.length / 3; index++) {
  30051. faceNormalx = normals[index * 3];
  30052. faceNormaly = normals[index * 3 + 1];
  30053. faceNormalz = normals[index * 3 + 2];
  30054. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30055. length = (length === 0) ? 1.0 : length;
  30056. faceNormalx /= length;
  30057. faceNormaly /= length;
  30058. faceNormalz /= length;
  30059. normals[index * 3] = faceNormalx;
  30060. normals[index * 3 + 1] = faceNormaly;
  30061. normals[index * 3 + 2] = faceNormalz;
  30062. }
  30063. };
  30064. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  30065. var li = indices.length;
  30066. var ln = normals.length;
  30067. var i;
  30068. var n;
  30069. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30070. switch (sideOrientation) {
  30071. case BABYLON.Mesh.FRONTSIDE:
  30072. // nothing changed
  30073. break;
  30074. case BABYLON.Mesh.BACKSIDE:
  30075. var tmp;
  30076. // indices
  30077. for (i = 0; i < li; i += 3) {
  30078. tmp = indices[i];
  30079. indices[i] = indices[i + 2];
  30080. indices[i + 2] = tmp;
  30081. }
  30082. // normals
  30083. for (n = 0; n < ln; n++) {
  30084. normals[n] = -normals[n];
  30085. }
  30086. break;
  30087. case BABYLON.Mesh.DOUBLESIDE:
  30088. // positions
  30089. var lp = positions.length;
  30090. var l = lp / 3;
  30091. for (var p = 0; p < lp; p++) {
  30092. positions[lp + p] = positions[p];
  30093. }
  30094. // indices
  30095. for (i = 0; i < li; i += 3) {
  30096. indices[i + li] = indices[i + 2] + l;
  30097. indices[i + 1 + li] = indices[i + 1] + l;
  30098. indices[i + 2 + li] = indices[i] + l;
  30099. }
  30100. // normals
  30101. for (n = 0; n < ln; n++) {
  30102. normals[ln + n] = -normals[n];
  30103. }
  30104. // uvs
  30105. var lu = uvs.length;
  30106. for (var u = 0; u < lu; u++) {
  30107. uvs[u + lu] = uvs[u];
  30108. }
  30109. break;
  30110. }
  30111. };
  30112. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30113. var vertexData = new VertexData();
  30114. // positions
  30115. var positions = parsedVertexData.positions;
  30116. if (positions) {
  30117. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30118. }
  30119. // normals
  30120. var normals = parsedVertexData.normals;
  30121. if (normals) {
  30122. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30123. }
  30124. // uvs
  30125. var uvs = parsedVertexData.uvs;
  30126. if (uvs) {
  30127. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30128. }
  30129. // uv2s
  30130. var uv2s = parsedVertexData.uv2s;
  30131. if (uv2s) {
  30132. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30133. }
  30134. // uv3s
  30135. var uv3s = parsedVertexData.uv3s;
  30136. if (uv3s) {
  30137. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30138. }
  30139. // uv4s
  30140. var uv4s = parsedVertexData.uv4s;
  30141. if (uv4s) {
  30142. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30143. }
  30144. // uv5s
  30145. var uv5s = parsedVertexData.uv5s;
  30146. if (uv5s) {
  30147. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30148. }
  30149. // uv6s
  30150. var uv6s = parsedVertexData.uv6s;
  30151. if (uv6s) {
  30152. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30153. }
  30154. // colors
  30155. var colors = parsedVertexData.colors;
  30156. if (colors) {
  30157. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30158. }
  30159. // matricesIndices
  30160. var matricesIndices = parsedVertexData.matricesIndices;
  30161. if (matricesIndices) {
  30162. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30163. }
  30164. // matricesWeights
  30165. var matricesWeights = parsedVertexData.matricesWeights;
  30166. if (matricesWeights) {
  30167. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30168. }
  30169. // indices
  30170. var indices = parsedVertexData.indices;
  30171. if (indices) {
  30172. vertexData.indices = indices;
  30173. }
  30174. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30175. };
  30176. return VertexData;
  30177. })();
  30178. BABYLON.VertexData = VertexData;
  30179. })(BABYLON || (BABYLON = {}));
  30180. var BABYLON;
  30181. (function (BABYLON) {
  30182. var Tags = (function () {
  30183. function Tags() {
  30184. }
  30185. Tags.EnableFor = function (obj) {
  30186. obj._tags = obj._tags || {};
  30187. obj.hasTags = function () {
  30188. return Tags.HasTags(obj);
  30189. };
  30190. obj.addTags = function (tagsString) {
  30191. return Tags.AddTagsTo(obj, tagsString);
  30192. };
  30193. obj.removeTags = function (tagsString) {
  30194. return Tags.RemoveTagsFrom(obj, tagsString);
  30195. };
  30196. obj.matchesTagsQuery = function (tagsQuery) {
  30197. return Tags.MatchesQuery(obj, tagsQuery);
  30198. };
  30199. };
  30200. Tags.DisableFor = function (obj) {
  30201. delete obj._tags;
  30202. delete obj.hasTags;
  30203. delete obj.addTags;
  30204. delete obj.removeTags;
  30205. delete obj.matchesTagsQuery;
  30206. };
  30207. Tags.HasTags = function (obj) {
  30208. if (!obj._tags) {
  30209. return false;
  30210. }
  30211. return !BABYLON.Tools.IsEmpty(obj._tags);
  30212. };
  30213. Tags.GetTags = function (obj, asString) {
  30214. if (asString === void 0) { asString = true; }
  30215. if (!obj._tags) {
  30216. return null;
  30217. }
  30218. if (asString) {
  30219. var tagsArray = [];
  30220. for (var tag in obj._tags) {
  30221. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  30222. tagsArray.push(tag);
  30223. }
  30224. }
  30225. return tagsArray.join(" ");
  30226. }
  30227. else {
  30228. return obj._tags;
  30229. }
  30230. };
  30231. // the tags 'true' and 'false' are reserved and cannot be used as tags
  30232. // a tag cannot start with '||', '&&', and '!'
  30233. // it cannot contain whitespaces
  30234. Tags.AddTagsTo = function (obj, tagsString) {
  30235. if (!tagsString) {
  30236. return;
  30237. }
  30238. if (typeof tagsString !== "string") {
  30239. return;
  30240. }
  30241. var tags = tagsString.split(" ");
  30242. for (var t in tags) {
  30243. Tags._AddTagTo(obj, tags[t]);
  30244. }
  30245. };
  30246. Tags._AddTagTo = function (obj, tag) {
  30247. tag = tag.trim();
  30248. if (tag === "" || tag === "true" || tag === "false") {
  30249. return;
  30250. }
  30251. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  30252. return;
  30253. }
  30254. Tags.EnableFor(obj);
  30255. obj._tags[tag] = true;
  30256. };
  30257. Tags.RemoveTagsFrom = function (obj, tagsString) {
  30258. if (!Tags.HasTags(obj)) {
  30259. return;
  30260. }
  30261. var tags = tagsString.split(" ");
  30262. for (var t in tags) {
  30263. Tags._RemoveTagFrom(obj, tags[t]);
  30264. }
  30265. };
  30266. Tags._RemoveTagFrom = function (obj, tag) {
  30267. delete obj._tags[tag];
  30268. };
  30269. Tags.MatchesQuery = function (obj, tagsQuery) {
  30270. if (tagsQuery === undefined) {
  30271. return true;
  30272. }
  30273. if (tagsQuery === "") {
  30274. return Tags.HasTags(obj);
  30275. }
  30276. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  30277. };
  30278. return Tags;
  30279. })();
  30280. BABYLON.Tags = Tags;
  30281. })(BABYLON || (BABYLON = {}));
  30282. var BABYLON;
  30283. (function (BABYLON) {
  30284. var Internals;
  30285. (function (Internals) {
  30286. var AndOrNotEvaluator = (function () {
  30287. function AndOrNotEvaluator() {
  30288. }
  30289. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  30290. if (!query.match(/\([^\(\)]*\)/g)) {
  30291. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  30292. }
  30293. else {
  30294. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  30295. // remove parenthesis
  30296. r = r.slice(1, r.length - 1);
  30297. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  30298. });
  30299. }
  30300. if (query === "true") {
  30301. return true;
  30302. }
  30303. if (query === "false") {
  30304. return false;
  30305. }
  30306. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  30307. };
  30308. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  30309. evaluateCallback = evaluateCallback || (function (r) {
  30310. return r === "true" ? true : false;
  30311. });
  30312. var result;
  30313. var or = parenthesisContent.split("||");
  30314. for (var i in or) {
  30315. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  30316. var and = ori.split("&&");
  30317. if (and.length > 1) {
  30318. for (var j = 0; j < and.length; ++j) {
  30319. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  30320. if (andj !== "true" && andj !== "false") {
  30321. if (andj[0] === "!") {
  30322. result = !evaluateCallback(andj.substring(1));
  30323. }
  30324. else {
  30325. result = evaluateCallback(andj);
  30326. }
  30327. }
  30328. else {
  30329. result = andj === "true" ? true : false;
  30330. }
  30331. if (!result) {
  30332. ori = "false";
  30333. break;
  30334. }
  30335. }
  30336. }
  30337. if (result || ori === "true") {
  30338. result = true;
  30339. break;
  30340. }
  30341. // result equals false (or undefined)
  30342. if (ori !== "true" && ori !== "false") {
  30343. if (ori[0] === "!") {
  30344. result = !evaluateCallback(ori.substring(1));
  30345. }
  30346. else {
  30347. result = evaluateCallback(ori);
  30348. }
  30349. }
  30350. else {
  30351. result = ori === "true" ? true : false;
  30352. }
  30353. }
  30354. // the whole parenthesis scope is replaced by 'true' or 'false'
  30355. return result ? "true" : "false";
  30356. };
  30357. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  30358. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  30359. // remove whitespaces
  30360. r = r.replace(/[\s]/g, function () { return ""; });
  30361. return r.length % 2 ? "!" : "";
  30362. });
  30363. booleanString = booleanString.trim();
  30364. if (booleanString === "!true") {
  30365. booleanString = "false";
  30366. }
  30367. else if (booleanString === "!false") {
  30368. booleanString = "true";
  30369. }
  30370. return booleanString;
  30371. };
  30372. return AndOrNotEvaluator;
  30373. })();
  30374. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  30375. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30376. })(BABYLON || (BABYLON = {}));
  30377. var BABYLON;
  30378. (function (BABYLON) {
  30379. var PostProcessRenderPass = (function () {
  30380. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  30381. this._enabled = true;
  30382. this._refCount = 0;
  30383. this._name = name;
  30384. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  30385. this.setRenderList(renderList);
  30386. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  30387. this._renderTexture.onAfterRenderObservable.add(afterRender);
  30388. this._scene = scene;
  30389. this._renderList = renderList;
  30390. }
  30391. // private
  30392. PostProcessRenderPass.prototype._incRefCount = function () {
  30393. if (this._refCount === 0) {
  30394. this._scene.customRenderTargets.push(this._renderTexture);
  30395. }
  30396. return ++this._refCount;
  30397. };
  30398. PostProcessRenderPass.prototype._decRefCount = function () {
  30399. this._refCount--;
  30400. if (this._refCount <= 0) {
  30401. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  30402. }
  30403. return this._refCount;
  30404. };
  30405. PostProcessRenderPass.prototype._update = function () {
  30406. this.setRenderList(this._renderList);
  30407. };
  30408. // public
  30409. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  30410. this._renderTexture.renderList = renderList;
  30411. };
  30412. PostProcessRenderPass.prototype.getRenderTexture = function () {
  30413. return this._renderTexture;
  30414. };
  30415. return PostProcessRenderPass;
  30416. })();
  30417. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  30418. })(BABYLON || (BABYLON = {}));
  30419. var BABYLON;
  30420. (function (BABYLON) {
  30421. var PostProcessRenderEffect = (function () {
  30422. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  30423. this._engine = engine;
  30424. this._name = name;
  30425. this._singleInstance = singleInstance || true;
  30426. this._getPostProcess = getPostProcess;
  30427. this._cameras = [];
  30428. this._indicesForCamera = [];
  30429. this._postProcesses = {};
  30430. this._renderPasses = {};
  30431. this._renderEffectAsPasses = {};
  30432. }
  30433. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  30434. get: function () {
  30435. for (var index in this._postProcesses) {
  30436. if (!this._postProcesses[index].isSupported) {
  30437. return false;
  30438. }
  30439. }
  30440. return true;
  30441. },
  30442. enumerable: true,
  30443. configurable: true
  30444. });
  30445. PostProcessRenderEffect.prototype._update = function () {
  30446. for (var renderPassName in this._renderPasses) {
  30447. this._renderPasses[renderPassName]._update();
  30448. }
  30449. };
  30450. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  30451. this._renderPasses[renderPass._name] = renderPass;
  30452. this._linkParameters();
  30453. };
  30454. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  30455. delete this._renderPasses[renderPass._name];
  30456. this._linkParameters();
  30457. };
  30458. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  30459. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  30460. this._linkParameters();
  30461. };
  30462. PostProcessRenderEffect.prototype.getPass = function (passName) {
  30463. for (var renderPassName in this._renderPasses) {
  30464. if (renderPassName === passName) {
  30465. return this._renderPasses[passName];
  30466. }
  30467. }
  30468. };
  30469. PostProcessRenderEffect.prototype.emptyPasses = function () {
  30470. this._renderPasses = {};
  30471. this._linkParameters();
  30472. };
  30473. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  30474. var cameraKey;
  30475. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30476. for (var i = 0; i < _cam.length; i++) {
  30477. var camera = _cam[i];
  30478. var cameraName = camera.name;
  30479. if (this._singleInstance) {
  30480. cameraKey = 0;
  30481. }
  30482. else {
  30483. cameraKey = cameraName;
  30484. }
  30485. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  30486. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  30487. if (!this._indicesForCamera[cameraName]) {
  30488. this._indicesForCamera[cameraName] = [];
  30489. }
  30490. this._indicesForCamera[cameraName].push(index);
  30491. if (this._cameras.indexOf(camera) === -1) {
  30492. this._cameras[cameraName] = camera;
  30493. }
  30494. for (var passName in this._renderPasses) {
  30495. this._renderPasses[passName]._incRefCount();
  30496. }
  30497. }
  30498. this._linkParameters();
  30499. };
  30500. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  30501. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30502. for (var i = 0; i < _cam.length; i++) {
  30503. var camera = _cam[i];
  30504. var cameraName = camera.name;
  30505. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30506. var index = this._cameras.indexOf(cameraName);
  30507. this._indicesForCamera.splice(index, 1);
  30508. this._cameras.splice(index, 1);
  30509. for (var passName in this._renderPasses) {
  30510. this._renderPasses[passName]._decRefCount();
  30511. }
  30512. }
  30513. };
  30514. PostProcessRenderEffect.prototype._enable = function (cameras) {
  30515. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30516. for (var i = 0; i < _cam.length; i++) {
  30517. var camera = _cam[i];
  30518. var cameraName = camera.name;
  30519. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  30520. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  30521. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  30522. }
  30523. }
  30524. for (var passName in this._renderPasses) {
  30525. this._renderPasses[passName]._incRefCount();
  30526. }
  30527. }
  30528. };
  30529. PostProcessRenderEffect.prototype._disable = function (cameras) {
  30530. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30531. for (var i = 0; i < _cam.length; i++) {
  30532. var camera = _cam[i];
  30533. var cameraName = camera.Name;
  30534. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  30535. for (var passName in this._renderPasses) {
  30536. this._renderPasses[passName]._decRefCount();
  30537. }
  30538. }
  30539. };
  30540. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  30541. if (this._singleInstance) {
  30542. return this._postProcesses[0];
  30543. }
  30544. else {
  30545. return this._postProcesses[camera.name];
  30546. }
  30547. };
  30548. PostProcessRenderEffect.prototype._linkParameters = function () {
  30549. var _this = this;
  30550. for (var index in this._postProcesses) {
  30551. if (this.applyParameters) {
  30552. this.applyParameters(this._postProcesses[index]);
  30553. }
  30554. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  30555. _this._linkTextures(effect);
  30556. });
  30557. }
  30558. };
  30559. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  30560. for (var renderPassName in this._renderPasses) {
  30561. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  30562. }
  30563. for (var renderEffectName in this._renderEffectAsPasses) {
  30564. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  30565. }
  30566. };
  30567. return PostProcessRenderEffect;
  30568. })();
  30569. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  30570. })(BABYLON || (BABYLON = {}));
  30571. var BABYLON;
  30572. (function (BABYLON) {
  30573. var PostProcessRenderPipeline = (function () {
  30574. function PostProcessRenderPipeline(engine, name) {
  30575. this._engine = engine;
  30576. this._name = name;
  30577. this._renderEffects = {};
  30578. this._renderEffectsForIsolatedPass = {};
  30579. this._cameras = [];
  30580. }
  30581. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  30582. get: function () {
  30583. for (var renderEffectName in this._renderEffects) {
  30584. if (!this._renderEffects[renderEffectName].isSupported) {
  30585. return false;
  30586. }
  30587. }
  30588. return true;
  30589. },
  30590. enumerable: true,
  30591. configurable: true
  30592. });
  30593. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  30594. this._renderEffects[renderEffect._name] = renderEffect;
  30595. };
  30596. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  30597. var renderEffects = this._renderEffects[renderEffectName];
  30598. if (!renderEffects) {
  30599. return;
  30600. }
  30601. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30602. };
  30603. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  30604. var renderEffects = this._renderEffects[renderEffectName];
  30605. if (!renderEffects) {
  30606. return;
  30607. }
  30608. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30609. };
  30610. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  30611. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30612. var indicesToDelete = [];
  30613. var i;
  30614. for (i = 0; i < _cam.length; i++) {
  30615. var camera = _cam[i];
  30616. var cameraName = camera.name;
  30617. if (this._cameras.indexOf(camera) === -1) {
  30618. this._cameras[cameraName] = camera;
  30619. }
  30620. else if (unique) {
  30621. indicesToDelete.push(i);
  30622. }
  30623. }
  30624. for (i = 0; i < indicesToDelete.length; i++) {
  30625. cameras.splice(indicesToDelete[i], 1);
  30626. }
  30627. for (var renderEffectName in this._renderEffects) {
  30628. this._renderEffects[renderEffectName]._attachCameras(_cam);
  30629. }
  30630. };
  30631. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30632. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30633. for (var renderEffectName in this._renderEffects) {
  30634. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30635. }
  30636. for (var i = 0; i < _cam.length; i++) {
  30637. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  30638. }
  30639. };
  30640. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  30641. var _this = this;
  30642. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30643. var pass = null;
  30644. var renderEffectName;
  30645. for (renderEffectName in this._renderEffects) {
  30646. pass = this._renderEffects[renderEffectName].getPass(passName);
  30647. if (pass != null) {
  30648. break;
  30649. }
  30650. }
  30651. if (pass === null) {
  30652. return;
  30653. }
  30654. for (renderEffectName in this._renderEffects) {
  30655. this._renderEffects[renderEffectName]._disable(_cam);
  30656. }
  30657. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  30658. for (var i = 0; i < _cam.length; i++) {
  30659. var camera = _cam[i];
  30660. var cameraName = camera.name;
  30661. 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); });
  30662. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  30663. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  30664. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  30665. }
  30666. };
  30667. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  30668. var _this = this;
  30669. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30670. for (var i = 0; i < _cam.length; i++) {
  30671. var camera = _cam[i];
  30672. var cameraName = camera.name;
  30673. 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); });
  30674. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  30675. }
  30676. for (var renderEffectName in this._renderEffects) {
  30677. this._renderEffects[renderEffectName]._enable(_cam);
  30678. }
  30679. };
  30680. PostProcessRenderPipeline.prototype._update = function () {
  30681. for (var renderEffectName in this._renderEffects) {
  30682. this._renderEffects[renderEffectName]._update();
  30683. }
  30684. for (var i = 0; i < this._cameras.length; i++) {
  30685. var cameraName = this._cameras[i].name;
  30686. if (this._renderEffectsForIsolatedPass[cameraName]) {
  30687. this._renderEffectsForIsolatedPass[cameraName]._update();
  30688. }
  30689. }
  30690. };
  30691. PostProcessRenderPipeline.prototype.dispose = function () {
  30692. // Must be implemented by children
  30693. };
  30694. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  30695. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  30696. return PostProcessRenderPipeline;
  30697. })();
  30698. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  30699. })(BABYLON || (BABYLON = {}));
  30700. var BABYLON;
  30701. (function (BABYLON) {
  30702. var PostProcessRenderPipelineManager = (function () {
  30703. function PostProcessRenderPipelineManager() {
  30704. this._renderPipelines = {};
  30705. }
  30706. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  30707. this._renderPipelines[renderPipeline._name] = renderPipeline;
  30708. };
  30709. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  30710. var renderPipeline = this._renderPipelines[renderPipelineName];
  30711. if (!renderPipeline) {
  30712. return;
  30713. }
  30714. renderPipeline._attachCameras(cameras, unique);
  30715. };
  30716. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  30717. var renderPipeline = this._renderPipelines[renderPipelineName];
  30718. if (!renderPipeline) {
  30719. return;
  30720. }
  30721. renderPipeline._detachCameras(cameras);
  30722. };
  30723. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30724. var renderPipeline = this._renderPipelines[renderPipelineName];
  30725. if (!renderPipeline) {
  30726. return;
  30727. }
  30728. renderPipeline._enableEffect(renderEffectName, cameras);
  30729. };
  30730. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30731. var renderPipeline = this._renderPipelines[renderPipelineName];
  30732. if (!renderPipeline) {
  30733. return;
  30734. }
  30735. renderPipeline._disableEffect(renderEffectName, cameras);
  30736. };
  30737. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  30738. var renderPipeline = this._renderPipelines[renderPipelineName];
  30739. if (!renderPipeline) {
  30740. return;
  30741. }
  30742. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  30743. };
  30744. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  30745. var renderPipeline = this._renderPipelines[renderPipelineName];
  30746. if (!renderPipeline) {
  30747. return;
  30748. }
  30749. renderPipeline._disableDisplayOnlyPass(cameras);
  30750. };
  30751. PostProcessRenderPipelineManager.prototype.update = function () {
  30752. for (var renderPipelineName in this._renderPipelines) {
  30753. var pipeline = this._renderPipelines[renderPipelineName];
  30754. if (!pipeline.isSupported) {
  30755. pipeline.dispose();
  30756. delete this._renderPipelines[renderPipelineName];
  30757. }
  30758. else {
  30759. pipeline._update();
  30760. }
  30761. }
  30762. };
  30763. return PostProcessRenderPipelineManager;
  30764. })();
  30765. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  30766. })(BABYLON || (BABYLON = {}));
  30767. var BABYLON;
  30768. (function (BABYLON) {
  30769. var BoundingBoxRenderer = (function () {
  30770. function BoundingBoxRenderer(scene) {
  30771. this.frontColor = new BABYLON.Color3(1, 1, 1);
  30772. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  30773. this.showBackLines = true;
  30774. this.renderList = new BABYLON.SmartArray(32);
  30775. this._scene = scene;
  30776. }
  30777. BoundingBoxRenderer.prototype._prepareRessources = function () {
  30778. if (this._colorShader) {
  30779. return;
  30780. }
  30781. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  30782. attributes: ["position"],
  30783. uniforms: ["worldViewProjection", "color"]
  30784. });
  30785. var engine = this._scene.getEngine();
  30786. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  30787. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  30788. this._ib = 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]);
  30789. };
  30790. BoundingBoxRenderer.prototype.reset = function () {
  30791. this.renderList.reset();
  30792. };
  30793. BoundingBoxRenderer.prototype.render = function () {
  30794. if (this.renderList.length === 0) {
  30795. return;
  30796. }
  30797. this._prepareRessources();
  30798. if (!this._colorShader.isReady()) {
  30799. return;
  30800. }
  30801. var engine = this._scene.getEngine();
  30802. engine.setDepthWrite(false);
  30803. this._colorShader._preBind();
  30804. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  30805. var boundingBox = this.renderList.data[boundingBoxIndex];
  30806. var min = boundingBox.minimum;
  30807. var max = boundingBox.maximum;
  30808. var diff = max.subtract(min);
  30809. var median = min.add(diff.scale(0.5));
  30810. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  30811. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  30812. .multiply(boundingBox.getWorldMatrix());
  30813. // VBOs
  30814. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  30815. if (this.showBackLines) {
  30816. // Back
  30817. engine.setDepthFunctionToGreaterOrEqual();
  30818. this._scene.resetCachedMaterial();
  30819. this._colorShader.setColor4("color", this.backColor.toColor4());
  30820. this._colorShader.bind(worldMatrix);
  30821. // Draw order
  30822. engine.draw(false, 0, 24);
  30823. }
  30824. // Front
  30825. engine.setDepthFunctionToLess();
  30826. this._scene.resetCachedMaterial();
  30827. this._colorShader.setColor4("color", this.frontColor.toColor4());
  30828. this._colorShader.bind(worldMatrix);
  30829. // Draw order
  30830. engine.draw(false, 0, 24);
  30831. }
  30832. this._colorShader.unbind();
  30833. engine.setDepthFunctionToLessOrEqual();
  30834. engine.setDepthWrite(true);
  30835. };
  30836. BoundingBoxRenderer.prototype.dispose = function () {
  30837. if (!this._colorShader) {
  30838. return;
  30839. }
  30840. this._colorShader.dispose();
  30841. this._vb.dispose();
  30842. this._scene.getEngine()._releaseBuffer(this._ib);
  30843. };
  30844. return BoundingBoxRenderer;
  30845. })();
  30846. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  30847. })(BABYLON || (BABYLON = {}));
  30848. var BABYLON;
  30849. (function (BABYLON) {
  30850. var Condition = (function () {
  30851. function Condition(actionManager) {
  30852. this._actionManager = actionManager;
  30853. }
  30854. Condition.prototype.isValid = function () {
  30855. return true;
  30856. };
  30857. Condition.prototype._getProperty = function (propertyPath) {
  30858. return this._actionManager._getProperty(propertyPath);
  30859. };
  30860. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  30861. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30862. };
  30863. Condition.prototype.serialize = function () {
  30864. };
  30865. Condition.prototype._serialize = function (serializedCondition) {
  30866. return {
  30867. type: 2,
  30868. children: [],
  30869. name: serializedCondition.name,
  30870. properties: serializedCondition.properties
  30871. };
  30872. };
  30873. return Condition;
  30874. })();
  30875. BABYLON.Condition = Condition;
  30876. var ValueCondition = (function (_super) {
  30877. __extends(ValueCondition, _super);
  30878. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  30879. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  30880. _super.call(this, actionManager);
  30881. this.propertyPath = propertyPath;
  30882. this.value = value;
  30883. this.operator = operator;
  30884. this._target = target;
  30885. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  30886. this._property = this._getProperty(this.propertyPath);
  30887. }
  30888. Object.defineProperty(ValueCondition, "IsEqual", {
  30889. get: function () {
  30890. return ValueCondition._IsEqual;
  30891. },
  30892. enumerable: true,
  30893. configurable: true
  30894. });
  30895. Object.defineProperty(ValueCondition, "IsDifferent", {
  30896. get: function () {
  30897. return ValueCondition._IsDifferent;
  30898. },
  30899. enumerable: true,
  30900. configurable: true
  30901. });
  30902. Object.defineProperty(ValueCondition, "IsGreater", {
  30903. get: function () {
  30904. return ValueCondition._IsGreater;
  30905. },
  30906. enumerable: true,
  30907. configurable: true
  30908. });
  30909. Object.defineProperty(ValueCondition, "IsLesser", {
  30910. get: function () {
  30911. return ValueCondition._IsLesser;
  30912. },
  30913. enumerable: true,
  30914. configurable: true
  30915. });
  30916. // Methods
  30917. ValueCondition.prototype.isValid = function () {
  30918. switch (this.operator) {
  30919. case ValueCondition.IsGreater:
  30920. return this._effectiveTarget[this._property] > this.value;
  30921. case ValueCondition.IsLesser:
  30922. return this._effectiveTarget[this._property] < this.value;
  30923. case ValueCondition.IsEqual:
  30924. case ValueCondition.IsDifferent:
  30925. var check;
  30926. if (this.value.equals) {
  30927. check = this.value.equals(this._effectiveTarget[this._property]);
  30928. }
  30929. else {
  30930. check = this.value === this._effectiveTarget[this._property];
  30931. }
  30932. return this.operator === ValueCondition.IsEqual ? check : !check;
  30933. }
  30934. return false;
  30935. };
  30936. ValueCondition.prototype.serialize = function () {
  30937. return this._serialize({
  30938. name: "ValueCondition",
  30939. properties: [
  30940. BABYLON.Action._GetTargetProperty(this._target),
  30941. { name: "propertyPath", value: this.propertyPath },
  30942. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  30943. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  30944. ]
  30945. });
  30946. };
  30947. ValueCondition.GetOperatorName = function (operator) {
  30948. switch (operator) {
  30949. case ValueCondition._IsEqual: return "IsEqual";
  30950. case ValueCondition._IsDifferent: return "IsDifferent";
  30951. case ValueCondition._IsGreater: return "IsGreater";
  30952. case ValueCondition._IsLesser: return "IsLesser";
  30953. default: return "";
  30954. }
  30955. };
  30956. // Statics
  30957. ValueCondition._IsEqual = 0;
  30958. ValueCondition._IsDifferent = 1;
  30959. ValueCondition._IsGreater = 2;
  30960. ValueCondition._IsLesser = 3;
  30961. return ValueCondition;
  30962. })(Condition);
  30963. BABYLON.ValueCondition = ValueCondition;
  30964. var PredicateCondition = (function (_super) {
  30965. __extends(PredicateCondition, _super);
  30966. function PredicateCondition(actionManager, predicate) {
  30967. _super.call(this, actionManager);
  30968. this.predicate = predicate;
  30969. }
  30970. PredicateCondition.prototype.isValid = function () {
  30971. return this.predicate();
  30972. };
  30973. return PredicateCondition;
  30974. })(Condition);
  30975. BABYLON.PredicateCondition = PredicateCondition;
  30976. var StateCondition = (function (_super) {
  30977. __extends(StateCondition, _super);
  30978. function StateCondition(actionManager, target, value) {
  30979. _super.call(this, actionManager);
  30980. this.value = value;
  30981. this._target = target;
  30982. }
  30983. // Methods
  30984. StateCondition.prototype.isValid = function () {
  30985. return this._target.state === this.value;
  30986. };
  30987. StateCondition.prototype.serialize = function () {
  30988. return this._serialize({
  30989. name: "StateCondition",
  30990. properties: [
  30991. BABYLON.Action._GetTargetProperty(this._target),
  30992. { name: "value", value: this.value }
  30993. ]
  30994. });
  30995. };
  30996. return StateCondition;
  30997. })(Condition);
  30998. BABYLON.StateCondition = StateCondition;
  30999. })(BABYLON || (BABYLON = {}));
  31000. var BABYLON;
  31001. (function (BABYLON) {
  31002. var Action = (function () {
  31003. function Action(triggerOptions, condition) {
  31004. this.triggerOptions = triggerOptions;
  31005. if (triggerOptions.parameter) {
  31006. this.trigger = triggerOptions.trigger;
  31007. this._triggerParameter = triggerOptions.parameter;
  31008. }
  31009. else {
  31010. this.trigger = triggerOptions;
  31011. }
  31012. this._nextActiveAction = this;
  31013. this._condition = condition;
  31014. }
  31015. // Methods
  31016. Action.prototype._prepare = function () {
  31017. };
  31018. Action.prototype.getTriggerParameter = function () {
  31019. return this._triggerParameter;
  31020. };
  31021. Action.prototype._executeCurrent = function (evt) {
  31022. if (this._nextActiveAction._condition) {
  31023. var condition = this._nextActiveAction._condition;
  31024. var currentRenderId = this._actionManager.getScene().getRenderId();
  31025. // We cache the current evaluation for the current frame
  31026. if (condition._evaluationId === currentRenderId) {
  31027. if (!condition._currentResult) {
  31028. return;
  31029. }
  31030. }
  31031. else {
  31032. condition._evaluationId = currentRenderId;
  31033. if (!condition.isValid()) {
  31034. condition._currentResult = false;
  31035. return;
  31036. }
  31037. condition._currentResult = true;
  31038. }
  31039. }
  31040. this._nextActiveAction.execute(evt);
  31041. this.skipToNextActiveAction();
  31042. };
  31043. Action.prototype.execute = function (evt) {
  31044. };
  31045. Action.prototype.skipToNextActiveAction = function () {
  31046. if (this._nextActiveAction._child) {
  31047. if (!this._nextActiveAction._child._actionManager) {
  31048. this._nextActiveAction._child._actionManager = this._actionManager;
  31049. }
  31050. this._nextActiveAction = this._nextActiveAction._child;
  31051. }
  31052. else {
  31053. this._nextActiveAction = this;
  31054. }
  31055. };
  31056. Action.prototype.then = function (action) {
  31057. this._child = action;
  31058. action._actionManager = this._actionManager;
  31059. action._prepare();
  31060. return action;
  31061. };
  31062. Action.prototype._getProperty = function (propertyPath) {
  31063. return this._actionManager._getProperty(propertyPath);
  31064. };
  31065. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  31066. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31067. };
  31068. Action.prototype.serialize = function (parent) {
  31069. };
  31070. // Called by BABYLON.Action objects in serialize(...). Internal use
  31071. Action.prototype._serialize = function (serializedAction, parent) {
  31072. var serializationObject = {
  31073. type: 1,
  31074. children: [],
  31075. name: serializedAction.name,
  31076. properties: serializedAction.properties || []
  31077. };
  31078. // Serialize child
  31079. if (this._child) {
  31080. this._child.serialize(serializationObject);
  31081. }
  31082. // Check if "this" has a condition
  31083. if (this._condition) {
  31084. var serializedCondition = this._condition.serialize();
  31085. serializedCondition.children.push(serializationObject);
  31086. if (parent) {
  31087. parent.children.push(serializedCondition);
  31088. }
  31089. return serializedCondition;
  31090. }
  31091. if (parent) {
  31092. parent.children.push(serializationObject);
  31093. }
  31094. return serializationObject;
  31095. };
  31096. Action._SerializeValueAsString = function (value) {
  31097. if (typeof value === "number") {
  31098. return value.toString();
  31099. }
  31100. if (typeof value === "boolean") {
  31101. return value ? "true" : "false";
  31102. }
  31103. if (value instanceof BABYLON.Vector2) {
  31104. return value.x + ", " + value.y;
  31105. }
  31106. if (value instanceof BABYLON.Vector3) {
  31107. return value.x + ", " + value.y + ", " + value.z;
  31108. }
  31109. if (value instanceof BABYLON.Color3) {
  31110. return value.r + ", " + value.g + ", " + value.b;
  31111. }
  31112. if (value instanceof BABYLON.Color4) {
  31113. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  31114. }
  31115. return value; // string
  31116. };
  31117. Action._GetTargetProperty = function (target) {
  31118. return {
  31119. name: "target",
  31120. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  31121. : target instanceof BABYLON.Light ? "LightProperties"
  31122. : target instanceof BABYLON.Camera ? "CameraProperties"
  31123. : "SceneProperties",
  31124. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  31125. };
  31126. };
  31127. return Action;
  31128. })();
  31129. BABYLON.Action = Action;
  31130. })(BABYLON || (BABYLON = {}));
  31131. var BABYLON;
  31132. (function (BABYLON) {
  31133. /**
  31134. * ActionEvent is the event beint sent when an action is triggered.
  31135. */
  31136. var ActionEvent = (function () {
  31137. /**
  31138. * @constructor
  31139. * @param source The mesh or sprite that triggered the action.
  31140. * @param pointerX The X mouse cursor position at the time of the event
  31141. * @param pointerY The Y mouse cursor position at the time of the event
  31142. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  31143. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  31144. */
  31145. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  31146. this.source = source;
  31147. this.pointerX = pointerX;
  31148. this.pointerY = pointerY;
  31149. this.meshUnderPointer = meshUnderPointer;
  31150. this.sourceEvent = sourceEvent;
  31151. this.additionalData = additionalData;
  31152. }
  31153. /**
  31154. * Helper function to auto-create an ActionEvent from a source mesh.
  31155. * @param source The source mesh that triggered the event
  31156. * @param evt {Event} The original (browser) event
  31157. */
  31158. ActionEvent.CreateNew = function (source, evt, additionalData) {
  31159. var scene = source.getScene();
  31160. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31161. };
  31162. /**
  31163. * Helper function to auto-create an ActionEvent from a source mesh.
  31164. * @param source The source sprite that triggered the event
  31165. * @param scene Scene associated with the sprite
  31166. * @param evt {Event} The original (browser) event
  31167. */
  31168. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  31169. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  31170. };
  31171. /**
  31172. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  31173. * @param scene the scene where the event occurred
  31174. * @param evt {Event} The original (browser) event
  31175. */
  31176. ActionEvent.CreateNewFromScene = function (scene, evt) {
  31177. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  31178. };
  31179. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  31180. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  31181. };
  31182. return ActionEvent;
  31183. })();
  31184. BABYLON.ActionEvent = ActionEvent;
  31185. /**
  31186. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  31187. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  31188. */
  31189. var ActionManager = (function () {
  31190. function ActionManager(scene) {
  31191. // Members
  31192. this.actions = new Array();
  31193. this._scene = scene;
  31194. scene._actionManagers.push(this);
  31195. }
  31196. Object.defineProperty(ActionManager, "NothingTrigger", {
  31197. get: function () {
  31198. return ActionManager._NothingTrigger;
  31199. },
  31200. enumerable: true,
  31201. configurable: true
  31202. });
  31203. Object.defineProperty(ActionManager, "OnPickTrigger", {
  31204. get: function () {
  31205. return ActionManager._OnPickTrigger;
  31206. },
  31207. enumerable: true,
  31208. configurable: true
  31209. });
  31210. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  31211. get: function () {
  31212. return ActionManager._OnLeftPickTrigger;
  31213. },
  31214. enumerable: true,
  31215. configurable: true
  31216. });
  31217. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  31218. get: function () {
  31219. return ActionManager._OnRightPickTrigger;
  31220. },
  31221. enumerable: true,
  31222. configurable: true
  31223. });
  31224. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  31225. get: function () {
  31226. return ActionManager._OnCenterPickTrigger;
  31227. },
  31228. enumerable: true,
  31229. configurable: true
  31230. });
  31231. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  31232. get: function () {
  31233. return ActionManager._OnPickDownTrigger;
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  31239. get: function () {
  31240. return ActionManager._OnPickUpTrigger;
  31241. },
  31242. enumerable: true,
  31243. configurable: true
  31244. });
  31245. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  31246. /// This trigger will only be raised if you also declared a OnPickDown
  31247. get: function () {
  31248. return ActionManager._OnPickOutTrigger;
  31249. },
  31250. enumerable: true,
  31251. configurable: true
  31252. });
  31253. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  31254. get: function () {
  31255. return ActionManager._OnLongPressTrigger;
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  31261. get: function () {
  31262. return ActionManager._OnPointerOverTrigger;
  31263. },
  31264. enumerable: true,
  31265. configurable: true
  31266. });
  31267. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  31268. get: function () {
  31269. return ActionManager._OnPointerOutTrigger;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  31275. get: function () {
  31276. return ActionManager._OnEveryFrameTrigger;
  31277. },
  31278. enumerable: true,
  31279. configurable: true
  31280. });
  31281. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  31282. get: function () {
  31283. return ActionManager._OnIntersectionEnterTrigger;
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  31289. get: function () {
  31290. return ActionManager._OnIntersectionExitTrigger;
  31291. },
  31292. enumerable: true,
  31293. configurable: true
  31294. });
  31295. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  31296. get: function () {
  31297. return ActionManager._OnKeyDownTrigger;
  31298. },
  31299. enumerable: true,
  31300. configurable: true
  31301. });
  31302. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  31303. get: function () {
  31304. return ActionManager._OnKeyUpTrigger;
  31305. },
  31306. enumerable: true,
  31307. configurable: true
  31308. });
  31309. // Methods
  31310. ActionManager.prototype.dispose = function () {
  31311. var index = this._scene._actionManagers.indexOf(this);
  31312. if (index > -1) {
  31313. this._scene._actionManagers.splice(index, 1);
  31314. }
  31315. };
  31316. ActionManager.prototype.getScene = function () {
  31317. return this._scene;
  31318. };
  31319. /**
  31320. * Does this action manager handles actions of any of the given triggers
  31321. * @param {number[]} triggers - the triggers to be tested
  31322. * @return {boolean} whether one (or more) of the triggers is handeled
  31323. */
  31324. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  31325. for (var index = 0; index < this.actions.length; index++) {
  31326. var action = this.actions[index];
  31327. if (triggers.indexOf(action.trigger) > -1) {
  31328. return true;
  31329. }
  31330. }
  31331. return false;
  31332. };
  31333. /**
  31334. * Does this action manager handles actions of a given trigger
  31335. * @param {number} trigger - the trigger to be tested
  31336. * @return {boolean} whether the trigger is handeled
  31337. */
  31338. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  31339. for (var index = 0; index < this.actions.length; index++) {
  31340. var action = this.actions[index];
  31341. if (action.trigger === trigger) {
  31342. return true;
  31343. }
  31344. }
  31345. return false;
  31346. };
  31347. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  31348. /**
  31349. * Does this action manager has pointer triggers
  31350. * @return {boolean} whether or not it has pointer triggers
  31351. */
  31352. get: function () {
  31353. for (var index = 0; index < this.actions.length; index++) {
  31354. var action = this.actions[index];
  31355. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  31356. return true;
  31357. }
  31358. }
  31359. return false;
  31360. },
  31361. enumerable: true,
  31362. configurable: true
  31363. });
  31364. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  31365. /**
  31366. * Does this action manager has pick triggers
  31367. * @return {boolean} whether or not it has pick triggers
  31368. */
  31369. get: function () {
  31370. for (var index = 0; index < this.actions.length; index++) {
  31371. var action = this.actions[index];
  31372. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  31373. return true;
  31374. }
  31375. }
  31376. return false;
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. /**
  31382. * Registers an action to this action manager
  31383. * @param {BABYLON.Action} action - the action to be registered
  31384. * @return {BABYLON.Action} the action amended (prepared) after registration
  31385. */
  31386. ActionManager.prototype.registerAction = function (action) {
  31387. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  31388. if (this.getScene().actionManager !== this) {
  31389. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  31390. return null;
  31391. }
  31392. }
  31393. this.actions.push(action);
  31394. action._actionManager = this;
  31395. action._prepare();
  31396. return action;
  31397. };
  31398. /**
  31399. * Process a specific trigger
  31400. * @param {number} trigger - the trigger to process
  31401. * @param evt {BABYLON.ActionEvent} the event details to be processed
  31402. */
  31403. ActionManager.prototype.processTrigger = function (trigger, evt) {
  31404. for (var index = 0; index < this.actions.length; index++) {
  31405. var action = this.actions[index];
  31406. if (action.trigger === trigger) {
  31407. if (trigger === ActionManager.OnKeyUpTrigger
  31408. || trigger === ActionManager.OnKeyDownTrigger) {
  31409. var parameter = action.getTriggerParameter();
  31410. if (parameter) {
  31411. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  31412. var actualkey = String.fromCharCode(unicode).toLowerCase();
  31413. if (actualkey !== parameter.toLowerCase()) {
  31414. continue;
  31415. }
  31416. }
  31417. }
  31418. action._executeCurrent(evt);
  31419. }
  31420. }
  31421. };
  31422. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  31423. var properties = propertyPath.split(".");
  31424. for (var index = 0; index < properties.length - 1; index++) {
  31425. target = target[properties[index]];
  31426. }
  31427. return target;
  31428. };
  31429. ActionManager.prototype._getProperty = function (propertyPath) {
  31430. var properties = propertyPath.split(".");
  31431. return properties[properties.length - 1];
  31432. };
  31433. ActionManager.prototype.serialize = function (name) {
  31434. var root = {
  31435. children: [],
  31436. name: name,
  31437. type: 3,
  31438. properties: [] // Empty for root but required
  31439. };
  31440. for (var i = 0; i < this.actions.length; i++) {
  31441. var triggerObject = {
  31442. type: 0,
  31443. children: [],
  31444. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  31445. properties: []
  31446. };
  31447. var triggerOptions = this.actions[i].triggerOptions;
  31448. if (triggerOptions && typeof triggerOptions !== "number") {
  31449. if (triggerOptions.parameter instanceof BABYLON.Node) {
  31450. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  31451. }
  31452. else {
  31453. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  31454. }
  31455. }
  31456. // Serialize child action, recursively
  31457. this.actions[i].serialize(triggerObject);
  31458. // Add serialized trigger
  31459. root.children.push(triggerObject);
  31460. }
  31461. return root;
  31462. };
  31463. ActionManager.Parse = function (parsedActions, object, scene) {
  31464. var actionManager = new BABYLON.ActionManager(scene);
  31465. if (object === null)
  31466. scene.actionManager = actionManager;
  31467. else
  31468. object.actionManager = actionManager;
  31469. // instanciate a new object
  31470. var instanciate = function (name, params) {
  31471. var newInstance = Object.create(BABYLON[name].prototype);
  31472. newInstance.constructor.apply(newInstance, params);
  31473. return newInstance;
  31474. };
  31475. var parseParameter = function (name, value, target, propertyPath) {
  31476. if (propertyPath === null) {
  31477. // String, boolean or float
  31478. var floatValue = parseFloat(value);
  31479. if (value === "true" || value === "false")
  31480. return value === "true";
  31481. else
  31482. return isNaN(floatValue) ? value : floatValue;
  31483. }
  31484. var effectiveTarget = propertyPath.split(".");
  31485. var values = value.split(",");
  31486. // Get effective Target
  31487. for (var i = 0; i < effectiveTarget.length; i++) {
  31488. target = target[effectiveTarget[i]];
  31489. }
  31490. // Return appropriate value with its type
  31491. if (typeof (target) === "boolean")
  31492. return values[0] === "true";
  31493. if (typeof (target) === "string")
  31494. return values[0];
  31495. // Parameters with multiple values such as Vector3 etc.
  31496. var split = new Array();
  31497. for (var i = 0; i < values.length; i++)
  31498. split.push(parseFloat(values[i]));
  31499. if (target instanceof BABYLON.Vector3)
  31500. return BABYLON.Vector3.FromArray(split);
  31501. if (target instanceof BABYLON.Vector4)
  31502. return BABYLON.Vector4.FromArray(split);
  31503. if (target instanceof BABYLON.Color3)
  31504. return BABYLON.Color3.FromArray(split);
  31505. if (target instanceof BABYLON.Color4)
  31506. return BABYLON.Color4.FromArray(split);
  31507. return parseFloat(values[0]);
  31508. };
  31509. // traverse graph per trigger
  31510. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  31511. if (combineArray === void 0) { combineArray = null; }
  31512. if (parsedAction.detached)
  31513. return;
  31514. var parameters = new Array();
  31515. var target = null;
  31516. var propertyPath = null;
  31517. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  31518. // Parameters
  31519. if (parsedAction.type === 2)
  31520. parameters.push(actionManager);
  31521. else
  31522. parameters.push(trigger);
  31523. if (combine) {
  31524. var actions = new Array();
  31525. for (var j = 0; j < parsedAction.combine.length; j++) {
  31526. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  31527. }
  31528. parameters.push(actions);
  31529. }
  31530. else {
  31531. for (var i = 0; i < parsedAction.properties.length; i++) {
  31532. var value = parsedAction.properties[i].value;
  31533. var name = parsedAction.properties[i].name;
  31534. var targetType = parsedAction.properties[i].targetType;
  31535. if (name === "target")
  31536. if (targetType !== null && targetType === "SceneProperties")
  31537. value = target = scene;
  31538. else
  31539. value = target = scene.getNodeByName(value);
  31540. else if (name === "parent")
  31541. value = scene.getNodeByName(value);
  31542. else if (name === "sound")
  31543. value = scene.getSoundByName(value);
  31544. else if (name !== "propertyPath") {
  31545. if (parsedAction.type === 2 && name === "operator")
  31546. value = BABYLON.ValueCondition[value];
  31547. else
  31548. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  31549. }
  31550. else {
  31551. propertyPath = value;
  31552. }
  31553. parameters.push(value);
  31554. }
  31555. }
  31556. if (combineArray === null) {
  31557. parameters.push(condition);
  31558. }
  31559. else {
  31560. parameters.push(null);
  31561. }
  31562. // If interpolate value action
  31563. if (parsedAction.name === "InterpolateValueAction") {
  31564. var param = parameters[parameters.length - 2];
  31565. parameters[parameters.length - 1] = param;
  31566. parameters[parameters.length - 2] = condition;
  31567. }
  31568. // Action or condition(s) and not CombineAction
  31569. var newAction = instanciate(parsedAction.name, parameters);
  31570. if (newAction instanceof BABYLON.Condition && condition !== null) {
  31571. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  31572. if (action)
  31573. action.then(nothing);
  31574. else
  31575. actionManager.registerAction(nothing);
  31576. action = nothing;
  31577. }
  31578. if (combineArray === null) {
  31579. if (newAction instanceof BABYLON.Condition) {
  31580. condition = newAction;
  31581. newAction = action;
  31582. }
  31583. else {
  31584. condition = null;
  31585. if (action)
  31586. action.then(newAction);
  31587. else
  31588. actionManager.registerAction(newAction);
  31589. }
  31590. }
  31591. else {
  31592. combineArray.push(newAction);
  31593. }
  31594. for (var i = 0; i < parsedAction.children.length; i++)
  31595. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  31596. };
  31597. // triggers
  31598. for (var i = 0; i < parsedActions.children.length; i++) {
  31599. var triggerParams;
  31600. var trigger = parsedActions.children[i];
  31601. if (trigger.properties.length > 0) {
  31602. var param = trigger.properties[0].value;
  31603. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  31604. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  31605. }
  31606. else
  31607. triggerParams = BABYLON.ActionManager[trigger.name];
  31608. for (var j = 0; j < trigger.children.length; j++) {
  31609. if (!trigger.detached)
  31610. traverse(trigger.children[j], triggerParams, null, null);
  31611. }
  31612. }
  31613. };
  31614. ActionManager.GetTriggerName = function (trigger) {
  31615. switch (trigger) {
  31616. case 0: return "NothingTrigger";
  31617. case 1: return "OnPickTrigger";
  31618. case 2: return "OnLeftPickTrigger";
  31619. case 3: return "OnRightPickTrigger";
  31620. case 4: return "OnCenterPickTrigger";
  31621. case 5: return "OnPickDownTrigger";
  31622. case 6: return "OnPickUpTrigger";
  31623. case 7: return "OnLongPressTrigger";
  31624. case 8: return "OnPointerOverTrigger";
  31625. case 9: return "OnPointerOutTrigger";
  31626. case 10: return "OnEveryFrameTrigger";
  31627. case 11: return "OnIntersectionEnterTrigger";
  31628. case 12: return "OnIntersectionExitTrigger";
  31629. case 13: return "OnKeyDownTrigger";
  31630. case 14: return "OnKeyUpTrigger";
  31631. case 15: return "OnPickOutTrigger";
  31632. default: return "";
  31633. }
  31634. };
  31635. // Statics
  31636. ActionManager._NothingTrigger = 0;
  31637. ActionManager._OnPickTrigger = 1;
  31638. ActionManager._OnLeftPickTrigger = 2;
  31639. ActionManager._OnRightPickTrigger = 3;
  31640. ActionManager._OnCenterPickTrigger = 4;
  31641. ActionManager._OnPickDownTrigger = 5;
  31642. ActionManager._OnPickUpTrigger = 6;
  31643. ActionManager._OnLongPressTrigger = 7;
  31644. ActionManager._OnPointerOverTrigger = 8;
  31645. ActionManager._OnPointerOutTrigger = 9;
  31646. ActionManager._OnEveryFrameTrigger = 10;
  31647. ActionManager._OnIntersectionEnterTrigger = 11;
  31648. ActionManager._OnIntersectionExitTrigger = 12;
  31649. ActionManager._OnKeyDownTrigger = 13;
  31650. ActionManager._OnKeyUpTrigger = 14;
  31651. ActionManager._OnPickOutTrigger = 15;
  31652. ActionManager.DragMovementThreshold = 10; // in pixels
  31653. ActionManager.LongPressDelay = 500; // in milliseconds
  31654. return ActionManager;
  31655. })();
  31656. BABYLON.ActionManager = ActionManager;
  31657. })(BABYLON || (BABYLON = {}));
  31658. var BABYLON;
  31659. (function (BABYLON) {
  31660. var InterpolateValueAction = (function (_super) {
  31661. __extends(InterpolateValueAction, _super);
  31662. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  31663. if (duration === void 0) { duration = 1000; }
  31664. _super.call(this, triggerOptions, condition);
  31665. this.propertyPath = propertyPath;
  31666. this.value = value;
  31667. this.duration = duration;
  31668. this.stopOtherAnimations = stopOtherAnimations;
  31669. this.onInterpolationDone = onInterpolationDone;
  31670. this._target = this._effectiveTarget = target;
  31671. }
  31672. InterpolateValueAction.prototype._prepare = function () {
  31673. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31674. this._property = this._getProperty(this.propertyPath);
  31675. };
  31676. InterpolateValueAction.prototype.execute = function () {
  31677. var scene = this._actionManager.getScene();
  31678. var keys = [
  31679. {
  31680. frame: 0,
  31681. value: this._effectiveTarget[this._property]
  31682. }, {
  31683. frame: 100,
  31684. value: this.value
  31685. }
  31686. ];
  31687. var dataType;
  31688. if (typeof this.value === "number") {
  31689. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  31690. }
  31691. else if (this.value instanceof BABYLON.Color3) {
  31692. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  31693. }
  31694. else if (this.value instanceof BABYLON.Vector3) {
  31695. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  31696. }
  31697. else if (this.value instanceof BABYLON.Matrix) {
  31698. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  31699. }
  31700. else if (this.value instanceof BABYLON.Quaternion) {
  31701. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  31702. }
  31703. else {
  31704. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  31705. return;
  31706. }
  31707. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  31708. animation.setKeys(keys);
  31709. if (this.stopOtherAnimations) {
  31710. scene.stopAnimation(this._effectiveTarget);
  31711. }
  31712. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  31713. };
  31714. InterpolateValueAction.prototype.serialize = function (parent) {
  31715. return _super.prototype._serialize.call(this, {
  31716. name: "InterpolateValueAction",
  31717. properties: [
  31718. BABYLON.Action._GetTargetProperty(this._target),
  31719. { name: "propertyPath", value: this.propertyPath },
  31720. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31721. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  31722. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  31723. ]
  31724. }, parent);
  31725. };
  31726. return InterpolateValueAction;
  31727. })(BABYLON.Action);
  31728. BABYLON.InterpolateValueAction = InterpolateValueAction;
  31729. })(BABYLON || (BABYLON = {}));
  31730. var BABYLON;
  31731. (function (BABYLON) {
  31732. var SwitchBooleanAction = (function (_super) {
  31733. __extends(SwitchBooleanAction, _super);
  31734. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  31735. _super.call(this, triggerOptions, condition);
  31736. this.propertyPath = propertyPath;
  31737. this._target = this._effectiveTarget = target;
  31738. }
  31739. SwitchBooleanAction.prototype._prepare = function () {
  31740. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31741. this._property = this._getProperty(this.propertyPath);
  31742. };
  31743. SwitchBooleanAction.prototype.execute = function () {
  31744. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  31745. };
  31746. SwitchBooleanAction.prototype.serialize = function (parent) {
  31747. return _super.prototype._serialize.call(this, {
  31748. name: "SwitchBooleanAction",
  31749. properties: [
  31750. BABYLON.Action._GetTargetProperty(this._target),
  31751. { name: "propertyPath", value: this.propertyPath }
  31752. ]
  31753. }, parent);
  31754. };
  31755. return SwitchBooleanAction;
  31756. })(BABYLON.Action);
  31757. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  31758. var SetStateAction = (function (_super) {
  31759. __extends(SetStateAction, _super);
  31760. function SetStateAction(triggerOptions, target, value, condition) {
  31761. _super.call(this, triggerOptions, condition);
  31762. this.value = value;
  31763. this._target = target;
  31764. }
  31765. SetStateAction.prototype.execute = function () {
  31766. this._target.state = this.value;
  31767. };
  31768. SetStateAction.prototype.serialize = function (parent) {
  31769. return _super.prototype._serialize.call(this, {
  31770. name: "SetStateAction",
  31771. properties: [
  31772. BABYLON.Action._GetTargetProperty(this._target),
  31773. { name: "value", value: this.value }
  31774. ]
  31775. }, parent);
  31776. };
  31777. return SetStateAction;
  31778. })(BABYLON.Action);
  31779. BABYLON.SetStateAction = SetStateAction;
  31780. var SetValueAction = (function (_super) {
  31781. __extends(SetValueAction, _super);
  31782. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  31783. _super.call(this, triggerOptions, condition);
  31784. this.propertyPath = propertyPath;
  31785. this.value = value;
  31786. this._target = this._effectiveTarget = target;
  31787. }
  31788. SetValueAction.prototype._prepare = function () {
  31789. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31790. this._property = this._getProperty(this.propertyPath);
  31791. };
  31792. SetValueAction.prototype.execute = function () {
  31793. this._effectiveTarget[this._property] = this.value;
  31794. if (this._target.markAsDirty) {
  31795. this._target.markAsDirty(this._property);
  31796. }
  31797. };
  31798. SetValueAction.prototype.serialize = function (parent) {
  31799. return _super.prototype._serialize.call(this, {
  31800. name: "SetValueAction",
  31801. properties: [
  31802. BABYLON.Action._GetTargetProperty(this._target),
  31803. { name: "propertyPath", value: this.propertyPath },
  31804. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31805. ]
  31806. }, parent);
  31807. };
  31808. return SetValueAction;
  31809. })(BABYLON.Action);
  31810. BABYLON.SetValueAction = SetValueAction;
  31811. var IncrementValueAction = (function (_super) {
  31812. __extends(IncrementValueAction, _super);
  31813. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  31814. _super.call(this, triggerOptions, condition);
  31815. this.propertyPath = propertyPath;
  31816. this.value = value;
  31817. this._target = this._effectiveTarget = target;
  31818. }
  31819. IncrementValueAction.prototype._prepare = function () {
  31820. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31821. this._property = this._getProperty(this.propertyPath);
  31822. if (typeof this._effectiveTarget[this._property] !== "number") {
  31823. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  31824. }
  31825. };
  31826. IncrementValueAction.prototype.execute = function () {
  31827. this._effectiveTarget[this._property] += this.value;
  31828. if (this._target.markAsDirty) {
  31829. this._target.markAsDirty(this._property);
  31830. }
  31831. };
  31832. IncrementValueAction.prototype.serialize = function (parent) {
  31833. return _super.prototype._serialize.call(this, {
  31834. name: "IncrementValueAction",
  31835. properties: [
  31836. BABYLON.Action._GetTargetProperty(this._target),
  31837. { name: "propertyPath", value: this.propertyPath },
  31838. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31839. ]
  31840. }, parent);
  31841. };
  31842. return IncrementValueAction;
  31843. })(BABYLON.Action);
  31844. BABYLON.IncrementValueAction = IncrementValueAction;
  31845. var PlayAnimationAction = (function (_super) {
  31846. __extends(PlayAnimationAction, _super);
  31847. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  31848. _super.call(this, triggerOptions, condition);
  31849. this.from = from;
  31850. this.to = to;
  31851. this.loop = loop;
  31852. this._target = target;
  31853. }
  31854. PlayAnimationAction.prototype._prepare = function () {
  31855. };
  31856. PlayAnimationAction.prototype.execute = function () {
  31857. var scene = this._actionManager.getScene();
  31858. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  31859. };
  31860. PlayAnimationAction.prototype.serialize = function (parent) {
  31861. return _super.prototype._serialize.call(this, {
  31862. name: "PlayAnimationAction",
  31863. properties: [
  31864. BABYLON.Action._GetTargetProperty(this._target),
  31865. { name: "from", value: String(this.from) },
  31866. { name: "to", value: String(this.to) },
  31867. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  31868. ]
  31869. }, parent);
  31870. };
  31871. return PlayAnimationAction;
  31872. })(BABYLON.Action);
  31873. BABYLON.PlayAnimationAction = PlayAnimationAction;
  31874. var StopAnimationAction = (function (_super) {
  31875. __extends(StopAnimationAction, _super);
  31876. function StopAnimationAction(triggerOptions, target, condition) {
  31877. _super.call(this, triggerOptions, condition);
  31878. this._target = target;
  31879. }
  31880. StopAnimationAction.prototype._prepare = function () {
  31881. };
  31882. StopAnimationAction.prototype.execute = function () {
  31883. var scene = this._actionManager.getScene();
  31884. scene.stopAnimation(this._target);
  31885. };
  31886. StopAnimationAction.prototype.serialize = function (parent) {
  31887. return _super.prototype._serialize.call(this, {
  31888. name: "StopAnimationAction",
  31889. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  31890. }, parent);
  31891. };
  31892. return StopAnimationAction;
  31893. })(BABYLON.Action);
  31894. BABYLON.StopAnimationAction = StopAnimationAction;
  31895. var DoNothingAction = (function (_super) {
  31896. __extends(DoNothingAction, _super);
  31897. function DoNothingAction(triggerOptions, condition) {
  31898. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  31899. _super.call(this, triggerOptions, condition);
  31900. }
  31901. DoNothingAction.prototype.execute = function () {
  31902. };
  31903. DoNothingAction.prototype.serialize = function (parent) {
  31904. return _super.prototype._serialize.call(this, {
  31905. name: "DoNothingAction",
  31906. properties: []
  31907. }, parent);
  31908. };
  31909. return DoNothingAction;
  31910. })(BABYLON.Action);
  31911. BABYLON.DoNothingAction = DoNothingAction;
  31912. var CombineAction = (function (_super) {
  31913. __extends(CombineAction, _super);
  31914. function CombineAction(triggerOptions, children, condition) {
  31915. _super.call(this, triggerOptions, condition);
  31916. this.children = children;
  31917. }
  31918. CombineAction.prototype._prepare = function () {
  31919. for (var index = 0; index < this.children.length; index++) {
  31920. this.children[index]._actionManager = this._actionManager;
  31921. this.children[index]._prepare();
  31922. }
  31923. };
  31924. CombineAction.prototype.execute = function (evt) {
  31925. for (var index = 0; index < this.children.length; index++) {
  31926. this.children[index].execute(evt);
  31927. }
  31928. };
  31929. CombineAction.prototype.serialize = function (parent) {
  31930. var serializationObject = _super.prototype._serialize.call(this, {
  31931. name: "CombineAction",
  31932. properties: [],
  31933. combine: []
  31934. }, parent);
  31935. for (var i = 0; i < this.children.length; i++) {
  31936. serializationObject.combine.push(this.children[i].serialize(null));
  31937. }
  31938. return serializationObject;
  31939. };
  31940. return CombineAction;
  31941. })(BABYLON.Action);
  31942. BABYLON.CombineAction = CombineAction;
  31943. var ExecuteCodeAction = (function (_super) {
  31944. __extends(ExecuteCodeAction, _super);
  31945. function ExecuteCodeAction(triggerOptions, func, condition) {
  31946. _super.call(this, triggerOptions, condition);
  31947. this.func = func;
  31948. }
  31949. ExecuteCodeAction.prototype.execute = function (evt) {
  31950. this.func(evt);
  31951. };
  31952. return ExecuteCodeAction;
  31953. })(BABYLON.Action);
  31954. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  31955. var SetParentAction = (function (_super) {
  31956. __extends(SetParentAction, _super);
  31957. function SetParentAction(triggerOptions, target, parent, condition) {
  31958. _super.call(this, triggerOptions, condition);
  31959. this._target = target;
  31960. this._parent = parent;
  31961. }
  31962. SetParentAction.prototype._prepare = function () {
  31963. };
  31964. SetParentAction.prototype.execute = function () {
  31965. if (this._target.parent === this._parent) {
  31966. return;
  31967. }
  31968. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  31969. invertParentWorldMatrix.invert();
  31970. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  31971. this._target.parent = this._parent;
  31972. };
  31973. SetParentAction.prototype.serialize = function (parent) {
  31974. return _super.prototype._serialize.call(this, {
  31975. name: "SetParentAction",
  31976. properties: [
  31977. BABYLON.Action._GetTargetProperty(this._target),
  31978. BABYLON.Action._GetTargetProperty(this._parent),
  31979. ]
  31980. }, parent);
  31981. };
  31982. return SetParentAction;
  31983. })(BABYLON.Action);
  31984. BABYLON.SetParentAction = SetParentAction;
  31985. var PlaySoundAction = (function (_super) {
  31986. __extends(PlaySoundAction, _super);
  31987. function PlaySoundAction(triggerOptions, sound, condition) {
  31988. _super.call(this, triggerOptions, condition);
  31989. this._sound = sound;
  31990. }
  31991. PlaySoundAction.prototype._prepare = function () {
  31992. };
  31993. PlaySoundAction.prototype.execute = function () {
  31994. if (this._sound !== undefined)
  31995. this._sound.play();
  31996. };
  31997. PlaySoundAction.prototype.serialize = function (parent) {
  31998. return _super.prototype._serialize.call(this, {
  31999. name: "PlaySoundAction",
  32000. properties: [{ name: "sound", value: this._sound.name }]
  32001. }, parent);
  32002. };
  32003. return PlaySoundAction;
  32004. })(BABYLON.Action);
  32005. BABYLON.PlaySoundAction = PlaySoundAction;
  32006. var StopSoundAction = (function (_super) {
  32007. __extends(StopSoundAction, _super);
  32008. function StopSoundAction(triggerOptions, sound, condition) {
  32009. _super.call(this, triggerOptions, condition);
  32010. this._sound = sound;
  32011. }
  32012. StopSoundAction.prototype._prepare = function () {
  32013. };
  32014. StopSoundAction.prototype.execute = function () {
  32015. if (this._sound !== undefined)
  32016. this._sound.stop();
  32017. };
  32018. StopSoundAction.prototype.serialize = function (parent) {
  32019. return _super.prototype._serialize.call(this, {
  32020. name: "StopSoundAction",
  32021. properties: [{ name: "sound", value: this._sound.name }]
  32022. }, parent);
  32023. };
  32024. return StopSoundAction;
  32025. })(BABYLON.Action);
  32026. BABYLON.StopSoundAction = StopSoundAction;
  32027. })(BABYLON || (BABYLON = {}));
  32028. var BABYLON;
  32029. (function (BABYLON) {
  32030. var Geometry = (function () {
  32031. function Geometry(id, scene, vertexData, updatable, mesh) {
  32032. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32033. this._totalVertices = 0;
  32034. this._isDisposed = false;
  32035. this.id = id;
  32036. this._engine = scene.getEngine();
  32037. this._meshes = [];
  32038. this._scene = scene;
  32039. //Init vertex buffer cache
  32040. this._vertexBuffers = {};
  32041. this._indices = [];
  32042. // vertexData
  32043. if (vertexData) {
  32044. this.setAllVerticesData(vertexData, updatable);
  32045. }
  32046. else {
  32047. this._totalVertices = 0;
  32048. this._indices = [];
  32049. }
  32050. // applyToMesh
  32051. if (mesh) {
  32052. if (mesh instanceof BABYLON.LinesMesh) {
  32053. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32054. this.updateExtend();
  32055. }
  32056. this.applyToMesh(mesh);
  32057. mesh.computeWorldMatrix(true);
  32058. }
  32059. }
  32060. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32061. /**
  32062. * 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
  32063. * @returns The Bias Vector
  32064. */
  32065. get: function () {
  32066. return this._boundingBias;
  32067. },
  32068. set: function (value) {
  32069. if (this._boundingBias && this._boundingBias.equals(value)) {
  32070. return;
  32071. }
  32072. this._boundingBias = value.clone();
  32073. this.updateBoundingInfo(true, null);
  32074. },
  32075. enumerable: true,
  32076. configurable: true
  32077. });
  32078. Object.defineProperty(Geometry.prototype, "extend", {
  32079. get: function () {
  32080. return this._extend;
  32081. },
  32082. enumerable: true,
  32083. configurable: true
  32084. });
  32085. Geometry.prototype.getScene = function () {
  32086. return this._scene;
  32087. };
  32088. Geometry.prototype.getEngine = function () {
  32089. return this._engine;
  32090. };
  32091. Geometry.prototype.isReady = function () {
  32092. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32093. };
  32094. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32095. vertexData.applyToGeometry(this, updatable);
  32096. this.notifyUpdate();
  32097. };
  32098. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32099. if (this._vertexBuffers[kind]) {
  32100. this._vertexBuffers[kind].dispose();
  32101. }
  32102. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32103. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32104. stride = this._vertexBuffers[kind].getStrideSize();
  32105. this._totalVertices = data.length / stride;
  32106. this.updateExtend(data);
  32107. var meshes = this._meshes;
  32108. var numOfMeshes = meshes.length;
  32109. for (var index = 0; index < numOfMeshes; index++) {
  32110. var mesh = meshes[index];
  32111. mesh._resetPointsArrayCache();
  32112. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32113. mesh._createGlobalSubMesh();
  32114. mesh.computeWorldMatrix(true);
  32115. }
  32116. }
  32117. this.notifyUpdate(kind);
  32118. };
  32119. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32120. var vertexBuffer = this.getVertexBuffer(kind);
  32121. if (!vertexBuffer) {
  32122. return;
  32123. }
  32124. vertexBuffer.updateDirectly(data, offset);
  32125. this.notifyUpdate(kind);
  32126. };
  32127. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32128. var vertexBuffer = this.getVertexBuffer(kind);
  32129. if (!vertexBuffer) {
  32130. return;
  32131. }
  32132. vertexBuffer.update(data);
  32133. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32134. var stride = vertexBuffer.getStrideSize();
  32135. this._totalVertices = data.length / stride;
  32136. this.updateBoundingInfo(updateExtends, data);
  32137. }
  32138. this.notifyUpdate(kind);
  32139. };
  32140. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32141. if (updateExtends) {
  32142. this.updateExtend(data);
  32143. }
  32144. var meshes = this._meshes;
  32145. var numOfMeshes = meshes.length;
  32146. for (var index = 0; index < numOfMeshes; index++) {
  32147. var mesh = meshes[index];
  32148. mesh._resetPointsArrayCache();
  32149. if (updateExtends) {
  32150. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32151. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32152. var subMesh = mesh.subMeshes[subIndex];
  32153. subMesh.refreshBoundingInfo();
  32154. }
  32155. }
  32156. }
  32157. };
  32158. Geometry.prototype.getTotalVertices = function () {
  32159. if (!this.isReady()) {
  32160. return 0;
  32161. }
  32162. return this._totalVertices;
  32163. };
  32164. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  32165. var vertexBuffer = this.getVertexBuffer(kind);
  32166. if (!vertexBuffer) {
  32167. return null;
  32168. }
  32169. var orig = vertexBuffer.getData();
  32170. if (!copyWhenShared || this._meshes.length === 1) {
  32171. return orig;
  32172. }
  32173. else {
  32174. var len = orig.length;
  32175. var copy = [];
  32176. for (var i = 0; i < len; i++) {
  32177. copy.push(orig[i]);
  32178. }
  32179. return copy;
  32180. }
  32181. };
  32182. Geometry.prototype.getVertexBuffer = function (kind) {
  32183. if (!this.isReady()) {
  32184. return null;
  32185. }
  32186. return this._vertexBuffers[kind];
  32187. };
  32188. Geometry.prototype.getVertexBuffers = function () {
  32189. if (!this.isReady()) {
  32190. return null;
  32191. }
  32192. return this._vertexBuffers;
  32193. };
  32194. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32195. if (!this._vertexBuffers) {
  32196. if (this._delayInfo) {
  32197. return this._delayInfo.indexOf(kind) !== -1;
  32198. }
  32199. return false;
  32200. }
  32201. return this._vertexBuffers[kind] !== undefined;
  32202. };
  32203. Geometry.prototype.getVerticesDataKinds = function () {
  32204. var result = [];
  32205. var kind;
  32206. if (!this._vertexBuffers && this._delayInfo) {
  32207. for (kind in this._delayInfo) {
  32208. result.push(kind);
  32209. }
  32210. }
  32211. else {
  32212. for (kind in this._vertexBuffers) {
  32213. result.push(kind);
  32214. }
  32215. }
  32216. return result;
  32217. };
  32218. Geometry.prototype.setIndices = function (indices, totalVertices) {
  32219. if (this._indexBuffer) {
  32220. this._engine._releaseBuffer(this._indexBuffer);
  32221. }
  32222. this._indices = indices;
  32223. if (this._meshes.length !== 0 && this._indices) {
  32224. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32225. }
  32226. if (totalVertices !== undefined) {
  32227. this._totalVertices = totalVertices;
  32228. }
  32229. var meshes = this._meshes;
  32230. var numOfMeshes = meshes.length;
  32231. for (var index = 0; index < numOfMeshes; index++) {
  32232. meshes[index]._createGlobalSubMesh();
  32233. }
  32234. this.notifyUpdate();
  32235. };
  32236. Geometry.prototype.getTotalIndices = function () {
  32237. if (!this.isReady()) {
  32238. return 0;
  32239. }
  32240. return this._indices.length;
  32241. };
  32242. Geometry.prototype.getIndices = function (copyWhenShared) {
  32243. if (!this.isReady()) {
  32244. return null;
  32245. }
  32246. var orig = this._indices;
  32247. if (!copyWhenShared || this._meshes.length === 1) {
  32248. return orig;
  32249. }
  32250. else {
  32251. var len = orig.length;
  32252. var copy = [];
  32253. for (var i = 0; i < len; i++) {
  32254. copy.push(orig[i]);
  32255. }
  32256. return copy;
  32257. }
  32258. };
  32259. Geometry.prototype.getIndexBuffer = function () {
  32260. if (!this.isReady()) {
  32261. return null;
  32262. }
  32263. return this._indexBuffer;
  32264. };
  32265. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32266. var meshes = this._meshes;
  32267. var index = meshes.indexOf(mesh);
  32268. if (index === -1) {
  32269. return;
  32270. }
  32271. for (var kind in this._vertexBuffers) {
  32272. this._vertexBuffers[kind].dispose();
  32273. }
  32274. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  32275. this._indexBuffer = null;
  32276. }
  32277. meshes.splice(index, 1);
  32278. mesh._geometry = null;
  32279. if (meshes.length === 0 && shouldDispose) {
  32280. this.dispose();
  32281. }
  32282. };
  32283. Geometry.prototype.applyToMesh = function (mesh) {
  32284. if (mesh._geometry === this) {
  32285. return;
  32286. }
  32287. var previousGeometry = mesh._geometry;
  32288. if (previousGeometry) {
  32289. previousGeometry.releaseForMesh(mesh);
  32290. }
  32291. var meshes = this._meshes;
  32292. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32293. mesh._geometry = this;
  32294. this._scene.pushGeometry(this);
  32295. meshes.push(mesh);
  32296. if (this.isReady()) {
  32297. this._applyToMesh(mesh);
  32298. }
  32299. else {
  32300. mesh._boundingInfo = this._boundingInfo;
  32301. }
  32302. };
  32303. Geometry.prototype.updateExtend = function (data) {
  32304. if (data === void 0) { data = null; }
  32305. if (!data) {
  32306. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32307. }
  32308. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  32309. };
  32310. Geometry.prototype._applyToMesh = function (mesh) {
  32311. var numOfMeshes = this._meshes.length;
  32312. // vertexBuffers
  32313. for (var kind in this._vertexBuffers) {
  32314. if (numOfMeshes === 1) {
  32315. this._vertexBuffers[kind].create();
  32316. }
  32317. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  32318. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32319. mesh._resetPointsArrayCache();
  32320. if (!this._extend) {
  32321. this.updateExtend(this._vertexBuffers[kind].getData());
  32322. }
  32323. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32324. mesh._createGlobalSubMesh();
  32325. //bounding info was just created again, world matrix should be applied again.
  32326. mesh._updateBoundingInfo();
  32327. }
  32328. }
  32329. // indexBuffer
  32330. if (numOfMeshes === 1 && this._indices) {
  32331. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32332. }
  32333. if (this._indexBuffer) {
  32334. this._indexBuffer.references = numOfMeshes;
  32335. }
  32336. };
  32337. Geometry.prototype.notifyUpdate = function (kind) {
  32338. if (this.onGeometryUpdated) {
  32339. this.onGeometryUpdated(this, kind);
  32340. }
  32341. };
  32342. Geometry.prototype.load = function (scene, onLoaded) {
  32343. var _this = this;
  32344. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32345. return;
  32346. }
  32347. if (this.isReady()) {
  32348. if (onLoaded) {
  32349. onLoaded();
  32350. }
  32351. return;
  32352. }
  32353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32354. scene._addPendingData(this);
  32355. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32356. _this._delayLoadingFunction(JSON.parse(data), _this);
  32357. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32358. _this._delayInfo = [];
  32359. scene._removePendingData(_this);
  32360. var meshes = _this._meshes;
  32361. var numOfMeshes = meshes.length;
  32362. for (var index = 0; index < numOfMeshes; index++) {
  32363. _this._applyToMesh(meshes[index]);
  32364. }
  32365. if (onLoaded) {
  32366. onLoaded();
  32367. }
  32368. }, function () { }, scene.database);
  32369. };
  32370. Geometry.prototype.isDisposed = function () {
  32371. return this._isDisposed;
  32372. };
  32373. Geometry.prototype.dispose = function () {
  32374. var meshes = this._meshes;
  32375. var numOfMeshes = meshes.length;
  32376. var index;
  32377. for (index = 0; index < numOfMeshes; index++) {
  32378. this.releaseForMesh(meshes[index]);
  32379. }
  32380. this._meshes = [];
  32381. for (var kind in this._vertexBuffers) {
  32382. this._vertexBuffers[kind].dispose();
  32383. }
  32384. this._vertexBuffers = [];
  32385. this._totalVertices = 0;
  32386. if (this._indexBuffer) {
  32387. this._engine._releaseBuffer(this._indexBuffer);
  32388. }
  32389. this._indexBuffer = null;
  32390. this._indices = [];
  32391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32392. this.delayLoadingFile = null;
  32393. this._delayLoadingFunction = null;
  32394. this._delayInfo = [];
  32395. this._boundingInfo = null;
  32396. this._scene.removeGeometry(this);
  32397. this._isDisposed = true;
  32398. };
  32399. Geometry.prototype.copy = function (id) {
  32400. var vertexData = new BABYLON.VertexData();
  32401. vertexData.indices = [];
  32402. var indices = this.getIndices();
  32403. for (var index = 0; index < indices.length; index++) {
  32404. vertexData.indices.push(indices[index]);
  32405. }
  32406. var updatable = false;
  32407. var stopChecking = false;
  32408. var kind;
  32409. for (kind in this._vertexBuffers) {
  32410. // using slice() to make a copy of the array and not just reference it
  32411. var data = this.getVerticesData(kind);
  32412. if (data instanceof Float32Array) {
  32413. vertexData.set(new Float32Array(data), kind);
  32414. }
  32415. else {
  32416. vertexData.set(data.slice(0), kind);
  32417. }
  32418. if (!stopChecking) {
  32419. updatable = this.getVertexBuffer(kind).isUpdatable();
  32420. stopChecking = !updatable;
  32421. }
  32422. }
  32423. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  32424. geometry.delayLoadState = this.delayLoadState;
  32425. geometry.delayLoadingFile = this.delayLoadingFile;
  32426. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32427. for (kind in this._delayInfo) {
  32428. geometry._delayInfo = geometry._delayInfo || [];
  32429. geometry._delayInfo.push(kind);
  32430. }
  32431. // Bounding info
  32432. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32433. return geometry;
  32434. };
  32435. Geometry.prototype.serialize = function () {
  32436. var serializationObject = {};
  32437. serializationObject.id = this.id;
  32438. if (BABYLON.Tags.HasTags(this)) {
  32439. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32440. }
  32441. return serializationObject;
  32442. };
  32443. Geometry.prototype.serializeVerticeData = function () {
  32444. var serializationObject = this.serialize();
  32445. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32446. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32447. }
  32448. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32449. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32450. }
  32451. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32452. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32453. }
  32454. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32455. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  32456. }
  32457. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32458. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  32459. }
  32460. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32461. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  32462. }
  32463. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32464. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  32465. }
  32466. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32467. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  32468. }
  32469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32470. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32471. }
  32472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32473. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32474. serializationObject.matricesIndices._isExpanded = true;
  32475. }
  32476. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32477. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32478. }
  32479. serializationObject.indices = this.getIndices();
  32480. return serializationObject;
  32481. };
  32482. // Statics
  32483. Geometry.ExtractFromMesh = function (mesh, id) {
  32484. var geometry = mesh._geometry;
  32485. if (!geometry) {
  32486. return null;
  32487. }
  32488. return geometry.copy(id);
  32489. };
  32490. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32491. // be aware Math.random() could cause collisions
  32492. Geometry.RandomId = function () {
  32493. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  32494. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  32495. return v.toString(16);
  32496. });
  32497. };
  32498. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32499. var scene = mesh.getScene();
  32500. // Geometry
  32501. var geometryId = parsedGeometry.geometryId;
  32502. if (geometryId) {
  32503. var geometry = scene.getGeometryByID(geometryId);
  32504. if (geometry) {
  32505. geometry.applyToMesh(mesh);
  32506. }
  32507. }
  32508. else if (parsedGeometry instanceof ArrayBuffer) {
  32509. var binaryInfo = mesh._binaryInfo;
  32510. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32511. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32512. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32513. }
  32514. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32515. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32516. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32517. }
  32518. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32519. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32520. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32521. }
  32522. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32523. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32524. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32525. }
  32526. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32527. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32528. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32529. }
  32530. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32531. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32532. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32533. }
  32534. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32535. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32536. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32537. }
  32538. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32539. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32540. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32541. }
  32542. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32543. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32544. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32545. }
  32546. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32547. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32549. }
  32550. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32551. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32552. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32553. }
  32554. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32555. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32556. mesh.setIndices(indicesData);
  32557. }
  32558. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32559. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32560. mesh.subMeshes = [];
  32561. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32562. var materialIndex = subMeshesData[(i * 5) + 0];
  32563. var verticesStart = subMeshesData[(i * 5) + 1];
  32564. var verticesCount = subMeshesData[(i * 5) + 2];
  32565. var indexStart = subMeshesData[(i * 5) + 3];
  32566. var indexCount = subMeshesData[(i * 5) + 4];
  32567. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32568. }
  32569. }
  32570. }
  32571. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32572. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  32573. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  32574. if (parsedGeometry.uvs) {
  32575. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  32576. }
  32577. if (parsedGeometry.uvs2) {
  32578. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  32579. }
  32580. if (parsedGeometry.uvs3) {
  32581. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  32582. }
  32583. if (parsedGeometry.uvs4) {
  32584. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  32585. }
  32586. if (parsedGeometry.uvs5) {
  32587. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  32588. }
  32589. if (parsedGeometry.uvs6) {
  32590. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  32591. }
  32592. if (parsedGeometry.colors) {
  32593. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  32594. }
  32595. if (parsedGeometry.matricesIndices) {
  32596. if (!parsedGeometry.matricesIndices._isExpanded) {
  32597. var floatIndices = [];
  32598. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32599. var matricesIndex = parsedGeometry.matricesIndices[i];
  32600. floatIndices.push(matricesIndex & 0x000000FF);
  32601. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32602. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32603. floatIndices.push(matricesIndex >> 24);
  32604. }
  32605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  32606. }
  32607. else {
  32608. delete parsedGeometry.matricesIndices._isExpanded;
  32609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  32610. }
  32611. }
  32612. if (parsedGeometry.matricesIndicesExtra) {
  32613. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32614. var floatIndices = [];
  32615. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32616. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32617. floatIndices.push(matricesIndex & 0x000000FF);
  32618. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32619. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32620. floatIndices.push(matricesIndex >> 24);
  32621. }
  32622. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  32623. }
  32624. else {
  32625. delete parsedGeometry.matricesIndices._isExpanded;
  32626. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  32627. }
  32628. }
  32629. if (parsedGeometry.matricesWeights) {
  32630. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  32631. }
  32632. if (parsedGeometry.matricesWeightsExtra) {
  32633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  32634. }
  32635. mesh.setIndices(parsedGeometry.indices);
  32636. }
  32637. // SubMeshes
  32638. if (parsedGeometry.subMeshes) {
  32639. mesh.subMeshes = [];
  32640. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32641. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32642. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32643. }
  32644. }
  32645. // Flat shading
  32646. if (mesh._shouldGenerateFlatShading) {
  32647. mesh.convertToFlatShadedMesh();
  32648. delete mesh._shouldGenerateFlatShading;
  32649. }
  32650. // Update
  32651. mesh.computeWorldMatrix(true);
  32652. // Octree
  32653. if (scene['_selectionOctree']) {
  32654. scene['_selectionOctree'].addMesh(mesh);
  32655. }
  32656. };
  32657. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32658. if (scene.getGeometryByID(parsedVertexData.id)) {
  32659. return null; // null since geometry could be something else than a box...
  32660. }
  32661. var geometry = new Geometry(parsedVertexData.id, scene);
  32662. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32663. if (parsedVertexData.delayLoadingFile) {
  32664. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32665. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32666. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32667. geometry._delayInfo = [];
  32668. if (parsedVertexData.hasUVs) {
  32669. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32670. }
  32671. if (parsedVertexData.hasUVs2) {
  32672. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32673. }
  32674. if (parsedVertexData.hasUVs3) {
  32675. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32676. }
  32677. if (parsedVertexData.hasUVs4) {
  32678. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32679. }
  32680. if (parsedVertexData.hasUVs5) {
  32681. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32682. }
  32683. if (parsedVertexData.hasUVs6) {
  32684. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32685. }
  32686. if (parsedVertexData.hasColors) {
  32687. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32688. }
  32689. if (parsedVertexData.hasMatricesIndices) {
  32690. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32691. }
  32692. if (parsedVertexData.hasMatricesWeights) {
  32693. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32694. }
  32695. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32696. }
  32697. else {
  32698. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32699. }
  32700. scene.pushGeometry(geometry, true);
  32701. return geometry;
  32702. };
  32703. return Geometry;
  32704. })();
  32705. BABYLON.Geometry = Geometry;
  32706. /////// Primitives //////////////////////////////////////////////
  32707. var Geometry;
  32708. (function (Geometry) {
  32709. var Primitives;
  32710. (function (Primitives) {
  32711. /// Abstract class
  32712. var _Primitive = (function (_super) {
  32713. __extends(_Primitive, _super);
  32714. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32715. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  32716. this._canBeRegenerated = _canBeRegenerated;
  32717. this._beingRegenerated = true;
  32718. this.regenerate();
  32719. this._beingRegenerated = false;
  32720. }
  32721. _Primitive.prototype.canBeRegenerated = function () {
  32722. return this._canBeRegenerated;
  32723. };
  32724. _Primitive.prototype.regenerate = function () {
  32725. if (!this._canBeRegenerated) {
  32726. return;
  32727. }
  32728. this._beingRegenerated = true;
  32729. this.setAllVerticesData(this._regenerateVertexData(), false);
  32730. this._beingRegenerated = false;
  32731. };
  32732. _Primitive.prototype.asNewGeometry = function (id) {
  32733. return _super.prototype.copy.call(this, id);
  32734. };
  32735. // overrides
  32736. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32737. if (!this._beingRegenerated) {
  32738. return;
  32739. }
  32740. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32741. };
  32742. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32743. if (!this._beingRegenerated) {
  32744. return;
  32745. }
  32746. _super.prototype.setVerticesData.call(this, kind, data, false);
  32747. };
  32748. // to override
  32749. // protected
  32750. _Primitive.prototype._regenerateVertexData = function () {
  32751. throw new Error("Abstract method");
  32752. };
  32753. _Primitive.prototype.copy = function (id) {
  32754. throw new Error("Must be overriden in sub-classes.");
  32755. };
  32756. _Primitive.prototype.serialize = function () {
  32757. var serializationObject = _super.prototype.serialize.call(this);
  32758. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32759. return serializationObject;
  32760. };
  32761. return _Primitive;
  32762. })(Geometry);
  32763. Primitives._Primitive = _Primitive;
  32764. var Ribbon = (function (_super) {
  32765. __extends(Ribbon, _super);
  32766. // Members
  32767. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32768. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32769. _super.call(this, id, scene, canBeRegenerated, mesh);
  32770. this.pathArray = pathArray;
  32771. this.closeArray = closeArray;
  32772. this.closePath = closePath;
  32773. this.offset = offset;
  32774. this.side = side;
  32775. }
  32776. Ribbon.prototype._regenerateVertexData = function () {
  32777. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32778. };
  32779. Ribbon.prototype.copy = function (id) {
  32780. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  32781. };
  32782. return Ribbon;
  32783. })(_Primitive);
  32784. Primitives.Ribbon = Ribbon;
  32785. var Box = (function (_super) {
  32786. __extends(Box, _super);
  32787. // Members
  32788. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32789. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32790. _super.call(this, id, scene, canBeRegenerated, mesh);
  32791. this.size = size;
  32792. this.side = side;
  32793. }
  32794. Box.prototype._regenerateVertexData = function () {
  32795. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32796. };
  32797. Box.prototype.copy = function (id) {
  32798. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32799. };
  32800. Box.prototype.serialize = function () {
  32801. var serializationObject = _super.prototype.serialize.call(this);
  32802. serializationObject.size = this.size;
  32803. return serializationObject;
  32804. };
  32805. Box.Parse = function (parsedBox, scene) {
  32806. if (scene.getGeometryByID(parsedBox.id)) {
  32807. return null; // null since geometry could be something else than a box...
  32808. }
  32809. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32810. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32811. scene.pushGeometry(box, true);
  32812. return box;
  32813. };
  32814. return Box;
  32815. })(_Primitive);
  32816. Primitives.Box = Box;
  32817. var Sphere = (function (_super) {
  32818. __extends(Sphere, _super);
  32819. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32821. _super.call(this, id, scene, canBeRegenerated, mesh);
  32822. this.segments = segments;
  32823. this.diameter = diameter;
  32824. this.side = side;
  32825. }
  32826. Sphere.prototype._regenerateVertexData = function () {
  32827. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32828. };
  32829. Sphere.prototype.copy = function (id) {
  32830. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32831. };
  32832. Sphere.prototype.serialize = function () {
  32833. var serializationObject = _super.prototype.serialize.call(this);
  32834. serializationObject.segments = this.segments;
  32835. serializationObject.diameter = this.diameter;
  32836. return serializationObject;
  32837. };
  32838. Sphere.Parse = function (parsedSphere, scene) {
  32839. if (scene.getGeometryByID(parsedSphere.id)) {
  32840. return null; // null since geometry could be something else than a sphere...
  32841. }
  32842. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32843. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32844. scene.pushGeometry(sphere, true);
  32845. return sphere;
  32846. };
  32847. return Sphere;
  32848. })(_Primitive);
  32849. Primitives.Sphere = Sphere;
  32850. var Disc = (function (_super) {
  32851. __extends(Disc, _super);
  32852. // Members
  32853. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32854. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32855. _super.call(this, id, scene, canBeRegenerated, mesh);
  32856. this.radius = radius;
  32857. this.tessellation = tessellation;
  32858. this.side = side;
  32859. }
  32860. Disc.prototype._regenerateVertexData = function () {
  32861. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32862. };
  32863. Disc.prototype.copy = function (id) {
  32864. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32865. };
  32866. return Disc;
  32867. })(_Primitive);
  32868. Primitives.Disc = Disc;
  32869. var Cylinder = (function (_super) {
  32870. __extends(Cylinder, _super);
  32871. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32872. if (subdivisions === void 0) { subdivisions = 1; }
  32873. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32874. _super.call(this, id, scene, canBeRegenerated, mesh);
  32875. this.height = height;
  32876. this.diameterTop = diameterTop;
  32877. this.diameterBottom = diameterBottom;
  32878. this.tessellation = tessellation;
  32879. this.subdivisions = subdivisions;
  32880. this.side = side;
  32881. }
  32882. Cylinder.prototype._regenerateVertexData = function () {
  32883. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32884. };
  32885. Cylinder.prototype.copy = function (id) {
  32886. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32887. };
  32888. Cylinder.prototype.serialize = function () {
  32889. var serializationObject = _super.prototype.serialize.call(this);
  32890. serializationObject.height = this.height;
  32891. serializationObject.diameterTop = this.diameterTop;
  32892. serializationObject.diameterBottom = this.diameterBottom;
  32893. serializationObject.tessellation = this.tessellation;
  32894. return serializationObject;
  32895. };
  32896. Cylinder.Parse = function (parsedCylinder, scene) {
  32897. if (scene.getGeometryByID(parsedCylinder.id)) {
  32898. return null; // null since geometry could be something else than a cylinder...
  32899. }
  32900. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32901. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32902. scene.pushGeometry(cylinder, true);
  32903. return cylinder;
  32904. };
  32905. return Cylinder;
  32906. })(_Primitive);
  32907. Primitives.Cylinder = Cylinder;
  32908. var Torus = (function (_super) {
  32909. __extends(Torus, _super);
  32910. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32911. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32912. _super.call(this, id, scene, canBeRegenerated, mesh);
  32913. this.diameter = diameter;
  32914. this.thickness = thickness;
  32915. this.tessellation = tessellation;
  32916. this.side = side;
  32917. }
  32918. Torus.prototype._regenerateVertexData = function () {
  32919. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32920. };
  32921. Torus.prototype.copy = function (id) {
  32922. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32923. };
  32924. Torus.prototype.serialize = function () {
  32925. var serializationObject = _super.prototype.serialize.call(this);
  32926. serializationObject.diameter = this.diameter;
  32927. serializationObject.thickness = this.thickness;
  32928. serializationObject.tessellation = this.tessellation;
  32929. return serializationObject;
  32930. };
  32931. Torus.Parse = function (parsedTorus, scene) {
  32932. if (scene.getGeometryByID(parsedTorus.id)) {
  32933. return null; // null since geometry could be something else than a torus...
  32934. }
  32935. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32936. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32937. scene.pushGeometry(torus, true);
  32938. return torus;
  32939. };
  32940. return Torus;
  32941. })(_Primitive);
  32942. Primitives.Torus = Torus;
  32943. var Ground = (function (_super) {
  32944. __extends(Ground, _super);
  32945. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32946. _super.call(this, id, scene, canBeRegenerated, mesh);
  32947. this.width = width;
  32948. this.height = height;
  32949. this.subdivisions = subdivisions;
  32950. }
  32951. Ground.prototype._regenerateVertexData = function () {
  32952. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32953. };
  32954. Ground.prototype.copy = function (id) {
  32955. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32956. };
  32957. Ground.prototype.serialize = function () {
  32958. var serializationObject = _super.prototype.serialize.call(this);
  32959. serializationObject.width = this.width;
  32960. serializationObject.height = this.height;
  32961. serializationObject.subdivisions = this.subdivisions;
  32962. return serializationObject;
  32963. };
  32964. Ground.Parse = function (parsedGround, scene) {
  32965. if (scene.getGeometryByID(parsedGround.id)) {
  32966. return null; // null since geometry could be something else than a ground...
  32967. }
  32968. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32969. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32970. scene.pushGeometry(ground, true);
  32971. return ground;
  32972. };
  32973. return Ground;
  32974. })(_Primitive);
  32975. Primitives.Ground = Ground;
  32976. var TiledGround = (function (_super) {
  32977. __extends(TiledGround, _super);
  32978. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32979. _super.call(this, id, scene, canBeRegenerated, mesh);
  32980. this.xmin = xmin;
  32981. this.zmin = zmin;
  32982. this.xmax = xmax;
  32983. this.zmax = zmax;
  32984. this.subdivisions = subdivisions;
  32985. this.precision = precision;
  32986. }
  32987. TiledGround.prototype._regenerateVertexData = function () {
  32988. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32989. };
  32990. TiledGround.prototype.copy = function (id) {
  32991. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32992. };
  32993. return TiledGround;
  32994. })(_Primitive);
  32995. Primitives.TiledGround = TiledGround;
  32996. var Plane = (function (_super) {
  32997. __extends(Plane, _super);
  32998. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32999. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33000. _super.call(this, id, scene, canBeRegenerated, mesh);
  33001. this.size = size;
  33002. this.side = side;
  33003. }
  33004. Plane.prototype._regenerateVertexData = function () {
  33005. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33006. };
  33007. Plane.prototype.copy = function (id) {
  33008. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33009. };
  33010. Plane.prototype.serialize = function () {
  33011. var serializationObject = _super.prototype.serialize.call(this);
  33012. serializationObject.size = this.size;
  33013. return serializationObject;
  33014. };
  33015. Plane.Parse = function (parsedPlane, scene) {
  33016. if (scene.getGeometryByID(parsedPlane.id)) {
  33017. return null; // null since geometry could be something else than a ground...
  33018. }
  33019. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33020. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33021. scene.pushGeometry(plane, true);
  33022. return plane;
  33023. };
  33024. return Plane;
  33025. })(_Primitive);
  33026. Primitives.Plane = Plane;
  33027. var TorusKnot = (function (_super) {
  33028. __extends(TorusKnot, _super);
  33029. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  33030. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33031. _super.call(this, id, scene, canBeRegenerated, mesh);
  33032. this.radius = radius;
  33033. this.tube = tube;
  33034. this.radialSegments = radialSegments;
  33035. this.tubularSegments = tubularSegments;
  33036. this.p = p;
  33037. this.q = q;
  33038. this.side = side;
  33039. }
  33040. TorusKnot.prototype._regenerateVertexData = function () {
  33041. 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 });
  33042. };
  33043. TorusKnot.prototype.copy = function (id) {
  33044. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33045. };
  33046. TorusKnot.prototype.serialize = function () {
  33047. var serializationObject = _super.prototype.serialize.call(this);
  33048. serializationObject.radius = this.radius;
  33049. serializationObject.tube = this.tube;
  33050. serializationObject.radialSegments = this.radialSegments;
  33051. serializationObject.tubularSegments = this.tubularSegments;
  33052. serializationObject.p = this.p;
  33053. serializationObject.q = this.q;
  33054. return serializationObject;
  33055. };
  33056. ;
  33057. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  33058. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33059. return null; // null since geometry could be something else than a ground...
  33060. }
  33061. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33062. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33063. scene.pushGeometry(torusKnot, true);
  33064. return torusKnot;
  33065. };
  33066. return TorusKnot;
  33067. })(_Primitive);
  33068. Primitives.TorusKnot = TorusKnot;
  33069. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  33070. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  33071. })(BABYLON || (BABYLON = {}));
  33072. var BABYLON;
  33073. (function (BABYLON) {
  33074. var GroundMesh = (function (_super) {
  33075. __extends(GroundMesh, _super);
  33076. function GroundMesh(name, scene) {
  33077. _super.call(this, name, scene);
  33078. this.generateOctree = false;
  33079. this._worldInverse = new BABYLON.Matrix();
  33080. }
  33081. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33082. get: function () {
  33083. return this._subdivisions;
  33084. },
  33085. enumerable: true,
  33086. configurable: true
  33087. });
  33088. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33089. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33090. this._subdivisions = chunksCount;
  33091. this.subdivide(this._subdivisions);
  33092. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33093. };
  33094. /**
  33095. * Returns a height (y) value in the Worl system :
  33096. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33097. * Returns the ground y position if (x, z) are outside the ground surface.
  33098. * Not pertinent if the ground is rotated.
  33099. */
  33100. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33101. // express x and y in the ground local system
  33102. x -= this.position.x;
  33103. z -= this.position.z;
  33104. x /= this.scaling.x;
  33105. z /= this.scaling.z;
  33106. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33107. return this.position.y;
  33108. }
  33109. if (!this._heightQuads || this._heightQuads.length == 0) {
  33110. this._initHeightQuads();
  33111. this._computeHeightQuads();
  33112. }
  33113. var facet = this._getFacetAt(x, z);
  33114. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33115. // return y in the World system
  33116. return y * this.scaling.y + this.position.y;
  33117. };
  33118. /**
  33119. * Returns a normalized vector (Vector3) orthogonal to the ground
  33120. * at the ground coordinates (x, z) expressed in the World system.
  33121. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  33122. * Not pertinent if the ground is rotated.
  33123. */
  33124. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  33125. var normal = new BABYLON.Vector3(0, 1, 0);
  33126. this.getNormalAtCoordinatesToRef(x, z, normal);
  33127. return normal;
  33128. };
  33129. /**
  33130. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  33131. * at the ground coordinates (x, z) expressed in the World system.
  33132. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  33133. * Not pertinent if the ground is rotated.
  33134. */
  33135. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  33136. // express x and y in the ground local system
  33137. x -= this.position.x;
  33138. z -= this.position.z;
  33139. x /= this.scaling.x;
  33140. z /= this.scaling.z;
  33141. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33142. return;
  33143. }
  33144. if (!this._heightQuads || this._heightQuads.length == 0) {
  33145. this._initHeightQuads();
  33146. this._computeHeightQuads();
  33147. }
  33148. var facet = this._getFacetAt(x, z);
  33149. ref.x = facet.x;
  33150. ref.y = facet.y;
  33151. ref.z = facet.z;
  33152. };
  33153. /**
  33154. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  33155. * if the ground has been updated.
  33156. * This can be used in the render loop
  33157. */
  33158. GroundMesh.prototype.updateCoordinateHeights = function () {
  33159. if (!this._heightQuads || this._heightQuads.length == 0) {
  33160. this._initHeightQuads();
  33161. }
  33162. this._computeHeightQuads();
  33163. };
  33164. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  33165. GroundMesh.prototype._getFacetAt = function (x, z) {
  33166. // retrieve col and row from x, z coordinates in the ground local system
  33167. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  33168. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  33169. var quad = this._heightQuads[row * this._subdivisions + col];
  33170. var facet;
  33171. if (z < quad.slope.x * x + quad.slope.y) {
  33172. facet = quad.facet1;
  33173. }
  33174. else {
  33175. facet = quad.facet2;
  33176. }
  33177. return facet;
  33178. };
  33179. // Creates and populates the heightMap array with "facet" elements :
  33180. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  33181. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33182. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33183. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33184. GroundMesh.prototype._initHeightQuads = function () {
  33185. this._heightQuads = new Array();
  33186. for (var row = 0; row < this._subdivisions; row++) {
  33187. for (var col = 0; col < this._subdivisions; col++) {
  33188. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  33189. this._heightQuads[row * this._subdivisions + col] = quad;
  33190. }
  33191. }
  33192. };
  33193. // Compute each quad element values and update the the heightMap array :
  33194. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  33195. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  33196. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  33197. GroundMesh.prototype._computeHeightQuads = function () {
  33198. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33199. var v1 = BABYLON.Tmp.Vector3[0];
  33200. var v2 = BABYLON.Tmp.Vector3[1];
  33201. var v3 = BABYLON.Tmp.Vector3[2];
  33202. var v4 = BABYLON.Tmp.Vector3[3];
  33203. var v1v2 = BABYLON.Tmp.Vector3[4];
  33204. var v1v3 = BABYLON.Tmp.Vector3[5];
  33205. var v1v4 = BABYLON.Tmp.Vector3[6];
  33206. var norm1 = BABYLON.Tmp.Vector3[7];
  33207. var norm2 = BABYLON.Tmp.Vector3[8];
  33208. var i = 0;
  33209. var j = 0;
  33210. var k = 0;
  33211. var cd = 0; // 2D slope coefficient : z = cd * x + h
  33212. var h = 0;
  33213. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  33214. var d2 = 0;
  33215. for (var row = 0; row < this._subdivisions; row++) {
  33216. for (var col = 0; col < this._subdivisions; col++) {
  33217. i = col * 3;
  33218. j = row * (this._subdivisions + 1) * 3;
  33219. k = (row + 1) * (this._subdivisions + 1) * 3;
  33220. v1.x = positions[j + i];
  33221. v1.y = positions[j + i + 1];
  33222. v1.z = positions[j + i + 2];
  33223. v2.x = positions[j + i + 3];
  33224. v2.y = positions[j + i + 4];
  33225. v2.z = positions[j + i + 5];
  33226. v3.x = positions[k + i];
  33227. v3.y = positions[k + i + 1];
  33228. v3.z = positions[k + i + 2];
  33229. v4.x = positions[k + i + 3];
  33230. v4.y = positions[k + i + 4];
  33231. v4.z = positions[k + i + 5];
  33232. // 2D slope V1V4
  33233. cd = (v4.z - v1.z) / (v4.x - v1.x);
  33234. h = v1.z - cd * v1.x; // v1 belongs to the slope
  33235. // facet equations :
  33236. // we compute each facet normal vector
  33237. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  33238. // we compute the value d by applying the equation to v1 which belongs to the plane
  33239. // then we store the facet equation in a Vector4
  33240. v2.subtractToRef(v1, v1v2);
  33241. v3.subtractToRef(v1, v1v3);
  33242. v4.subtractToRef(v1, v1v4);
  33243. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  33244. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  33245. norm1.normalize();
  33246. norm2.normalize();
  33247. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  33248. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  33249. var quad = this._heightQuads[row * this._subdivisions + col];
  33250. quad.slope.copyFromFloats(cd, h);
  33251. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  33252. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  33253. }
  33254. }
  33255. };
  33256. return GroundMesh;
  33257. })(BABYLON.Mesh);
  33258. BABYLON.GroundMesh = GroundMesh;
  33259. })(BABYLON || (BABYLON = {}));
  33260. var BABYLON;
  33261. (function (BABYLON) {
  33262. var LinesMesh = (function (_super) {
  33263. __extends(LinesMesh, _super);
  33264. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  33265. if (parent === void 0) { parent = null; }
  33266. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  33267. this.color = new BABYLON.Color3(1, 1, 1);
  33268. this.alpha = 1;
  33269. if (source) {
  33270. this.color = source.color.clone();
  33271. this.alpha = source.alpha;
  33272. }
  33273. this._intersectionThreshold = 0.1;
  33274. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  33275. attributes: ["position"],
  33276. uniforms: ["worldViewProjection", "color"],
  33277. needAlphaBlending: true
  33278. });
  33279. }
  33280. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  33281. /**
  33282. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33283. * This margin is expressed in world space coordinates, so its value may vary.
  33284. * Default value is 0.1
  33285. * @returns the intersection Threshold value.
  33286. */
  33287. get: function () {
  33288. return this._intersectionThreshold;
  33289. },
  33290. /**
  33291. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  33292. * This margin is expressed in world space coordinates, so its value may vary.
  33293. * @param value the new threshold to apply
  33294. */
  33295. set: function (value) {
  33296. if (this._intersectionThreshold === value) {
  33297. return;
  33298. }
  33299. this._intersectionThreshold = value;
  33300. if (this.geometry) {
  33301. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  33302. }
  33303. },
  33304. enumerable: true,
  33305. configurable: true
  33306. });
  33307. Object.defineProperty(LinesMesh.prototype, "material", {
  33308. get: function () {
  33309. return this._colorShader;
  33310. },
  33311. enumerable: true,
  33312. configurable: true
  33313. });
  33314. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  33315. get: function () {
  33316. return false;
  33317. },
  33318. enumerable: true,
  33319. configurable: true
  33320. });
  33321. LinesMesh.prototype.createInstance = function (name) {
  33322. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  33323. return null;
  33324. };
  33325. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  33326. var engine = this.getScene().getEngine();
  33327. var indexToBind = this._geometry.getIndexBuffer();
  33328. // VBOs
  33329. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  33330. // Color
  33331. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  33332. };
  33333. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  33334. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  33335. return;
  33336. }
  33337. var engine = this.getScene().getEngine();
  33338. // Draw order
  33339. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  33340. };
  33341. LinesMesh.prototype.dispose = function (doNotRecurse) {
  33342. this._colorShader.dispose();
  33343. _super.prototype.dispose.call(this, doNotRecurse);
  33344. };
  33345. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  33346. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  33347. };
  33348. return LinesMesh;
  33349. })(BABYLON.Mesh);
  33350. BABYLON.LinesMesh = LinesMesh;
  33351. })(BABYLON || (BABYLON = {}));
  33352. var BABYLON;
  33353. (function (BABYLON) {
  33354. var DefaultLoadingScreen = (function () {
  33355. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33356. var _this = this;
  33357. if (_loadingText === void 0) { _loadingText = ""; }
  33358. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33359. this._renderingCanvas = _renderingCanvas;
  33360. this._loadingText = _loadingText;
  33361. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33362. // Resize
  33363. this._resizeLoadingUI = function () {
  33364. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33365. _this._loadingDiv.style.position = "absolute";
  33366. _this._loadingDiv.style.left = canvasRect.left + "px";
  33367. _this._loadingDiv.style.top = canvasRect.top + "px";
  33368. _this._loadingDiv.style.width = canvasRect.width + "px";
  33369. _this._loadingDiv.style.height = canvasRect.height + "px";
  33370. };
  33371. }
  33372. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33373. var _this = this;
  33374. if (this._loadingDiv) {
  33375. // Do not add a loading screen if there is already one
  33376. return;
  33377. }
  33378. this._loadingDiv = document.createElement("div");
  33379. this._loadingDiv.id = "babylonjsLoadingDiv";
  33380. this._loadingDiv.style.opacity = "0";
  33381. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33382. // Loading text
  33383. this._loadingTextDiv = document.createElement("div");
  33384. this._loadingTextDiv.style.position = "absolute";
  33385. this._loadingTextDiv.style.left = "0";
  33386. this._loadingTextDiv.style.top = "50%";
  33387. this._loadingTextDiv.style.marginTop = "80px";
  33388. this._loadingTextDiv.style.width = "100%";
  33389. this._loadingTextDiv.style.height = "20px";
  33390. this._loadingTextDiv.style.fontFamily = "Arial";
  33391. this._loadingTextDiv.style.fontSize = "14px";
  33392. this._loadingTextDiv.style.color = "white";
  33393. this._loadingTextDiv.style.textAlign = "center";
  33394. this._loadingTextDiv.innerHTML = "Loading";
  33395. this._loadingDiv.appendChild(this._loadingTextDiv);
  33396. //set the predefined text
  33397. this._loadingTextDiv.innerHTML = this._loadingText;
  33398. // Loading img
  33399. var imgBack = new Image();
  33400. 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==";
  33401. imgBack.style.position = "absolute";
  33402. imgBack.style.left = "50%";
  33403. imgBack.style.top = "50%";
  33404. imgBack.style.marginLeft = "-50px";
  33405. imgBack.style.marginTop = "-50px";
  33406. imgBack.style.transition = "transform 1.0s ease";
  33407. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33408. var deg = 360;
  33409. var onTransitionEnd = function () {
  33410. deg += 360;
  33411. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33412. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33413. };
  33414. imgBack.addEventListener("transitionend", onTransitionEnd);
  33415. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33416. this._loadingDiv.appendChild(imgBack);
  33417. // front image
  33418. var imgFront = new Image();
  33419. 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=";
  33420. imgFront.style.position = "absolute";
  33421. imgFront.style.left = "50%";
  33422. imgFront.style.top = "50%";
  33423. imgFront.style.marginLeft = "-50px";
  33424. imgFront.style.marginTop = "-50px";
  33425. this._loadingDiv.appendChild(imgFront);
  33426. this._resizeLoadingUI();
  33427. window.addEventListener("resize", this._resizeLoadingUI);
  33428. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33429. document.body.appendChild(this._loadingDiv);
  33430. setTimeout(function () {
  33431. _this._loadingDiv.style.opacity = "1";
  33432. imgBack.style.transform = "rotateZ(360deg)";
  33433. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33434. }, 0);
  33435. };
  33436. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33437. var _this = this;
  33438. if (!this._loadingDiv) {
  33439. return;
  33440. }
  33441. var onTransitionEnd = function () {
  33442. if (!_this._loadingDiv) {
  33443. return;
  33444. }
  33445. document.body.removeChild(_this._loadingDiv);
  33446. window.removeEventListener("resize", _this._resizeLoadingUI);
  33447. _this._loadingDiv = null;
  33448. };
  33449. this._loadingDiv.style.opacity = "0";
  33450. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33451. };
  33452. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33453. set: function (text) {
  33454. this._loadingText = text;
  33455. if (this._loadingTextDiv) {
  33456. this._loadingTextDiv.innerHTML = this._loadingText;
  33457. }
  33458. },
  33459. enumerable: true,
  33460. configurable: true
  33461. });
  33462. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33463. get: function () {
  33464. return this._loadingDivBackgroundColor;
  33465. },
  33466. set: function (color) {
  33467. this._loadingDivBackgroundColor = color;
  33468. if (!this._loadingDiv) {
  33469. return;
  33470. }
  33471. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33472. },
  33473. enumerable: true,
  33474. configurable: true
  33475. });
  33476. return DefaultLoadingScreen;
  33477. })();
  33478. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33479. })(BABYLON || (BABYLON = {}));
  33480. var BABYLON;
  33481. (function (BABYLON) {
  33482. var AudioEngine = (function () {
  33483. function AudioEngine() {
  33484. this._audioContext = null;
  33485. this._audioContextInitialized = false;
  33486. this.canUseWebAudio = false;
  33487. this.WarnedWebAudioUnsupported = false;
  33488. this.unlocked = false;
  33489. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33490. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33491. this.canUseWebAudio = true;
  33492. }
  33493. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33494. this._unlockiOSaudio();
  33495. }
  33496. else {
  33497. this.unlocked = true;
  33498. }
  33499. }
  33500. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33501. get: function () {
  33502. if (!this._audioContextInitialized) {
  33503. this._initializeAudioContext();
  33504. }
  33505. return this._audioContext;
  33506. },
  33507. enumerable: true,
  33508. configurable: true
  33509. });
  33510. AudioEngine.prototype._unlockiOSaudio = function () {
  33511. var _this = this;
  33512. var unlockaudio = function () {
  33513. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33514. var source = _this.audioContext.createBufferSource();
  33515. source.buffer = buffer;
  33516. source.connect(_this.audioContext.destination);
  33517. source.start(0);
  33518. setTimeout(function () {
  33519. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33520. _this.unlocked = true;
  33521. window.removeEventListener('touchend', unlockaudio, false);
  33522. if (_this.onAudioUnlocked) {
  33523. _this.onAudioUnlocked();
  33524. }
  33525. }
  33526. }, 0);
  33527. };
  33528. window.addEventListener('touchend', unlockaudio, false);
  33529. };
  33530. AudioEngine.prototype._initializeAudioContext = function () {
  33531. try {
  33532. if (this.canUseWebAudio) {
  33533. this._audioContext = new AudioContext();
  33534. // create a global volume gain node
  33535. this.masterGain = this._audioContext.createGain();
  33536. this.masterGain.gain.value = 1;
  33537. this.masterGain.connect(this._audioContext.destination);
  33538. this._audioContextInitialized = true;
  33539. }
  33540. }
  33541. catch (e) {
  33542. this.canUseWebAudio = false;
  33543. BABYLON.Tools.Error("Web Audio: " + e.message);
  33544. }
  33545. };
  33546. AudioEngine.prototype.dispose = function () {
  33547. if (this.canUseWebAudio && this._audioContextInitialized) {
  33548. if (this._connectedAnalyser) {
  33549. this._connectedAnalyser.stopDebugCanvas();
  33550. this._connectedAnalyser.dispose();
  33551. this.masterGain.disconnect();
  33552. this.masterGain.connect(this._audioContext.destination);
  33553. this._connectedAnalyser = null;
  33554. }
  33555. this.masterGain.gain.value = 1;
  33556. }
  33557. this.WarnedWebAudioUnsupported = false;
  33558. };
  33559. AudioEngine.prototype.getGlobalVolume = function () {
  33560. if (this.canUseWebAudio && this._audioContextInitialized) {
  33561. return this.masterGain.gain.value;
  33562. }
  33563. else {
  33564. return -1;
  33565. }
  33566. };
  33567. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33568. if (this.canUseWebAudio && this._audioContextInitialized) {
  33569. this.masterGain.gain.value = newVolume;
  33570. }
  33571. };
  33572. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33573. if (this._connectedAnalyser) {
  33574. this._connectedAnalyser.stopDebugCanvas();
  33575. }
  33576. if (this.canUseWebAudio && this._audioContextInitialized) {
  33577. this._connectedAnalyser = analyser;
  33578. this.masterGain.disconnect();
  33579. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33580. }
  33581. };
  33582. return AudioEngine;
  33583. })();
  33584. BABYLON.AudioEngine = AudioEngine;
  33585. })(BABYLON || (BABYLON = {}));
  33586. var BABYLON;
  33587. (function (BABYLON) {
  33588. var Sound = (function () {
  33589. /**
  33590. * Create a sound and attach it to a scene
  33591. * @param name Name of your sound
  33592. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33593. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33594. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33595. */
  33596. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33597. var _this = this;
  33598. this.autoplay = false;
  33599. this.loop = false;
  33600. this.useCustomAttenuation = false;
  33601. this.spatialSound = false;
  33602. this.refDistance = 1;
  33603. this.rolloffFactor = 1;
  33604. this.maxDistance = 100;
  33605. this.distanceModel = "linear";
  33606. this._panningModel = "equalpower";
  33607. this._playbackRate = 1;
  33608. this._streaming = false;
  33609. this._startTime = 0;
  33610. this._startOffset = 0;
  33611. this._position = BABYLON.Vector3.Zero();
  33612. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33613. this._volume = 1;
  33614. this._isLoaded = false;
  33615. this._isReadyToPlay = false;
  33616. this.isPlaying = false;
  33617. this.isPaused = false;
  33618. this._isDirectional = false;
  33619. // Used if you'd like to create a directional sound.
  33620. // If not set, the sound will be omnidirectional
  33621. this._coneInnerAngle = 360;
  33622. this._coneOuterAngle = 360;
  33623. this._coneOuterGain = 0;
  33624. this._isOutputConnected = false;
  33625. this.name = name;
  33626. this._scene = scene;
  33627. this._readyToPlayCallback = readyToPlayCallback;
  33628. // Default custom attenuation function is a linear attenuation
  33629. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33630. if (currentDistance < maxDistance) {
  33631. return currentVolume * (1 - currentDistance / maxDistance);
  33632. }
  33633. else {
  33634. return 0;
  33635. }
  33636. };
  33637. if (options) {
  33638. this.autoplay = options.autoplay || false;
  33639. this.loop = options.loop || false;
  33640. // if volume === 0, we need another way to check this option
  33641. if (options.volume !== undefined) {
  33642. this._volume = options.volume;
  33643. }
  33644. this.spatialSound = options.spatialSound || false;
  33645. this.maxDistance = options.maxDistance || 100;
  33646. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33647. this.rolloffFactor = options.rolloffFactor || 1;
  33648. this.refDistance = options.refDistance || 1;
  33649. this.distanceModel = options.distanceModel || "linear";
  33650. this._playbackRate = options.playbackRate || 1;
  33651. this._streaming = options.streaming || false;
  33652. }
  33653. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33654. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33655. this._soundGain.gain.value = this._volume;
  33656. this._inputAudioNode = this._soundGain;
  33657. this._ouputAudioNode = this._soundGain;
  33658. if (this.spatialSound) {
  33659. this._createSpatialParameters();
  33660. }
  33661. this._scene.mainSoundTrack.AddSound(this);
  33662. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33663. if (urlOrArrayBuffer) {
  33664. // If it's an URL
  33665. if (typeof (urlOrArrayBuffer) === "string") {
  33666. // Loading sound using XHR2
  33667. if (!this._streaming) {
  33668. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33669. }
  33670. else {
  33671. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33672. this._htmlAudioElement.controls = false;
  33673. this._htmlAudioElement.loop = this.loop;
  33674. this._htmlAudioElement.crossOrigin = "anonymous";
  33675. this._htmlAudioElement.preload = "auto";
  33676. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33677. _this._isReadyToPlay = true;
  33678. if (_this.autoplay) {
  33679. _this.play();
  33680. }
  33681. if (_this._readyToPlayCallback) {
  33682. _this._readyToPlayCallback();
  33683. }
  33684. });
  33685. document.body.appendChild(this._htmlAudioElement);
  33686. }
  33687. }
  33688. else {
  33689. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33690. if (urlOrArrayBuffer.byteLength > 0) {
  33691. this._soundLoaded(urlOrArrayBuffer);
  33692. }
  33693. }
  33694. else {
  33695. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33696. }
  33697. }
  33698. }
  33699. }
  33700. else {
  33701. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33702. this._scene.mainSoundTrack.AddSound(this);
  33703. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33704. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33705. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33706. }
  33707. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33708. if (this._readyToPlayCallback) {
  33709. window.setTimeout(function () {
  33710. _this._readyToPlayCallback();
  33711. }, 1000);
  33712. }
  33713. }
  33714. }
  33715. Sound.prototype.dispose = function () {
  33716. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33717. if (this.isPlaying) {
  33718. this.stop();
  33719. }
  33720. this._isReadyToPlay = false;
  33721. if (this.soundTrackId === -1) {
  33722. this._scene.mainSoundTrack.RemoveSound(this);
  33723. }
  33724. else {
  33725. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33726. }
  33727. if (this._soundGain) {
  33728. this._soundGain.disconnect();
  33729. this._soundGain = null;
  33730. }
  33731. if (this._soundPanner) {
  33732. this._soundPanner.disconnect();
  33733. this._soundPanner = null;
  33734. }
  33735. if (this._soundSource) {
  33736. this._soundSource.disconnect();
  33737. this._soundSource = null;
  33738. }
  33739. this._audioBuffer = null;
  33740. if (this._htmlAudioElement) {
  33741. this._htmlAudioElement.pause();
  33742. this._htmlAudioElement.src = "";
  33743. document.body.removeChild(this._htmlAudioElement);
  33744. }
  33745. if (this._connectedMesh) {
  33746. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33747. this._connectedMesh = null;
  33748. }
  33749. }
  33750. };
  33751. Sound.prototype._soundLoaded = function (audioData) {
  33752. var _this = this;
  33753. this._isLoaded = true;
  33754. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33755. _this._audioBuffer = buffer;
  33756. _this._isReadyToPlay = true;
  33757. if (_this.autoplay) {
  33758. _this.play();
  33759. }
  33760. if (_this._readyToPlayCallback) {
  33761. _this._readyToPlayCallback();
  33762. }
  33763. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33764. };
  33765. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33766. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33767. this._audioBuffer = audioBuffer;
  33768. this._isReadyToPlay = true;
  33769. }
  33770. };
  33771. Sound.prototype.updateOptions = function (options) {
  33772. if (options) {
  33773. this.loop = options.loop || this.loop;
  33774. this.maxDistance = options.maxDistance || this.maxDistance;
  33775. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33776. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33777. this.refDistance = options.refDistance || this.refDistance;
  33778. this.distanceModel = options.distanceModel || this.distanceModel;
  33779. this._playbackRate = options.playbackRate || this._playbackRate;
  33780. this._updateSpatialParameters();
  33781. if (this.isPlaying) {
  33782. if (this._streaming) {
  33783. this._htmlAudioElement.playbackRate = this._playbackRate;
  33784. }
  33785. else {
  33786. this._soundSource.playbackRate.value = this._playbackRate;
  33787. }
  33788. }
  33789. }
  33790. };
  33791. Sound.prototype._createSpatialParameters = function () {
  33792. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33793. if (this._scene.headphone) {
  33794. this._panningModel = "HRTF";
  33795. }
  33796. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33797. this._updateSpatialParameters();
  33798. this._soundPanner.connect(this._ouputAudioNode);
  33799. this._inputAudioNode = this._soundPanner;
  33800. }
  33801. };
  33802. Sound.prototype._updateSpatialParameters = function () {
  33803. if (this.spatialSound) {
  33804. if (this.useCustomAttenuation) {
  33805. // Tricks to disable in a way embedded Web Audio attenuation
  33806. this._soundPanner.distanceModel = "linear";
  33807. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33808. this._soundPanner.refDistance = 1;
  33809. this._soundPanner.rolloffFactor = 1;
  33810. this._soundPanner.panningModel = this._panningModel;
  33811. }
  33812. else {
  33813. this._soundPanner.distanceModel = this.distanceModel;
  33814. this._soundPanner.maxDistance = this.maxDistance;
  33815. this._soundPanner.refDistance = this.refDistance;
  33816. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33817. this._soundPanner.panningModel = this._panningModel;
  33818. }
  33819. }
  33820. };
  33821. Sound.prototype.switchPanningModelToHRTF = function () {
  33822. this._panningModel = "HRTF";
  33823. this._switchPanningModel();
  33824. };
  33825. Sound.prototype.switchPanningModelToEqualPower = function () {
  33826. this._panningModel = "equalpower";
  33827. this._switchPanningModel();
  33828. };
  33829. Sound.prototype._switchPanningModel = function () {
  33830. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33831. this._soundPanner.panningModel = this._panningModel;
  33832. }
  33833. };
  33834. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33835. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33836. if (this._isOutputConnected) {
  33837. this._ouputAudioNode.disconnect();
  33838. }
  33839. this._ouputAudioNode.connect(soundTrackAudioNode);
  33840. this._isOutputConnected = true;
  33841. }
  33842. };
  33843. /**
  33844. * Transform this sound into a directional source
  33845. * @param coneInnerAngle Size of the inner cone in degree
  33846. * @param coneOuterAngle Size of the outer cone in degree
  33847. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33848. */
  33849. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33850. if (coneOuterAngle < coneInnerAngle) {
  33851. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33852. return;
  33853. }
  33854. this._coneInnerAngle = coneInnerAngle;
  33855. this._coneOuterAngle = coneOuterAngle;
  33856. this._coneOuterGain = coneOuterGain;
  33857. this._isDirectional = true;
  33858. if (this.isPlaying && this.loop) {
  33859. this.stop();
  33860. this.play();
  33861. }
  33862. };
  33863. Sound.prototype.setPosition = function (newPosition) {
  33864. this._position = newPosition;
  33865. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33866. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33867. }
  33868. };
  33869. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33870. this._localDirection = newLocalDirection;
  33871. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33872. this._updateDirection();
  33873. }
  33874. };
  33875. Sound.prototype._updateDirection = function () {
  33876. var mat = this._connectedMesh.getWorldMatrix();
  33877. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33878. direction.normalize();
  33879. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33880. };
  33881. Sound.prototype.updateDistanceFromListener = function () {
  33882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33883. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33884. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33885. }
  33886. };
  33887. Sound.prototype.setAttenuationFunction = function (callback) {
  33888. this._customAttenuationFunction = callback;
  33889. };
  33890. /**
  33891. * Play the sound
  33892. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33893. */
  33894. Sound.prototype.play = function (time) {
  33895. var _this = this;
  33896. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33897. try {
  33898. if (this._startOffset < 0) {
  33899. time = -this._startOffset;
  33900. this._startOffset = 0;
  33901. }
  33902. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33903. if (!this._soundSource || !this._streamingSource) {
  33904. if (this.spatialSound) {
  33905. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33906. if (this._isDirectional) {
  33907. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33908. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33909. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33910. if (this._connectedMesh) {
  33911. this._updateDirection();
  33912. }
  33913. else {
  33914. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33915. }
  33916. }
  33917. }
  33918. }
  33919. if (this._streaming) {
  33920. if (!this._streamingSource) {
  33921. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33922. this._htmlAudioElement.onended = function () { _this._onended(); };
  33923. this._htmlAudioElement.playbackRate = this._playbackRate;
  33924. }
  33925. this._streamingSource.disconnect();
  33926. this._streamingSource.connect(this._inputAudioNode);
  33927. this._htmlAudioElement.play();
  33928. }
  33929. else {
  33930. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33931. this._soundSource.buffer = this._audioBuffer;
  33932. this._soundSource.connect(this._inputAudioNode);
  33933. this._soundSource.loop = this.loop;
  33934. this._soundSource.playbackRate.value = this._playbackRate;
  33935. this._soundSource.onended = function () { _this._onended(); };
  33936. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33937. }
  33938. this._startTime = startTime;
  33939. this.isPlaying = true;
  33940. this.isPaused = false;
  33941. }
  33942. catch (ex) {
  33943. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33944. }
  33945. }
  33946. };
  33947. Sound.prototype._onended = function () {
  33948. this.isPlaying = false;
  33949. if (this.onended) {
  33950. this.onended();
  33951. }
  33952. };
  33953. /**
  33954. * Stop the sound
  33955. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33956. */
  33957. Sound.prototype.stop = function (time) {
  33958. if (this.isPlaying) {
  33959. if (this._streaming) {
  33960. this._htmlAudioElement.pause();
  33961. // Test needed for Firefox or it will generate an Invalid State Error
  33962. if (this._htmlAudioElement.currentTime > 0) {
  33963. this._htmlAudioElement.currentTime = 0;
  33964. }
  33965. }
  33966. else {
  33967. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33968. this._soundSource.stop(stopTime);
  33969. if (!this.isPaused) {
  33970. this._startOffset = 0;
  33971. }
  33972. }
  33973. this.isPlaying = false;
  33974. }
  33975. };
  33976. Sound.prototype.pause = function () {
  33977. if (this.isPlaying) {
  33978. this.isPaused = true;
  33979. if (this._streaming) {
  33980. this._htmlAudioElement.pause();
  33981. }
  33982. else {
  33983. this.stop(0);
  33984. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33985. }
  33986. }
  33987. };
  33988. Sound.prototype.setVolume = function (newVolume, time) {
  33989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33990. if (time) {
  33991. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33992. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33993. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33994. }
  33995. else {
  33996. this._soundGain.gain.value = newVolume;
  33997. }
  33998. }
  33999. this._volume = newVolume;
  34000. };
  34001. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34002. this._playbackRate = newPlaybackRate;
  34003. if (this.isPlaying) {
  34004. if (this._streaming) {
  34005. this._htmlAudioElement.playbackRate = this._playbackRate;
  34006. }
  34007. else {
  34008. this._soundSource.playbackRate.value = this._playbackRate;
  34009. }
  34010. }
  34011. };
  34012. Sound.prototype.getVolume = function () {
  34013. return this._volume;
  34014. };
  34015. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34016. var _this = this;
  34017. if (this._connectedMesh) {
  34018. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34019. this._registerFunc = null;
  34020. }
  34021. this._connectedMesh = meshToConnectTo;
  34022. if (!this.spatialSound) {
  34023. this.spatialSound = true;
  34024. this._createSpatialParameters();
  34025. if (this.isPlaying && this.loop) {
  34026. this.stop();
  34027. this.play();
  34028. }
  34029. }
  34030. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34031. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34032. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34033. };
  34034. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34035. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34036. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34037. this._updateDirection();
  34038. }
  34039. };
  34040. Sound.prototype.clone = function () {
  34041. var _this = this;
  34042. if (!this._streaming) {
  34043. var setBufferAndRun = function () {
  34044. if (_this._isReadyToPlay) {
  34045. clonedSound._audioBuffer = _this.getAudioBuffer();
  34046. clonedSound._isReadyToPlay = true;
  34047. if (clonedSound.autoplay) {
  34048. clonedSound.play();
  34049. }
  34050. }
  34051. else {
  34052. window.setTimeout(setBufferAndRun, 300);
  34053. }
  34054. };
  34055. var currentOptions = {
  34056. autoplay: this.autoplay, loop: this.loop,
  34057. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34058. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34059. refDistance: this.refDistance, distanceModel: this.distanceModel
  34060. };
  34061. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34062. if (this.useCustomAttenuation) {
  34063. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34064. }
  34065. clonedSound.setPosition(this._position);
  34066. clonedSound.setPlaybackRate(this._playbackRate);
  34067. setBufferAndRun();
  34068. return clonedSound;
  34069. }
  34070. else {
  34071. return null;
  34072. }
  34073. };
  34074. Sound.prototype.getAudioBuffer = function () {
  34075. return this._audioBuffer;
  34076. };
  34077. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34078. var soundName = parsedSound.name;
  34079. var soundUrl;
  34080. if (parsedSound.url) {
  34081. soundUrl = rootUrl + parsedSound.url;
  34082. }
  34083. else {
  34084. soundUrl = rootUrl + soundName;
  34085. }
  34086. var options = {
  34087. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34088. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34089. rolloffFactor: parsedSound.rolloffFactor,
  34090. refDistance: parsedSound.refDistance,
  34091. distanceModel: parsedSound.distanceModel,
  34092. playbackRate: parsedSound.playbackRate
  34093. };
  34094. var newSound;
  34095. if (!sourceSound) {
  34096. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34097. scene._addPendingData(newSound);
  34098. }
  34099. else {
  34100. var setBufferAndRun = function () {
  34101. if (sourceSound._isReadyToPlay) {
  34102. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34103. newSound._isReadyToPlay = true;
  34104. if (newSound.autoplay) {
  34105. newSound.play();
  34106. }
  34107. }
  34108. else {
  34109. window.setTimeout(setBufferAndRun, 300);
  34110. }
  34111. };
  34112. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34113. setBufferAndRun();
  34114. }
  34115. if (parsedSound.position) {
  34116. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34117. newSound.setPosition(soundPosition);
  34118. }
  34119. if (parsedSound.isDirectional) {
  34120. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34121. if (parsedSound.localDirectionToMesh) {
  34122. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34123. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34124. }
  34125. }
  34126. if (parsedSound.connectedMeshId) {
  34127. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34128. if (connectedMesh) {
  34129. newSound.attachToMesh(connectedMesh);
  34130. }
  34131. }
  34132. return newSound;
  34133. };
  34134. return Sound;
  34135. })();
  34136. BABYLON.Sound = Sound;
  34137. })(BABYLON || (BABYLON = {}));
  34138. var BABYLON;
  34139. (function (BABYLON) {
  34140. var SoundTrack = (function () {
  34141. function SoundTrack(scene, options) {
  34142. this.id = -1;
  34143. this._isMainTrack = false;
  34144. this._isInitialized = false;
  34145. this._scene = scene;
  34146. this.soundCollection = new Array();
  34147. this._options = options;
  34148. if (!this._isMainTrack) {
  34149. this._scene.soundTracks.push(this);
  34150. this.id = this._scene.soundTracks.length - 1;
  34151. }
  34152. }
  34153. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34154. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34155. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34156. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34157. if (this._options) {
  34158. if (this._options.volume) {
  34159. this._outputAudioNode.gain.value = this._options.volume;
  34160. }
  34161. if (this._options.mainTrack) {
  34162. this._isMainTrack = this._options.mainTrack;
  34163. }
  34164. }
  34165. this._isInitialized = true;
  34166. }
  34167. };
  34168. SoundTrack.prototype.dispose = function () {
  34169. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34170. if (this._connectedAnalyser) {
  34171. this._connectedAnalyser.stopDebugCanvas();
  34172. }
  34173. while (this.soundCollection.length) {
  34174. this.soundCollection[0].dispose();
  34175. }
  34176. if (this._outputAudioNode) {
  34177. this._outputAudioNode.disconnect();
  34178. }
  34179. this._outputAudioNode = null;
  34180. }
  34181. };
  34182. SoundTrack.prototype.AddSound = function (sound) {
  34183. if (!this._isInitialized) {
  34184. this._initializeSoundTrackAudioGraph();
  34185. }
  34186. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34187. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34188. }
  34189. if (sound.soundTrackId) {
  34190. if (sound.soundTrackId === -1) {
  34191. this._scene.mainSoundTrack.RemoveSound(sound);
  34192. }
  34193. else {
  34194. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34195. }
  34196. }
  34197. this.soundCollection.push(sound);
  34198. sound.soundTrackId = this.id;
  34199. };
  34200. SoundTrack.prototype.RemoveSound = function (sound) {
  34201. var index = this.soundCollection.indexOf(sound);
  34202. if (index !== -1) {
  34203. this.soundCollection.splice(index, 1);
  34204. }
  34205. };
  34206. SoundTrack.prototype.setVolume = function (newVolume) {
  34207. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34208. this._outputAudioNode.gain.value = newVolume;
  34209. }
  34210. };
  34211. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34212. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34213. for (var i = 0; i < this.soundCollection.length; i++) {
  34214. this.soundCollection[i].switchPanningModelToHRTF();
  34215. }
  34216. }
  34217. };
  34218. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34219. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34220. for (var i = 0; i < this.soundCollection.length; i++) {
  34221. this.soundCollection[i].switchPanningModelToEqualPower();
  34222. }
  34223. }
  34224. };
  34225. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34226. if (this._connectedAnalyser) {
  34227. this._connectedAnalyser.stopDebugCanvas();
  34228. }
  34229. this._connectedAnalyser = analyser;
  34230. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34231. this._outputAudioNode.disconnect();
  34232. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34233. }
  34234. };
  34235. return SoundTrack;
  34236. })();
  34237. BABYLON.SoundTrack = SoundTrack;
  34238. })(BABYLON || (BABYLON = {}));
  34239. var BABYLON;
  34240. (function (BABYLON) {
  34241. var SIMDVector3 = (function () {
  34242. function SIMDVector3() {
  34243. }
  34244. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34245. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34246. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34247. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34248. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34249. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34250. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  34251. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34252. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34253. };
  34254. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34255. var v0 = SIMD.float32x4.splat(x);
  34256. var v1 = SIMD.float32x4.splat(y);
  34257. var v2 = SIMD.float32x4.splat(z);
  34258. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34259. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34260. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34261. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34262. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  34263. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34264. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34265. };
  34266. return SIMDVector3;
  34267. })();
  34268. BABYLON.SIMDVector3 = SIMDVector3;
  34269. var SIMDMatrix = (function () {
  34270. function SIMDMatrix() {
  34271. }
  34272. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34273. if (offset === void 0) { offset = 0; }
  34274. var tm = this.m;
  34275. var om = other.m;
  34276. var om0 = SIMD.float32x4.load(om, 0);
  34277. var om1 = SIMD.float32x4.load(om, 4);
  34278. var om2 = SIMD.float32x4.load(om, 8);
  34279. var om3 = SIMD.float32x4.load(om, 12);
  34280. var tm0 = SIMD.float32x4.load(tm, 0);
  34281. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  34282. var tm1 = SIMD.float32x4.load(tm, 4);
  34283. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  34284. var tm2 = SIMD.float32x4.load(tm, 8);
  34285. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  34286. var tm3 = SIMD.float32x4.load(tm, 12);
  34287. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  34288. };
  34289. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34290. var src = this.m;
  34291. var dest = other.m;
  34292. var row0, row1, row2, row3;
  34293. var tmp1;
  34294. var minor0, minor1, minor2, minor3;
  34295. var det;
  34296. // Load the 4 rows
  34297. var src0 = SIMD.float32x4.load(src, 0);
  34298. var src1 = SIMD.float32x4.load(src, 4);
  34299. var src2 = SIMD.float32x4.load(src, 8);
  34300. var src3 = SIMD.float32x4.load(src, 12);
  34301. // Transpose the source matrix. Sort of. Not a true transpose operation
  34302. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34303. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34304. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34305. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34306. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34307. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34308. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34309. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34310. // This is a true transposition, but it will lead to an incorrect result
  34311. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34312. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34313. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34314. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34315. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34316. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34317. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34318. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34319. // ----
  34320. tmp1 = SIMD.float32x4.mul(row2, row3);
  34321. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34322. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34323. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34324. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34325. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34326. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34327. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34328. // ----
  34329. tmp1 = SIMD.float32x4.mul(row1, row2);
  34330. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34331. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34332. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34333. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34334. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34335. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34336. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34337. // ----
  34338. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34339. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34340. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34341. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34342. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34343. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34344. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34345. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34346. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34347. // ----
  34348. tmp1 = SIMD.float32x4.mul(row0, row1);
  34349. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34350. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34351. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34352. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34353. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34354. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34355. // ----
  34356. tmp1 = SIMD.float32x4.mul(row0, row3);
  34357. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34358. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34359. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34360. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34361. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34362. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34363. // ----
  34364. tmp1 = SIMD.float32x4.mul(row0, row2);
  34365. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34366. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34367. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34368. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34369. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34370. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34371. // Compute determinant
  34372. det = SIMD.float32x4.mul(row0, minor0);
  34373. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34374. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34375. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34376. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34377. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34378. // These shuffles aren't necessary if the faulty transposition is done
  34379. // up at the top of this function.
  34380. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34381. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34382. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34383. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34384. // Compute final values by multiplying with 1/det
  34385. minor0 = SIMD.float32x4.mul(det, minor0);
  34386. minor1 = SIMD.float32x4.mul(det, minor1);
  34387. minor2 = SIMD.float32x4.mul(det, minor2);
  34388. minor3 = SIMD.float32x4.mul(det, minor3);
  34389. SIMD.float32x4.store(dest, 0, minor0);
  34390. SIMD.float32x4.store(dest, 4, minor1);
  34391. SIMD.float32x4.store(dest, 8, minor2);
  34392. SIMD.float32x4.store(dest, 12, minor3);
  34393. return this;
  34394. };
  34395. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34396. var out = result.m;
  34397. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34398. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34399. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34400. // cc.kmVec3Subtract(f, pCenter, pEye);
  34401. var f = SIMD.float32x4.sub(center, eye);
  34402. // cc.kmVec3Normalize(f, f);
  34403. var tmp = SIMD.float32x4.mul(f, f);
  34404. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34405. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34406. // cc.kmVec3Assign(up, pUp);
  34407. // cc.kmVec3Normalize(up, up);
  34408. tmp = SIMD.float32x4.mul(up, up);
  34409. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34410. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34411. // cc.kmVec3Cross(s, f, up);
  34412. 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)));
  34413. // cc.kmVec3Normalize(s, s);
  34414. tmp = SIMD.float32x4.mul(s, s);
  34415. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34416. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34417. // cc.kmVec3Cross(u, s, f);
  34418. 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)));
  34419. // cc.kmVec3Normalize(s, s);
  34420. tmp = SIMD.float32x4.mul(s, s);
  34421. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34422. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34423. var zero = SIMD.float32x4.splat(0.0);
  34424. s = SIMD.float32x4.neg(s);
  34425. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34426. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34427. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34428. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34429. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34430. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34431. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34432. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34433. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34434. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34435. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34436. var b3 = SIMD.float32x4.neg(eye);
  34437. b3 = SIMD.float32x4.withW(b3, 1.0);
  34438. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  34439. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  34440. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  34441. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  34442. };
  34443. return SIMDMatrix;
  34444. })();
  34445. BABYLON.SIMDMatrix = SIMDMatrix;
  34446. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34447. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34448. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34449. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34450. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34451. var SIMDHelper = (function () {
  34452. function SIMDHelper() {
  34453. }
  34454. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34455. get: function () {
  34456. return SIMDHelper._isEnabled;
  34457. },
  34458. enumerable: true,
  34459. configurable: true
  34460. });
  34461. SIMDHelper.DisableSIMD = function () {
  34462. // Replace functions
  34463. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34464. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34465. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34466. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34467. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34468. SIMDHelper._isEnabled = false;
  34469. };
  34470. SIMDHelper.EnableSIMD = function () {
  34471. if (window.SIMD === undefined) {
  34472. return;
  34473. }
  34474. // Replace functions
  34475. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34476. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34477. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34478. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34480. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34481. get: function () { return this._data[0]; },
  34482. set: function (value) {
  34483. if (!this._data) {
  34484. this._data = new Float32Array(3);
  34485. }
  34486. this._data[0] = value;
  34487. }
  34488. });
  34489. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34490. get: function () { return this._data[1]; },
  34491. set: function (value) {
  34492. this._data[1] = value;
  34493. }
  34494. });
  34495. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34496. get: function () { return this._data[2]; },
  34497. set: function (value) {
  34498. this._data[2] = value;
  34499. }
  34500. });
  34501. SIMDHelper._isEnabled = true;
  34502. };
  34503. SIMDHelper._isEnabled = false;
  34504. return SIMDHelper;
  34505. })();
  34506. BABYLON.SIMDHelper = SIMDHelper;
  34507. })(BABYLON || (BABYLON = {}));
  34508. var BABYLON;
  34509. (function (BABYLON) {
  34510. /**
  34511. * This class describe a rectangle that were added to the map.
  34512. * You have access to its coordinates either in pixel or normalized (UV)
  34513. */
  34514. var PackedRect = (function () {
  34515. function PackedRect(root, parent, pos, size) {
  34516. this._pos = pos;
  34517. this._size = size;
  34518. this._root = root;
  34519. this._parent = parent;
  34520. }
  34521. Object.defineProperty(PackedRect.prototype, "pos", {
  34522. /**
  34523. * @returns the position of this node into the map
  34524. */
  34525. get: function () {
  34526. return this._pos;
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34532. /**
  34533. * @returns the size of the rectangle this node handles
  34534. */
  34535. get: function () {
  34536. return this._contentSize;
  34537. },
  34538. enumerable: true,
  34539. configurable: true
  34540. });
  34541. Object.defineProperty(PackedRect.prototype, "UVs", {
  34542. /**
  34543. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34544. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34545. */
  34546. get: function () {
  34547. var mainWidth = this._root._size.width;
  34548. var mainHeight = this._root._size.height;
  34549. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34550. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34551. var uvs = new Array();
  34552. uvs.push(topLeft);
  34553. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34554. uvs.push(rightBottom);
  34555. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34556. return uvs;
  34557. },
  34558. enumerable: true,
  34559. configurable: true
  34560. });
  34561. /**
  34562. * Free this rectangle from the map.
  34563. * Call this method when you no longer need the rectangle to be in the map.
  34564. */
  34565. PackedRect.prototype.freeContent = function () {
  34566. if (!this.contentSize) {
  34567. return;
  34568. }
  34569. this._contentSize = null;
  34570. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34571. this.attemptDefrag();
  34572. };
  34573. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34574. get: function () {
  34575. return this._contentSize != null || this._leftNode != null;
  34576. },
  34577. enumerable: true,
  34578. configurable: true
  34579. });
  34580. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34581. var node = this.findNode(contentSize);
  34582. // Not enough space...
  34583. if (!node) {
  34584. return null;
  34585. }
  34586. node.splitNode(contentSize);
  34587. return node;
  34588. };
  34589. PackedRect.prototype.findNode = function (size) {
  34590. var resNode = null;
  34591. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  34592. if (this.isUsed) {
  34593. if (this._leftNode) {
  34594. resNode = this._leftNode.findNode(size);
  34595. }
  34596. if (!resNode && this._rightNode) {
  34597. resNode = this._rightNode.findNode(size);
  34598. }
  34599. if (!resNode && this._bottomNode) {
  34600. resNode = this._bottomNode.findNode(size);
  34601. }
  34602. }
  34603. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  34604. resNode = this;
  34605. }
  34606. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  34607. resNode = this;
  34608. }
  34609. return resNode;
  34610. };
  34611. PackedRect.prototype.splitNode = function (contentSize) {
  34612. // 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)
  34613. if (!this._contentSize && this._initialSize) {
  34614. 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));
  34615. return this._leftNode.splitNode(contentSize);
  34616. }
  34617. else {
  34618. this._contentSize = contentSize.clone();
  34619. this._initialSize = contentSize.clone();
  34620. if (contentSize.width !== this._size.width) {
  34621. 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));
  34622. }
  34623. if (contentSize.height !== this._size.height) {
  34624. 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));
  34625. }
  34626. return this;
  34627. }
  34628. };
  34629. PackedRect.prototype.attemptDefrag = function () {
  34630. if (!this.isUsed && this.isRecursiveFree) {
  34631. this.clearNode();
  34632. if (this._parent) {
  34633. this._parent.attemptDefrag();
  34634. }
  34635. }
  34636. };
  34637. PackedRect.prototype.clearNode = function () {
  34638. this._initialSize = null;
  34639. this._rightNode = null;
  34640. this._bottomNode = null;
  34641. };
  34642. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  34643. get: function () {
  34644. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. PackedRect.prototype.evalFreeSize = function (size) {
  34650. var levelSize = 0;
  34651. if (!this.isUsed) {
  34652. if (this._initialSize) {
  34653. levelSize = this._initialSize.surface;
  34654. }
  34655. else {
  34656. levelSize = this._size.surface;
  34657. }
  34658. }
  34659. if (this._rightNode) {
  34660. levelSize += this._rightNode.evalFreeSize(0);
  34661. }
  34662. if (this._bottomNode) {
  34663. levelSize += this._bottomNode.evalFreeSize(0);
  34664. }
  34665. return levelSize + size;
  34666. };
  34667. return PackedRect;
  34668. })();
  34669. BABYLON.PackedRect = PackedRect;
  34670. /**
  34671. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  34672. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  34673. * 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.
  34674. */
  34675. var RectPackingMap = (function (_super) {
  34676. __extends(RectPackingMap, _super);
  34677. /**
  34678. * Create an instance of the object with a dimension using the given size
  34679. * @param size The dimension of the rectangle that will contain all the sub ones.
  34680. */
  34681. function RectPackingMap(size) {
  34682. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  34683. this._root = this;
  34684. }
  34685. /**
  34686. * Add a rectangle, finding the best location to store it into the map
  34687. * @param size the dimension of the rectangle to store
  34688. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  34689. */
  34690. RectPackingMap.prototype.addRect = function (size) {
  34691. var node = this.findAndSplitNode(size);
  34692. return node;
  34693. };
  34694. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  34695. /**
  34696. * Return the current space free normalized between [0;1]
  34697. * @returns {}
  34698. */
  34699. get: function () {
  34700. var freeSize = 0;
  34701. freeSize = this.evalFreeSize(freeSize);
  34702. return freeSize / (this._size.width * this._size.height);
  34703. },
  34704. enumerable: true,
  34705. configurable: true
  34706. });
  34707. return RectPackingMap;
  34708. })(PackedRect);
  34709. BABYLON.RectPackingMap = RectPackingMap;
  34710. })(BABYLON || (BABYLON = {}));
  34711. var BABYLON;
  34712. (function (BABYLON) {
  34713. var DynamicFloatArrayElementInfo = (function () {
  34714. function DynamicFloatArrayElementInfo() {
  34715. }
  34716. return DynamicFloatArrayElementInfo;
  34717. })();
  34718. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  34719. /**
  34720. * 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.
  34721. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  34722. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  34723. * 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.
  34724. * 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.
  34725. * 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".
  34726. */
  34727. var DynamicFloatArray = (function () {
  34728. /**
  34729. * Construct an instance of the dynamic float array
  34730. * @param stride size of one element in float (i.e. not bytes!)
  34731. * @param initialElementCount the number of available entries at construction
  34732. */
  34733. function DynamicFloatArray(stride, initialElementCount) {
  34734. this._stride = stride;
  34735. this.buffer = new Float32Array(stride * initialElementCount);
  34736. this._lastUsed = 0;
  34737. this._firstFree = 0;
  34738. this._allEntries = new Array(initialElementCount);
  34739. this._freeEntries = new Array(initialElementCount);
  34740. for (var i = 0; i < initialElementCount; i++) {
  34741. var element = new DynamicFloatArrayElementInfo();
  34742. element.offset = i * stride;
  34743. this._allEntries[i] = element;
  34744. this._freeEntries[initialElementCount - i - 1] = element;
  34745. }
  34746. }
  34747. /**
  34748. * Allocate an element in the array.
  34749. * @return the element info instance that contains the offset into the main buffer of the element's location.
  34750. * Beware, this offset may change when you call pack()
  34751. */
  34752. DynamicFloatArray.prototype.allocElement = function () {
  34753. if (this._freeEntries.length === 0) {
  34754. this._growBuffer();
  34755. }
  34756. var el = this._freeEntries.pop();
  34757. this._lastUsed = Math.max(el.offset, this._lastUsed);
  34758. if (el.offset === this._firstFree) {
  34759. if (this._freeEntries.length > 0) {
  34760. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  34761. }
  34762. else {
  34763. this._firstFree += this._stride;
  34764. }
  34765. }
  34766. return el;
  34767. };
  34768. /**
  34769. * Free the element corresponding to the given element info
  34770. * @param elInfo the element that describe the allocated element
  34771. */
  34772. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  34773. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  34774. this._freeEntries.push(elInfo);
  34775. };
  34776. /**
  34777. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  34778. * 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().
  34779. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  34780. */
  34781. DynamicFloatArray.prototype.pack = function () {
  34782. // no free slot? no need to pack
  34783. if (this._freeEntries.length === 0) {
  34784. return this.buffer;
  34785. }
  34786. // If the buffer is already packed the last used will always be lower than the first free
  34787. if (this._lastUsed < this._firstFree) {
  34788. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  34789. return elementsBuffer_1;
  34790. }
  34791. var s = this._stride;
  34792. // 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
  34793. var lastFree = new DynamicFloatArrayElementInfo();
  34794. lastFree.offset = this.totalElementCount * s;
  34795. this._freeEntries.push(lastFree);
  34796. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  34797. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  34798. var firstFreeSlotOffset = sortedFree[0].offset;
  34799. var freeZoneSize = 1;
  34800. var occupiedZoneSize = this.usedElementCount * s;
  34801. var prevOffset = sortedFree[0].offset;
  34802. for (var i = 1; i < sortedFree.length; i++) {
  34803. // 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
  34804. if (firstFreeSlotOffset >= occupiedZoneSize) {
  34805. break;
  34806. }
  34807. var curFree = sortedFree[i];
  34808. var curOffset = curFree.offset;
  34809. // Compute the distance between this offset and the previous
  34810. var distance = curOffset - prevOffset;
  34811. // If the distance is the stride size, they are adjacent, it good, move to the next
  34812. if (distance === s) {
  34813. // Free zone is one element bigger
  34814. ++freeZoneSize;
  34815. // as we're about to iterate to the next, the cur becomes the previous...
  34816. prevOffset = curOffset;
  34817. continue;
  34818. }
  34819. // Distance is bigger, which means there's x element between the previous free and this one
  34820. var usedRange = (distance / s) - 1;
  34821. // Two cases the free zone is smaller than the data to move or bigger
  34822. // Copy what can fit in the free zone
  34823. var curMoveOffset = curOffset - s;
  34824. var copyCount = Math.min(freeZoneSize, usedRange);
  34825. for (var j = 0; j < copyCount; j++) {
  34826. var freeI = firstFreeSlotOffset / s;
  34827. var curI = curMoveOffset / s;
  34828. var moveEl = sortedAll[curI];
  34829. this._moveElement(moveEl, firstFreeSlotOffset);
  34830. var replacedEl = sortedAll[freeI];
  34831. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  34832. replacedEl.offset = curMoveOffset;
  34833. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  34834. sortedAll[freeI] = moveEl;
  34835. sortedAll[curI] = replacedEl;
  34836. curMoveOffset -= s;
  34837. firstFreeSlotOffset += s;
  34838. }
  34839. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  34840. if (freeZoneSize <= usedRange) {
  34841. firstFreeSlotOffset = curMoveOffset + s;
  34842. freeZoneSize = 1;
  34843. }
  34844. else {
  34845. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  34846. }
  34847. // as we're about to iterate to the next, the cur becomes the previous...
  34848. prevOffset = curOffset;
  34849. }
  34850. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  34851. this._lastUsed = firstFreeSlotOffset - s;
  34852. this._firstFree = firstFreeSlotOffset;
  34853. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  34854. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  34855. this._allEntries = sortedAll;
  34856. return elementsBuffer;
  34857. };
  34858. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  34859. for (var i = 0; i < this._stride; i++) {
  34860. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  34861. }
  34862. element.offset = destOffset;
  34863. };
  34864. DynamicFloatArray.prototype._growBuffer = function () {
  34865. // Allocate the new buffer with 50% more entries, copy the content of the current one
  34866. var newElCount = Math.floor(this.totalElementCount * 1.5);
  34867. var newBuffer = new Float32Array(newElCount * this._stride);
  34868. newBuffer.set(this.buffer);
  34869. var curCount = this.totalElementCount;
  34870. var addedCount = newElCount - this.totalElementCount;
  34871. for (var i = 0; i < addedCount; i++) {
  34872. var element = new DynamicFloatArrayElementInfo();
  34873. element.offset = (curCount + i) * this.stride;
  34874. this._allEntries.push(element);
  34875. this._freeEntries[addedCount - i - 1] = element;
  34876. }
  34877. this._firstFree = curCount * this.stride;
  34878. this.buffer = newBuffer;
  34879. };
  34880. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  34881. /**
  34882. * Get the total count of entries that can fit in the current buffer
  34883. * @returns the elements count
  34884. */
  34885. get: function () {
  34886. return this._allEntries.length;
  34887. },
  34888. enumerable: true,
  34889. configurable: true
  34890. });
  34891. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  34892. /**
  34893. * Get the count of free entries that can still be allocated without resizing the buffer
  34894. * @returns the free elements count
  34895. */
  34896. get: function () {
  34897. return this._freeEntries.length;
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  34903. /**
  34904. * Get the count of allocated elements
  34905. * @returns the allocated elements count
  34906. */
  34907. get: function () {
  34908. return this._allEntries.length - this._freeEntries.length;
  34909. },
  34910. enumerable: true,
  34911. configurable: true
  34912. });
  34913. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  34914. /**
  34915. * Return the size of one element in float
  34916. * @returns the size in float
  34917. */
  34918. get: function () {
  34919. return this._stride;
  34920. },
  34921. enumerable: true,
  34922. configurable: true
  34923. });
  34924. return DynamicFloatArray;
  34925. })();
  34926. BABYLON.DynamicFloatArray = DynamicFloatArray;
  34927. })(BABYLON || (BABYLON = {}));
  34928. var BABYLON;
  34929. (function (BABYLON) {
  34930. /**
  34931. * This class given information about a given character.
  34932. */
  34933. var CharInfo = (function () {
  34934. function CharInfo() {
  34935. }
  34936. return CharInfo;
  34937. })();
  34938. BABYLON.CharInfo = CharInfo;
  34939. var FontTexture = (function (_super) {
  34940. __extends(FontTexture, _super);
  34941. /**
  34942. * Create a new instance of the FontTexture class
  34943. * @param name the name of the texture
  34944. * @param font the font to use, use the W3C CSS notation
  34945. * @param scene the scene that owns the texture
  34946. * @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
  34947. * @param samplingMode the texture sampling mode
  34948. */
  34949. function FontTexture(name, font, scene, maxCharCount, samplingMode) {
  34950. if (maxCharCount === void 0) { maxCharCount = 200; }
  34951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34952. _super.call(this, null, scene, true, false, samplingMode);
  34953. this._charInfos = {};
  34954. this._curCharCount = 0;
  34955. this._lastUpdateCharCount = -1;
  34956. this._usedCounter = 1;
  34957. this.name = name;
  34958. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34959. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34960. // First canvas creation to determine the size of the texture to create
  34961. this._canvas = document.createElement("canvas");
  34962. this._context = this._canvas.getContext("2d");
  34963. this._context.font = font;
  34964. this._context.fillStyle = "white";
  34965. var res = this.getFontHeight(font);
  34966. this._lineHeight = res.height;
  34967. this._offset = res.offset - 1;
  34968. var maxCharWidth = this._context.measureText("W").width;
  34969. this._spaceWidth = this._context.measureText(" ").width;
  34970. // This is an approximate size, but should always be able to fit at least the maxCharCount
  34971. var totalEstSurface = this._lineHeight * maxCharWidth * maxCharCount;
  34972. var edge = Math.sqrt(totalEstSurface);
  34973. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  34974. // Create the texture that will store the font characters
  34975. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  34976. var textureSize = this.getSize();
  34977. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  34978. this._canvas = document.createElement("canvas");
  34979. this._canvas.width = textureSize.width;
  34980. this._canvas.height = textureSize.height;
  34981. this._context = this._canvas.getContext("2d");
  34982. this._context.textBaseline = "top";
  34983. this._context.font = font;
  34984. this._context.fillStyle = "white";
  34985. this._context.imageSmoothingEnabled = false;
  34986. this._currentFreePosition = BABYLON.Vector2.Zero();
  34987. // Add the basic ASCII based characters
  34988. for (var i = 0x20; i < 0x7F; i++) {
  34989. var c = String.fromCharCode(i);
  34990. this.getChar(c);
  34991. }
  34992. this.update();
  34993. }
  34994. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  34995. get: function () {
  34996. return this._spaceWidth;
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  35002. get: function () {
  35003. return this._lineHeight;
  35004. },
  35005. enumerable: true,
  35006. configurable: true
  35007. });
  35008. FontTexture.GetCachedFontTexture = function (scene, fontName) {
  35009. var s = scene;
  35010. if (!s.__fontTextureCache__) {
  35011. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  35012. }
  35013. var dic = s.__fontTextureCache__;
  35014. var lfn = fontName.toLocaleLowerCase();
  35015. var ft = dic.get(lfn);
  35016. if (ft) {
  35017. ++ft._usedCounter;
  35018. return ft;
  35019. }
  35020. ft = new FontTexture(null, lfn, scene, 200, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  35021. dic.add(lfn, ft);
  35022. return ft;
  35023. };
  35024. FontTexture.ReleaseCachedFontTexture = function (scene, fontName) {
  35025. var s = scene;
  35026. var dic = s.__fontTextureCache__;
  35027. if (!dic) {
  35028. return;
  35029. }
  35030. var lfn = fontName.toLocaleLowerCase();
  35031. var font = dic.get(lfn);
  35032. if (--font._usedCounter === 0) {
  35033. dic.remove(lfn);
  35034. font.dispose();
  35035. }
  35036. };
  35037. /**
  35038. * Make sure the given char is present in the font map.
  35039. * @param char the character to get or add
  35040. * @return the CharInfo instance corresponding to the given character
  35041. */
  35042. FontTexture.prototype.getChar = function (char) {
  35043. if (char.length !== 1) {
  35044. return null;
  35045. }
  35046. var info = this._charInfos[char];
  35047. if (info) {
  35048. return info;
  35049. }
  35050. info = new CharInfo();
  35051. var measure = this._context.measureText(char);
  35052. var textureSize = this.getSize();
  35053. // we reached the end of the current line?
  35054. var xMargin = 2;
  35055. var yMargin = 2;
  35056. var width = measure.width;
  35057. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  35058. this._currentFreePosition.x = 0;
  35059. this._currentFreePosition.y += this._lineHeight + yMargin; // +2 for safety margin
  35060. // No more room?
  35061. if (this._currentFreePosition.y > textureSize.height) {
  35062. return this.getChar("!");
  35063. }
  35064. }
  35065. // Draw the character in the texture
  35066. this._context.fillText(char, this._currentFreePosition.x - 0.5, this._currentFreePosition.y - this._offset - 0.5);
  35067. // Fill the CharInfo object
  35068. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  35069. info.bottomRightUV = new BABYLON.Vector2(info.topLeftUV.x + (width / textureSize.width), info.topLeftUV.y + ((this._lineHeight + 2) / textureSize.height));
  35070. info.charWidth = width;
  35071. // Add the info structure
  35072. this._charInfos[char] = info;
  35073. this._curCharCount++;
  35074. // Set the next position
  35075. this._currentFreePosition.x += width + xMargin;
  35076. return info;
  35077. };
  35078. FontTexture.prototype.measureText = function (text, tabulationSize) {
  35079. if (tabulationSize === void 0) { tabulationSize = 4; }
  35080. var maxWidth = 0;
  35081. var curWidth = 0;
  35082. var lineCount = 1;
  35083. var charxpos = 0;
  35084. // Parse each char of the string
  35085. for (var _i = 0; _i < text.length; _i++) {
  35086. var char = text[_i];
  35087. // Next line feed?
  35088. if (char === "\n") {
  35089. maxWidth = Math.max(maxWidth, curWidth);
  35090. charxpos = 0;
  35091. curWidth = 0;
  35092. ++lineCount;
  35093. continue;
  35094. }
  35095. // Tabulation ?
  35096. if (char === "\t") {
  35097. var nextPos = charxpos + tabulationSize;
  35098. nextPos = nextPos - (nextPos % tabulationSize);
  35099. curWidth += (nextPos - charxpos) * this.spaceWidth;
  35100. charxpos = nextPos;
  35101. continue;
  35102. }
  35103. if (char < " ") {
  35104. continue;
  35105. }
  35106. curWidth += this.getChar(char).charWidth;
  35107. ++charxpos;
  35108. }
  35109. maxWidth = Math.max(maxWidth, curWidth);
  35110. return new BABYLON.Size(maxWidth, lineCount * this._lineHeight);
  35111. };
  35112. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  35113. FontTexture.prototype.getFontHeight = function (font) {
  35114. var fontDraw = document.createElement("canvas");
  35115. var ctx = fontDraw.getContext('2d');
  35116. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  35117. ctx.textBaseline = 'top';
  35118. ctx.fillStyle = 'white';
  35119. ctx.font = font;
  35120. ctx.fillText('jH|', 0, 0);
  35121. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  35122. var start = -1;
  35123. var end = -1;
  35124. for (var row = 0; row < fontDraw.height; row++) {
  35125. for (var column = 0; column < fontDraw.width; column++) {
  35126. var index = (row * fontDraw.width + column) * 4;
  35127. if (pixels[index] === 0) {
  35128. if (column === fontDraw.width - 1 && start !== -1) {
  35129. end = row;
  35130. row = fontDraw.height;
  35131. break;
  35132. }
  35133. continue;
  35134. }
  35135. else {
  35136. if (start === -1) {
  35137. start = row;
  35138. }
  35139. break;
  35140. }
  35141. }
  35142. }
  35143. return { height: end - start, offset: start - 1 };
  35144. };
  35145. Object.defineProperty(FontTexture.prototype, "canRescale", {
  35146. get: function () {
  35147. return false;
  35148. },
  35149. enumerable: true,
  35150. configurable: true
  35151. });
  35152. FontTexture.prototype.getContext = function () {
  35153. return this._context;
  35154. };
  35155. /**
  35156. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  35157. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  35158. */
  35159. FontTexture.prototype.update = function () {
  35160. // Update only if there's new char added since the previous update
  35161. if (this._lastUpdateCharCount < this._curCharCount) {
  35162. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  35163. this._lastUpdateCharCount = this._curCharCount;
  35164. }
  35165. };
  35166. // cloning should be prohibited, there's no point to duplicate this texture at all
  35167. FontTexture.prototype.clone = function () {
  35168. return null;
  35169. };
  35170. return FontTexture;
  35171. })(BABYLON.Texture);
  35172. BABYLON.FontTexture = FontTexture;
  35173. })(BABYLON || (BABYLON = {}));
  35174. var BABYLON;
  35175. (function (BABYLON) {
  35176. var MapTexture = (function (_super) {
  35177. __extends(MapTexture, _super);
  35178. function MapTexture(name, scene, size, samplingMode) {
  35179. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  35180. _super.call(this, null, scene, true, false, samplingMode);
  35181. this.name = name;
  35182. this._size = size;
  35183. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35184. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35185. // Create the rectPackMap that will allocate portion of the texture
  35186. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  35187. // Create the texture that will store the content
  35188. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  35189. }
  35190. /**
  35191. * Allocate a rectangle of a given size in the texture map
  35192. * @param size the size of the rectangle to allocation
  35193. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  35194. */
  35195. MapTexture.prototype.allocateRect = function (size) {
  35196. return this._rectPackingMap.addRect(size);
  35197. };
  35198. /**
  35199. * Free a given rectangle from the texture map
  35200. * @param rectInfo the instance corresponding to the rect to free.
  35201. */
  35202. MapTexture.prototype.freeRect = function (rectInfo) {
  35203. if (rectInfo) {
  35204. rectInfo.freeContent();
  35205. }
  35206. };
  35207. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  35208. /**
  35209. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  35210. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  35211. * @returns {}
  35212. */
  35213. get: function () {
  35214. return this._rectPackingMap.freeSpace;
  35215. },
  35216. enumerable: true,
  35217. configurable: true
  35218. });
  35219. /**
  35220. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  35221. * 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.
  35222. * Don't forget to call unbindTexture when you're done rendering
  35223. * @param rect the zone to render to
  35224. * @param clear true to clear the portion's color/depth data
  35225. */
  35226. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  35227. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  35228. };
  35229. /**
  35230. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  35231. * 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.
  35232. * Don't forget to call unbindTexture when you're done rendering
  35233. * @param pos the position into the texture
  35234. * @param size the portion to fit the clip space to
  35235. * @param clear true to clear the portion's color/depth data
  35236. */
  35237. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  35238. var engine = this.getScene().getEngine();
  35239. engine.bindFramebuffer(this._texture);
  35240. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  35241. if (clear) {
  35242. var gl = engine._gl;
  35243. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  35244. // Save state
  35245. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  35246. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  35247. // Change state
  35248. gl.enable(gl.SCISSOR_TEST);
  35249. gl.scissor(pos.x, pos.y, size.width, size.height);
  35250. // Clear
  35251. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  35252. // Restore state
  35253. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  35254. if (curScissor === true) {
  35255. gl.enable(gl.SCISSOR_TEST);
  35256. }
  35257. else {
  35258. gl.disable(gl.SCISSOR_TEST);
  35259. }
  35260. }
  35261. };
  35262. /**
  35263. * Unbind the texture map from the rendering engine.
  35264. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  35265. * @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.
  35266. */
  35267. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  35268. // Dump ?
  35269. if (dumpForDebug) {
  35270. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  35271. }
  35272. var engine = this.getScene().getEngine();
  35273. if (this._replacedViewport) {
  35274. engine.setViewport(this._replacedViewport);
  35275. this._replacedViewport = null;
  35276. }
  35277. engine.unBindFramebuffer(this._texture);
  35278. };
  35279. Object.defineProperty(MapTexture.prototype, "canRescale", {
  35280. get: function () {
  35281. return false;
  35282. },
  35283. enumerable: true,
  35284. configurable: true
  35285. });
  35286. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  35287. // Anyway, there's not much point to use this method for this kind of texture I guess
  35288. MapTexture.prototype.clone = function () {
  35289. return null;
  35290. };
  35291. return MapTexture;
  35292. })(BABYLON.Texture);
  35293. BABYLON.MapTexture = MapTexture;
  35294. })(BABYLON || (BABYLON = {}));
  35295. var BABYLON;
  35296. (function (BABYLON) {
  35297. /**
  35298. * Stores 2D Bounding Information.
  35299. * This class handles a circle area and a bounding rectangle one.
  35300. */
  35301. var BoundingInfo2D = (function () {
  35302. function BoundingInfo2D() {
  35303. this.radius = 0;
  35304. this.center = BABYLON.Vector2.Zero();
  35305. this.extent = BABYLON.Vector2.Zero();
  35306. }
  35307. BoundingInfo2D.CreateFromSize = function (size, origin) {
  35308. var r = new BoundingInfo2D();
  35309. BoundingInfo2D.CreateFromSizeToRef(size, r, origin);
  35310. return r;
  35311. };
  35312. BoundingInfo2D.CreateFromRadius = function (radius, origin) {
  35313. var r = new BoundingInfo2D();
  35314. BoundingInfo2D.CreateFromRadiusToRef(radius, r, origin);
  35315. return r;
  35316. };
  35317. BoundingInfo2D.CreateFromPoints = function (points, origin) {
  35318. var r = new BoundingInfo2D();
  35319. BoundingInfo2D.CreateFromPointsToRef(points, r, origin);
  35320. return r;
  35321. };
  35322. BoundingInfo2D.CreateFromSizeToRef = function (size, b, origin) {
  35323. b.center = new BABYLON.Vector2(size.width / 2, size.height / 2);
  35324. b.extent = b.center.clone();
  35325. if (origin) {
  35326. b.center.x -= size.width * origin.x;
  35327. b.center.y -= size.height * origin.y;
  35328. }
  35329. b.radius = b.extent.length();
  35330. };
  35331. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b, origin) {
  35332. b.center = BABYLON.Vector2.Zero();
  35333. if (origin) {
  35334. b.center.x -= radius * origin.x;
  35335. b.center.y -= radius * origin.y;
  35336. }
  35337. b.extent = new BABYLON.Vector2(radius, radius);
  35338. b.radius = radius;
  35339. };
  35340. BoundingInfo2D.CreateFromPointsToRef = function (points, b, origin) {
  35341. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  35342. for (var _i = 0; _i < points.length; _i++) {
  35343. var p = points[_i];
  35344. xmin = Math.min(p.x, xmin);
  35345. xmax = Math.max(p.x, xmax);
  35346. ymin = Math.min(p.y, ymin);
  35347. ymax = Math.max(p.y, ymax);
  35348. }
  35349. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b, origin);
  35350. };
  35351. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b, origin) {
  35352. var w = xmax - xmin;
  35353. var h = ymax - ymin;
  35354. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  35355. if (origin) {
  35356. b.center.x -= w * origin.x;
  35357. b.center.y -= h * origin.y;
  35358. }
  35359. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  35360. b.radius = b.extent.length();
  35361. };
  35362. /**
  35363. * Duplicate this instance and return a new one
  35364. * @return the duplicated instance
  35365. */
  35366. BoundingInfo2D.prototype.clone = function () {
  35367. var r = new BoundingInfo2D();
  35368. r.center = this.center.clone();
  35369. r.radius = this.radius;
  35370. r.extent = this.extent.clone();
  35371. return r;
  35372. };
  35373. BoundingInfo2D.prototype.max = function () {
  35374. var r = BABYLON.Vector2.Zero();
  35375. this.maxToRef(r);
  35376. return r;
  35377. };
  35378. BoundingInfo2D.prototype.maxToRef = function (result) {
  35379. result.x = this.center.x + this.extent.x;
  35380. result.y = this.center.y + this.extent.y;
  35381. };
  35382. /**
  35383. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  35384. * @param matrix the transformation matrix to apply
  35385. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  35386. */
  35387. BoundingInfo2D.prototype.transform = function (matrix) {
  35388. var r = new BoundingInfo2D();
  35389. this.transformToRef(matrix, r);
  35390. return r;
  35391. };
  35392. /**
  35393. * Compute the union of this BoundingInfo2D with a given one, return a new BoundingInfo2D as a result
  35394. * @param other the second BoundingInfo2D to compute the union with this one
  35395. * @return a new instance containing the result of the union
  35396. */
  35397. BoundingInfo2D.prototype.union = function (other) {
  35398. var r = new BoundingInfo2D();
  35399. this.unionToRef(other, r);
  35400. return r;
  35401. };
  35402. /**
  35403. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  35404. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  35405. * @param matrix The matrix to use to compute the transformation
  35406. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  35407. */
  35408. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  35409. // Construct a bounding box based on the extent values
  35410. var p = new Array(4);
  35411. p[0] = new BABYLON.Vector2(this.center.x + this.extent.x, this.center.y + this.extent.y);
  35412. p[1] = new BABYLON.Vector2(this.center.x + this.extent.x, this.center.y - this.extent.y);
  35413. p[2] = new BABYLON.Vector2(this.center.x - this.extent.x, this.center.y - this.extent.y);
  35414. p[3] = new BABYLON.Vector2(this.center.x - this.extent.x, this.center.y + this.extent.y);
  35415. // Transform the four points of the bounding box with the matrix
  35416. for (var i = 0; i < 4; i++) {
  35417. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  35418. }
  35419. BoundingInfo2D.CreateFromPointsToRef(p, result);
  35420. };
  35421. /**
  35422. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  35423. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  35424. * @param other the second object used to compute the union
  35425. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  35426. */
  35427. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  35428. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  35429. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  35430. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  35431. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  35432. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  35433. };
  35434. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  35435. // is it inside the radius?
  35436. var pickLocal = pickPosition.subtract(this.center);
  35437. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  35438. // is it inside the rectangle?
  35439. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  35440. }
  35441. return false;
  35442. };
  35443. return BoundingInfo2D;
  35444. })();
  35445. BABYLON.BoundingInfo2D = BoundingInfo2D;
  35446. })(BABYLON || (BABYLON = {}));
  35447. var BABYLON;
  35448. (function (BABYLON) {
  35449. /**
  35450. * Base class implementing the ILocable interface.
  35451. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  35452. */
  35453. var LockableBase = (function () {
  35454. function LockableBase() {
  35455. }
  35456. LockableBase.prototype.isLocked = function () {
  35457. return this._isLocked;
  35458. };
  35459. LockableBase.prototype.lock = function () {
  35460. if (this._isLocked) {
  35461. return true;
  35462. }
  35463. this.onLock();
  35464. this._isLocked = true;
  35465. return false;
  35466. };
  35467. /**
  35468. * Protected handler that will be called when the instance is about to be locked.
  35469. */
  35470. LockableBase.prototype.onLock = function () {
  35471. };
  35472. return LockableBase;
  35473. })();
  35474. BABYLON.LockableBase = LockableBase;
  35475. /**
  35476. * This class implements a Brush that will be drawn with a uniform solid color (i.e. the same color everywhere in the content where the brush is assigned to).
  35477. */
  35478. var SolidColorBrush2D = (function (_super) {
  35479. __extends(SolidColorBrush2D, _super);
  35480. function SolidColorBrush2D(color, lock) {
  35481. if (lock === void 0) { lock = false; }
  35482. _super.call(this);
  35483. this._color = color;
  35484. if (lock) {
  35485. {
  35486. this.lock();
  35487. }
  35488. }
  35489. }
  35490. SolidColorBrush2D.prototype.isTransparent = function () {
  35491. return this._color && this._color.a < 1.0;
  35492. };
  35493. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  35494. /**
  35495. * The color used by this instance to render
  35496. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  35497. */
  35498. get: function () {
  35499. return this._color;
  35500. },
  35501. set: function (value) {
  35502. if (this.isLocked()) {
  35503. return;
  35504. }
  35505. this._color = value;
  35506. },
  35507. enumerable: true,
  35508. configurable: true
  35509. });
  35510. /**
  35511. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  35512. */
  35513. SolidColorBrush2D.prototype.toString = function () {
  35514. return this._color.toHexString();
  35515. };
  35516. SolidColorBrush2D = __decorate([
  35517. BABYLON.className("SolidColorBrush2D")
  35518. ], SolidColorBrush2D);
  35519. return SolidColorBrush2D;
  35520. })(LockableBase);
  35521. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  35522. var GradientColorBrush2D = (function (_super) {
  35523. __extends(GradientColorBrush2D, _super);
  35524. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  35525. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  35526. if (rotation === void 0) { rotation = 0; }
  35527. if (scale === void 0) { scale = 1; }
  35528. if (lock === void 0) { lock = false; }
  35529. _super.call(this);
  35530. this._color1 = color1;
  35531. this._color2 = color2;
  35532. this._translation = translation;
  35533. this._rotation = rotation;
  35534. this._scale = scale;
  35535. if (lock) {
  35536. this.lock();
  35537. }
  35538. }
  35539. GradientColorBrush2D.prototype.isTransparent = function () {
  35540. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  35541. };
  35542. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  35543. get: function () {
  35544. return this._color1;
  35545. },
  35546. set: function (value) {
  35547. if (this.isLocked()) {
  35548. return;
  35549. }
  35550. this._color1 = value;
  35551. },
  35552. enumerable: true,
  35553. configurable: true
  35554. });
  35555. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  35556. get: function () {
  35557. return this._color2;
  35558. },
  35559. set: function (value) {
  35560. if (this.isLocked()) {
  35561. return;
  35562. }
  35563. this._color2 = value;
  35564. },
  35565. enumerable: true,
  35566. configurable: true
  35567. });
  35568. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  35569. get: function () {
  35570. return this._translation;
  35571. },
  35572. set: function (value) {
  35573. if (this.isLocked()) {
  35574. return;
  35575. }
  35576. this._translation = value;
  35577. },
  35578. enumerable: true,
  35579. configurable: true
  35580. });
  35581. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  35582. get: function () {
  35583. return this._rotation;
  35584. },
  35585. set: function (value) {
  35586. if (this.isLocked()) {
  35587. return;
  35588. }
  35589. this._rotation = value;
  35590. },
  35591. enumerable: true,
  35592. configurable: true
  35593. });
  35594. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  35595. get: function () {
  35596. return this._scale;
  35597. },
  35598. set: function (value) {
  35599. if (this.isLocked()) {
  35600. return;
  35601. }
  35602. this._scale = value;
  35603. },
  35604. enumerable: true,
  35605. configurable: true
  35606. });
  35607. GradientColorBrush2D.prototype.toString = function () {
  35608. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  35609. };
  35610. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  35611. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  35612. };
  35613. GradientColorBrush2D = __decorate([
  35614. BABYLON.className("GradientColorBrush2D")
  35615. ], GradientColorBrush2D);
  35616. return GradientColorBrush2D;
  35617. })(LockableBase);
  35618. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  35619. })(BABYLON || (BABYLON = {}));
  35620. var BABYLON;
  35621. (function (BABYLON) {
  35622. var Prim2DClassInfo = (function () {
  35623. function Prim2DClassInfo() {
  35624. }
  35625. return Prim2DClassInfo;
  35626. })();
  35627. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  35628. var Prim2DPropInfo = (function () {
  35629. function Prim2DPropInfo() {
  35630. }
  35631. Prim2DPropInfo.PROPKIND_MODEL = 1;
  35632. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  35633. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  35634. return Prim2DPropInfo;
  35635. })();
  35636. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  35637. var PropertyChangedInfo = (function () {
  35638. function PropertyChangedInfo() {
  35639. }
  35640. return PropertyChangedInfo;
  35641. })();
  35642. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  35643. var ClassTreeInfo = (function () {
  35644. function ClassTreeInfo(baseClass, type, classContentFactory) {
  35645. this._baseClass = baseClass;
  35646. this._type = type;
  35647. this._subClasses = new Array();
  35648. this._levelContent = new BABYLON.StringDictionary();
  35649. this._classContentFactory = classContentFactory;
  35650. }
  35651. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  35652. get: function () {
  35653. if (!this._classContent) {
  35654. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  35655. }
  35656. return this._classContent;
  35657. },
  35658. enumerable: true,
  35659. configurable: true
  35660. });
  35661. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  35662. get: function () {
  35663. return this._type;
  35664. },
  35665. enumerable: true,
  35666. configurable: true
  35667. });
  35668. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  35669. get: function () {
  35670. return this._levelContent;
  35671. },
  35672. enumerable: true,
  35673. configurable: true
  35674. });
  35675. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  35676. get: function () {
  35677. if (!this._fullContent) {
  35678. var dic = new BABYLON.StringDictionary();
  35679. var curLevel = this;
  35680. while (curLevel) {
  35681. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  35682. curLevel = curLevel._baseClass;
  35683. }
  35684. this._fullContent = dic;
  35685. }
  35686. return this._fullContent;
  35687. },
  35688. enumerable: true,
  35689. configurable: true
  35690. });
  35691. ClassTreeInfo.prototype.getLevelOf = function (type) {
  35692. // Are we already there?
  35693. if (type === this._type) {
  35694. return this;
  35695. }
  35696. var baseProto = Object.getPrototypeOf(type);
  35697. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  35698. if (!curProtoContent) {
  35699. this.getLevelOf(baseProto);
  35700. }
  35701. return this.getOrAddType(baseProto, type);
  35702. };
  35703. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  35704. // Are we at the level corresponding to the baseType?
  35705. // If so, get or add the level we're looking for
  35706. if (baseType === this._type) {
  35707. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  35708. var subType = _a[_i];
  35709. if (subType.type === type) {
  35710. return subType.node;
  35711. }
  35712. }
  35713. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  35714. var info = { type: type, node: node };
  35715. this._subClasses.push(info);
  35716. return info.node;
  35717. }
  35718. // Recurse down to keep looking for the node corresponding to the baseTypeName
  35719. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  35720. var subType = _c[_b];
  35721. var info = subType.node.getOrAddType(baseType, type);
  35722. if (info) {
  35723. return info;
  35724. }
  35725. }
  35726. return null;
  35727. };
  35728. ClassTreeInfo.get = function (type) {
  35729. var dic = type["__classTreeInfo"];
  35730. if (!dic) {
  35731. return null;
  35732. }
  35733. return dic.getLevelOf(type);
  35734. };
  35735. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  35736. var dic = type["__classTreeInfo"];
  35737. if (!dic) {
  35738. dic = new ClassTreeInfo(null, type, classContentFactory);
  35739. type["__classTreeInfo"] = dic;
  35740. }
  35741. return dic;
  35742. };
  35743. return ClassTreeInfo;
  35744. })();
  35745. BABYLON.ClassTreeInfo = ClassTreeInfo;
  35746. var SmartPropertyPrim = (function () {
  35747. function SmartPropertyPrim() {
  35748. }
  35749. SmartPropertyPrim.prototype.setupSmartPropertyPrim = function () {
  35750. this._modelKey = null;
  35751. this._modelDirty = false;
  35752. this._levelBoundingInfoDirty = false;
  35753. this._instanceDirtyFlags = 0;
  35754. this._isDisposed = false;
  35755. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  35756. this.animations = new Array();
  35757. };
  35758. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  35759. /**
  35760. * Check if the object is disposed or not.
  35761. * @returns true if the object is dispose, false otherwise.
  35762. */
  35763. get: function () {
  35764. return this._isDisposed;
  35765. },
  35766. enumerable: true,
  35767. configurable: true
  35768. });
  35769. /**
  35770. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  35771. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  35772. */
  35773. SmartPropertyPrim.prototype.dispose = function () {
  35774. if (this.isDisposed) {
  35775. return false;
  35776. }
  35777. // Don't set to null, it may upset somebody...
  35778. this.animations.splice(0);
  35779. this._isDisposed = true;
  35780. return true;
  35781. };
  35782. /**
  35783. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  35784. * Look at Sprite2D for more information
  35785. */
  35786. SmartPropertyPrim.prototype.getAnimatables = function () {
  35787. return new Array();
  35788. };
  35789. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  35790. /**
  35791. * Property giving the Model Key associated to the property.
  35792. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  35793. * @returns the model key string.
  35794. */
  35795. get: function () {
  35796. var _this = this;
  35797. // No need to compute it?
  35798. if (!this._modelDirty && this._modelKey) {
  35799. return this._modelKey;
  35800. }
  35801. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  35802. var propDic = this.propDic;
  35803. propDic.forEach(function (k, v) {
  35804. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  35805. var propVal = _this[v.name];
  35806. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  35807. }
  35808. });
  35809. this._modelDirty = false;
  35810. this._modelKey = modelKey;
  35811. return modelKey;
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  35817. /**
  35818. * States if the Primitive is dirty and should be rendered again next time.
  35819. * @returns true is dirty, false otherwise
  35820. */
  35821. get: function () {
  35822. return (this._instanceDirtyFlags !== 0) || this._modelDirty;
  35823. },
  35824. enumerable: true,
  35825. configurable: true
  35826. });
  35827. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  35828. /**
  35829. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  35830. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  35831. */
  35832. get: function () {
  35833. if (!this._propInfo) {
  35834. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  35835. if (!cti) {
  35836. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  35837. }
  35838. this._propInfo = cti.fullContent;
  35839. }
  35840. return this._propInfo;
  35841. },
  35842. enumerable: true,
  35843. configurable: true
  35844. });
  35845. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind) {
  35846. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  35847. var node = dic.getLevelOf(target);
  35848. var propInfo = node.levelContent.get(propId.toString());
  35849. if (propInfo) {
  35850. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  35851. }
  35852. // Create, setup and add the PropInfo object to our prop dictionary
  35853. propInfo = new Prim2DPropInfo();
  35854. propInfo.id = propId;
  35855. propInfo.flagId = Math.pow(2, propId);
  35856. propInfo.kind = kind;
  35857. propInfo.name = propName;
  35858. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  35859. propInfo.typeLevelCompare = typeLevelCompare;
  35860. node.levelContent.add(propName, propInfo);
  35861. return propInfo;
  35862. };
  35863. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  35864. // Nothing to nothing: nothing to do!
  35865. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  35866. return true;
  35867. }
  35868. // Check value unchanged
  35869. if ((curValue != null) && (newValue != null)) {
  35870. if (typeof (curValue.equals) == "function") {
  35871. if (curValue.equals(newValue)) {
  35872. return true;
  35873. }
  35874. }
  35875. else {
  35876. if (curValue === newValue) {
  35877. return true;
  35878. }
  35879. }
  35880. }
  35881. return false;
  35882. };
  35883. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  35884. var i = propertyName.indexOf(".");
  35885. if (i !== -1) {
  35886. propertyName = propertyName.substr(0, i);
  35887. }
  35888. var propInfo = this.propDic.get(propertyName);
  35889. if (!propInfo) {
  35890. return;
  35891. }
  35892. var newValue = this[propertyName];
  35893. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  35894. };
  35895. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  35896. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  35897. if (propInfo.dirtyBoundingInfo) {
  35898. this._levelBoundingInfoDirty = true;
  35899. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  35900. if (this instanceof BABYLON.Prim2DBase) {
  35901. var curprim = this.parent;
  35902. while (curprim) {
  35903. curprim._boundingInfoDirty = true;
  35904. if (curprim instanceof BABYLON.Group2D) {
  35905. if (curprim.isRenderableGroup) {
  35906. break;
  35907. }
  35908. }
  35909. curprim = curprim.parent;
  35910. }
  35911. }
  35912. }
  35913. // Trigger property changed
  35914. var info = SmartPropertyPrim.propChangedInfo;
  35915. info.oldValue = curValue;
  35916. info.newValue = newValue;
  35917. info.propertyName = propName;
  35918. var propMask = propInfo.flagId;
  35919. this.propertyChanged.notifyObservers(info, propMask);
  35920. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  35921. if (this instanceof BABYLON.Group2D) {
  35922. this.handleGroupChanged(propInfo);
  35923. }
  35924. // Check if we need to dirty only if the type change and make the test
  35925. var skipDirty = false;
  35926. if (typeLevelCompare && curValue != null && newValue != null) {
  35927. var cvProto = curValue.__proto__;
  35928. var nvProto = newValue.__proto__;
  35929. skipDirty = (cvProto === nvProto);
  35930. }
  35931. // Set the dirty flags
  35932. if (!skipDirty) {
  35933. if (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  35934. if (!this.isDirty) {
  35935. this.onPrimBecomesDirty();
  35936. }
  35937. this._modelDirty = true;
  35938. }
  35939. else if ((propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  35940. if (!this.isDirty) {
  35941. this.onPrimBecomesDirty();
  35942. }
  35943. this._instanceDirtyFlags |= propMask;
  35944. }
  35945. }
  35946. };
  35947. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  35948. };
  35949. /**
  35950. * Check if a given set of properties are dirty or not.
  35951. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  35952. * @return true if at least one property is dirty, false if none of them are.
  35953. */
  35954. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  35955. return (this._instanceDirtyFlags & flags) !== 0;
  35956. };
  35957. /**
  35958. * Clear a given set of properties.
  35959. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  35960. * @return the new set of property still marked as dirty
  35961. */
  35962. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  35963. this._instanceDirtyFlags &= ~flags;
  35964. return this._instanceDirtyFlags;
  35965. };
  35966. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  35967. /**
  35968. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  35969. * @returns {}
  35970. */
  35971. get: function () {
  35972. if (this._levelBoundingInfoDirty) {
  35973. this.updateLevelBoundingInfo();
  35974. this._levelBoundingInfoDirty = false;
  35975. }
  35976. return this._levelBoundingInfo;
  35977. },
  35978. enumerable: true,
  35979. configurable: true
  35980. });
  35981. /**
  35982. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  35983. */
  35984. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  35985. };
  35986. /**
  35987. * Property method called when the Primitive becomes dirty
  35988. */
  35989. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  35990. };
  35991. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, kind) {
  35992. return function (target, propName, descriptor) {
  35993. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, typeLevelCompare, kind);
  35994. if (piStore) {
  35995. piStore(propInfo);
  35996. }
  35997. var getter = descriptor.get, setter = descriptor.set;
  35998. // Overload the property setter implementation to add our own logic
  35999. descriptor.set = function (val) {
  36000. // check for disposed first, do nothing
  36001. if (this.isDisposed) {
  36002. return;
  36003. }
  36004. var curVal = getter.call(this);
  36005. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  36006. return;
  36007. }
  36008. // Cast the object we're working one
  36009. var prim = this;
  36010. // Change the value
  36011. setter.call(this, val);
  36012. // Notify change, dirty flags update
  36013. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  36014. };
  36015. };
  36016. };
  36017. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  36018. SmartPropertyPrim = __decorate([
  36019. BABYLON.className("SmartPropertyPrim")
  36020. ], SmartPropertyPrim);
  36021. return SmartPropertyPrim;
  36022. })();
  36023. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  36024. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36025. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36026. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36027. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_MODEL);
  36028. }
  36029. BABYLON.modelLevelProperty = modelLevelProperty;
  36030. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36031. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36032. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36033. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_INSTANCE);
  36034. }
  36035. BABYLON.instanceLevelProperty = instanceLevelProperty;
  36036. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo) {
  36037. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  36038. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  36039. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, Prim2DPropInfo.PROPKIND_DYNAMIC);
  36040. }
  36041. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  36042. })(BABYLON || (BABYLON = {}));
  36043. var BABYLON;
  36044. (function (BABYLON) {
  36045. var Render2DContext = (function () {
  36046. function Render2DContext() {
  36047. }
  36048. return Render2DContext;
  36049. })();
  36050. BABYLON.Render2DContext = Render2DContext;
  36051. /**
  36052. * This class store information for the pointerEventObservable Observable.
  36053. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  36054. */
  36055. var PrimitivePointerInfo = (function () {
  36056. function PrimitivePointerInfo() {
  36057. this.primitivePointerPos = BABYLON.Vector2.Zero();
  36058. this.tilt = BABYLON.Vector2.Zero();
  36059. this.cancelBubble = false;
  36060. }
  36061. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  36062. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  36063. /**
  36064. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  36065. * Bubbles: yes
  36066. */
  36067. get: function () {
  36068. return PrimitivePointerInfo._pointerOver;
  36069. },
  36070. enumerable: true,
  36071. configurable: true
  36072. });
  36073. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  36074. /**
  36075. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  36076. * Bubbles: no
  36077. */
  36078. get: function () {
  36079. return PrimitivePointerInfo._pointerEnter;
  36080. },
  36081. enumerable: true,
  36082. configurable: true
  36083. });
  36084. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  36085. /**
  36086. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  36087. * Bubbles: yes
  36088. */
  36089. get: function () {
  36090. return PrimitivePointerInfo._pointerDown;
  36091. },
  36092. enumerable: true,
  36093. configurable: true
  36094. });
  36095. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  36096. /**
  36097. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  36098. * Bubbles: yes
  36099. */
  36100. get: function () {
  36101. return PrimitivePointerInfo._pointerMouseWheel;
  36102. },
  36103. enumerable: true,
  36104. configurable: true
  36105. });
  36106. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  36107. /**
  36108. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  36109. * Bubbles: yes
  36110. */
  36111. get: function () {
  36112. return PrimitivePointerInfo._pointerMove;
  36113. },
  36114. enumerable: true,
  36115. configurable: true
  36116. });
  36117. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  36118. /**
  36119. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  36120. * Bubbles: yes
  36121. */
  36122. get: function () {
  36123. return PrimitivePointerInfo._pointerUp;
  36124. },
  36125. enumerable: true,
  36126. configurable: true
  36127. });
  36128. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  36129. /**
  36130. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  36131. * Bubbles: yes
  36132. */
  36133. get: function () {
  36134. return PrimitivePointerInfo._pointerOut;
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  36140. /**
  36141. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  36142. * Bubbles: no
  36143. */
  36144. get: function () {
  36145. return PrimitivePointerInfo._pointerLeave;
  36146. },
  36147. enumerable: true,
  36148. configurable: true
  36149. });
  36150. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  36151. /**
  36152. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  36153. * Bubbles: yes
  36154. */
  36155. get: function () {
  36156. return PrimitivePointerInfo._pointerGotCapture;
  36157. },
  36158. enumerable: true,
  36159. configurable: true
  36160. });
  36161. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  36162. /**
  36163. * This event type is raised after pointer capture is released for a pointer.
  36164. * Bubbles: yes
  36165. */
  36166. get: function () {
  36167. return PrimitivePointerInfo._pointerLostCapture;
  36168. },
  36169. enumerable: true,
  36170. configurable: true
  36171. });
  36172. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  36173. get: function () {
  36174. return PrimitivePointerInfo._mouseWheelPrecision;
  36175. },
  36176. enumerable: true,
  36177. configurable: true
  36178. });
  36179. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  36180. this.relatedTarget = prim;
  36181. this.relatedTargetPointerPos = primPointerPos;
  36182. };
  36183. PrimitivePointerInfo.getEventTypeName = function (mask) {
  36184. switch (mask) {
  36185. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  36186. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  36187. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  36188. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  36189. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  36190. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  36191. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  36192. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  36193. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  36194. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  36195. }
  36196. };
  36197. PrimitivePointerInfo._pointerOver = 0x0001;
  36198. PrimitivePointerInfo._pointerEnter = 0x0002;
  36199. PrimitivePointerInfo._pointerDown = 0x0004;
  36200. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  36201. PrimitivePointerInfo._pointerMove = 0x0010;
  36202. PrimitivePointerInfo._pointerUp = 0x0020;
  36203. PrimitivePointerInfo._pointerOut = 0x0040;
  36204. PrimitivePointerInfo._pointerLeave = 0x0080;
  36205. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  36206. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  36207. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  36208. return PrimitivePointerInfo;
  36209. })();
  36210. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  36211. /**
  36212. * Stores information about a Primitive that was intersected
  36213. */
  36214. var PrimitiveIntersectedInfo = (function () {
  36215. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  36216. this.prim = prim;
  36217. this.intersectionLocation = intersectionLocation;
  36218. }
  36219. return PrimitiveIntersectedInfo;
  36220. })();
  36221. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  36222. /**
  36223. * Main class used for the Primitive Intersection API
  36224. */
  36225. var IntersectInfo2D = (function () {
  36226. function IntersectInfo2D() {
  36227. this.findFirstOnly = false;
  36228. this.intersectHidden = false;
  36229. this.pickPosition = BABYLON.Vector2.Zero();
  36230. }
  36231. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  36232. /**
  36233. * true if at least one primitive intersected during the test
  36234. */
  36235. get: function () {
  36236. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  36237. },
  36238. enumerable: true,
  36239. configurable: true
  36240. });
  36241. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  36242. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  36243. var cur = _a[_i];
  36244. if (cur.prim === prim) {
  36245. return cur.intersectionLocation;
  36246. }
  36247. }
  36248. return null;
  36249. };
  36250. // Internals, don't use
  36251. IntersectInfo2D.prototype._exit = function (firstLevel) {
  36252. if (firstLevel) {
  36253. this._globalPickPosition = null;
  36254. }
  36255. };
  36256. return IntersectInfo2D;
  36257. })();
  36258. BABYLON.IntersectInfo2D = IntersectInfo2D;
  36259. var Prim2DBase = (function (_super) {
  36260. __extends(Prim2DBase, _super);
  36261. function Prim2DBase() {
  36262. _super.apply(this, arguments);
  36263. }
  36264. Prim2DBase.prototype.setupPrim2DBase = function (owner, parent, id, position, isVisible) {
  36265. if (isVisible === void 0) { isVisible = true; }
  36266. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && id !== null && id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  36267. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  36268. }
  36269. this.setupSmartPropertyPrim();
  36270. this._pointerEventObservable = new BABYLON.Observable();
  36271. this._isPickable = true;
  36272. this._siblingDepthOffset = this._hierarchyDepthOffset = 0;
  36273. this._boundingInfoDirty = true;
  36274. this._boundingInfo = new BABYLON.BoundingInfo2D();
  36275. this._owner = owner;
  36276. this._parent = parent;
  36277. if (parent != null) {
  36278. this._hierarchyDepth = parent._hierarchyDepth + 1;
  36279. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  36280. parent.addChild(this);
  36281. }
  36282. else {
  36283. this._hierarchyDepth = 0;
  36284. this._renderGroup = null;
  36285. }
  36286. this._id = id;
  36287. this.propertyChanged = new BABYLON.Observable();
  36288. this._children = new Array();
  36289. this._globalTransformProcessStep = 0;
  36290. this._globalTransformStep = 0;
  36291. if (this instanceof BABYLON.Group2D) {
  36292. var group = this;
  36293. group.detectGroupStates();
  36294. }
  36295. this.position = position;
  36296. this.rotation = 0;
  36297. this.scale = 1;
  36298. this.levelVisible = isVisible;
  36299. this.origin = new BABYLON.Vector2(0.5, 0.5);
  36300. };
  36301. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  36302. get: function () {
  36303. if (!this._actionManager) {
  36304. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  36305. }
  36306. return this._actionManager;
  36307. },
  36308. enumerable: true,
  36309. configurable: true
  36310. });
  36311. /**
  36312. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  36313. * @param predicate the predicate to test on each parent
  36314. * @return the first primitive where the predicate was successful
  36315. */
  36316. Prim2DBase.prototype.traverseUp = function (predicate) {
  36317. var p = this;
  36318. while (p != null) {
  36319. if (predicate(p)) {
  36320. return p;
  36321. }
  36322. p = p._parent;
  36323. }
  36324. return null;
  36325. };
  36326. Object.defineProperty(Prim2DBase.prototype, "owner", {
  36327. /**
  36328. * Retrieve the owner Canvas2D
  36329. */
  36330. get: function () {
  36331. return this._owner;
  36332. },
  36333. enumerable: true,
  36334. configurable: true
  36335. });
  36336. Object.defineProperty(Prim2DBase.prototype, "parent", {
  36337. /**
  36338. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  36339. */
  36340. get: function () {
  36341. return this._parent;
  36342. },
  36343. enumerable: true,
  36344. configurable: true
  36345. });
  36346. Object.defineProperty(Prim2DBase.prototype, "children", {
  36347. /**
  36348. * The array of direct children primitives
  36349. */
  36350. get: function () {
  36351. return this._children;
  36352. },
  36353. enumerable: true,
  36354. configurable: true
  36355. });
  36356. Object.defineProperty(Prim2DBase.prototype, "id", {
  36357. /**
  36358. * The identifier of this primitive, may not be unique, it's for information purpose only
  36359. */
  36360. get: function () {
  36361. return this._id;
  36362. },
  36363. enumerable: true,
  36364. configurable: true
  36365. });
  36366. Object.defineProperty(Prim2DBase.prototype, "position", {
  36367. get: function () {
  36368. return this._position;
  36369. },
  36370. set: function (value) {
  36371. this._position = value;
  36372. },
  36373. enumerable: true,
  36374. configurable: true
  36375. });
  36376. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  36377. get: function () {
  36378. return this._rotation;
  36379. },
  36380. set: function (value) {
  36381. this._rotation = value;
  36382. },
  36383. enumerable: true,
  36384. configurable: true
  36385. });
  36386. Object.defineProperty(Prim2DBase.prototype, "scale", {
  36387. get: function () {
  36388. return this._scale;
  36389. },
  36390. set: function (value) {
  36391. this._scale = value;
  36392. },
  36393. enumerable: true,
  36394. configurable: true
  36395. });
  36396. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  36397. /**
  36398. * this method must be implemented by the primitive type to return its size
  36399. * @returns The size of the primitive
  36400. */
  36401. get: function () {
  36402. return undefined;
  36403. },
  36404. enumerable: true,
  36405. configurable: true
  36406. });
  36407. Object.defineProperty(Prim2DBase.prototype, "origin", {
  36408. /**
  36409. * The origin defines the normalized coordinate of the center of the primitive, from the top/left corner.
  36410. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  36411. * For instance:
  36412. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  36413. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  36414. * 0,1 means the center is top/left
  36415. * @returns The normalized center.
  36416. */
  36417. get: function () {
  36418. return this._origin;
  36419. },
  36420. set: function (value) {
  36421. this._origin = value;
  36422. },
  36423. enumerable: true,
  36424. configurable: true
  36425. });
  36426. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  36427. get: function () {
  36428. return this._levelVisible;
  36429. },
  36430. set: function (value) {
  36431. this._levelVisible = value;
  36432. },
  36433. enumerable: true,
  36434. configurable: true
  36435. });
  36436. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  36437. get: function () {
  36438. return this._isVisible;
  36439. },
  36440. set: function (value) {
  36441. this._isVisible = value;
  36442. },
  36443. enumerable: true,
  36444. configurable: true
  36445. });
  36446. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  36447. get: function () {
  36448. return this._zOrder;
  36449. },
  36450. set: function (value) {
  36451. this._zOrder = value;
  36452. },
  36453. enumerable: true,
  36454. configurable: true
  36455. });
  36456. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  36457. /**
  36458. * Define if the Primitive can be subject to intersection test or not (default is true)
  36459. */
  36460. get: function () {
  36461. return this._isPickable;
  36462. },
  36463. set: function (value) {
  36464. this._isPickable = value;
  36465. },
  36466. enumerable: true,
  36467. configurable: true
  36468. });
  36469. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  36470. /**
  36471. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  36472. * @returns {}
  36473. */
  36474. get: function () {
  36475. return this._hierarchyDepth;
  36476. },
  36477. enumerable: true,
  36478. configurable: true
  36479. });
  36480. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  36481. /**
  36482. * Retrieve the Group that is responsible to render this primitive
  36483. * @returns {}
  36484. */
  36485. get: function () {
  36486. return this._renderGroup;
  36487. },
  36488. enumerable: true,
  36489. configurable: true
  36490. });
  36491. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  36492. /**
  36493. * Get the global transformation matrix of the primitive
  36494. */
  36495. get: function () {
  36496. return this._globalTransform;
  36497. },
  36498. enumerable: true,
  36499. configurable: true
  36500. });
  36501. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  36502. /**
  36503. * Get invert of the global transformation matrix of the primitive
  36504. * @returns {}
  36505. */
  36506. get: function () {
  36507. return this._invGlobalTransform;
  36508. },
  36509. enumerable: true,
  36510. configurable: true
  36511. });
  36512. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  36513. /**
  36514. * Get the local transformation of the primitive
  36515. */
  36516. get: function () {
  36517. this._updateLocalTransform();
  36518. return this._localTransform;
  36519. },
  36520. enumerable: true,
  36521. configurable: true
  36522. });
  36523. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  36524. /**
  36525. * Get the boundingInfo associated to the primitive.
  36526. * The value is supposed to be always up to date
  36527. */
  36528. get: function () {
  36529. if (this._boundingInfoDirty) {
  36530. this._boundingInfo = this.levelBoundingInfo.clone();
  36531. var bi = this._boundingInfo;
  36532. var tps = new BABYLON.BoundingInfo2D();
  36533. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36534. var curChild = _a[_i];
  36535. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  36536. bi.unionToRef(tps, bi);
  36537. }
  36538. this._boundingInfoDirty = false;
  36539. }
  36540. return this._boundingInfo;
  36541. },
  36542. enumerable: true,
  36543. configurable: true
  36544. });
  36545. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  36546. /**
  36547. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  36548. */
  36549. get: function () {
  36550. return this._pointerEventObservable;
  36551. },
  36552. enumerable: true,
  36553. configurable: true
  36554. });
  36555. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  36556. return false;
  36557. };
  36558. /**
  36559. * Capture all the Events of the given PointerId for this primitive.
  36560. * Don't forget to call releasePointerEventsCapture when done.
  36561. * @param pointerId the Id of the pointer to capture the events from.
  36562. */
  36563. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  36564. return this.owner._setPointerCapture(pointerId, this);
  36565. };
  36566. /**
  36567. * Release a captured pointer made with setPointerEventCapture.
  36568. * @param pointerId the Id of the pointer to release the capture from.
  36569. */
  36570. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  36571. return this.owner._releasePointerCapture(pointerId, this);
  36572. };
  36573. /**
  36574. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  36575. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  36576. */
  36577. Prim2DBase.prototype.intersect = function (intersectInfo) {
  36578. if (!intersectInfo) {
  36579. return false;
  36580. }
  36581. // If this is null it means this method is call for the first level, initialize stuffs
  36582. var firstLevel = !intersectInfo._globalPickPosition;
  36583. if (firstLevel) {
  36584. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  36585. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  36586. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  36587. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  36588. intersectInfo.intersectedPrimitives = new Array();
  36589. intersectInfo.topMostIntersectedPrimitive = null;
  36590. }
  36591. if (!intersectInfo.intersectHidden && !this.isVisible) {
  36592. return false;
  36593. }
  36594. // Fast rejection test with boundingInfo
  36595. if (!this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  36596. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  36597. intersectInfo._exit(firstLevel);
  36598. return false;
  36599. }
  36600. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  36601. var levelIntersectRes = this.levelIntersect(intersectInfo);
  36602. if (levelIntersectRes) {
  36603. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  36604. intersectInfo.intersectedPrimitives.push(pii);
  36605. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.getActualZOffset() > pii.prim.getActualZOffset())) {
  36606. intersectInfo.topMostIntersectedPrimitive = pii;
  36607. }
  36608. // If we must stop at the first intersection, we're done, quit!
  36609. if (intersectInfo.findFirstOnly) {
  36610. intersectInfo._exit(firstLevel);
  36611. return true;
  36612. }
  36613. }
  36614. // Recurse to children if needed
  36615. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  36616. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36617. var curChild = _a[_i];
  36618. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  36619. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  36620. continue;
  36621. }
  36622. // Must compute the localPickLocation for the children level
  36623. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  36624. // If we got an intersection with the child and we only need to find the first one, quit!
  36625. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  36626. intersectInfo._exit(firstLevel);
  36627. return true;
  36628. }
  36629. }
  36630. }
  36631. intersectInfo._exit(firstLevel);
  36632. return intersectInfo.isIntersected;
  36633. };
  36634. Prim2DBase.prototype.moveChild = function (child, previous) {
  36635. if (child.parent !== this) {
  36636. return false;
  36637. }
  36638. var prevOffset, nextOffset;
  36639. var childIndex = this._children.indexOf(child);
  36640. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  36641. // Move to first position
  36642. if (!previous) {
  36643. prevOffset = 1;
  36644. nextOffset = this._children[1]._siblingDepthOffset;
  36645. }
  36646. else {
  36647. prevOffset = this._children[prevIndex]._siblingDepthOffset;
  36648. nextOffset = this._children[prevIndex + 1]._siblingDepthOffset;
  36649. }
  36650. child._siblingDepthOffset = (nextOffset - prevOffset) / 2;
  36651. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  36652. };
  36653. Prim2DBase.prototype.addChild = function (child) {
  36654. child._hierarchyDepthOffset = this._hierarchyDepthOffset + ((this._children.length + 1) * this._siblingDepthOffset);
  36655. child._siblingDepthOffset = this._siblingDepthOffset / this.owner.hierarchyLevelMaxSiblingCount;
  36656. this._children.push(child);
  36657. };
  36658. Prim2DBase.prototype.dispose = function () {
  36659. if (!_super.prototype.dispose.call(this)) {
  36660. return false;
  36661. }
  36662. if (this._actionManager) {
  36663. this._actionManager.dispose();
  36664. this._actionManager = null;
  36665. }
  36666. // If there's a parent, remove this object from its parent list
  36667. if (this._parent) {
  36668. var i = this._parent._children.indexOf(this);
  36669. if (i !== undefined) {
  36670. this._parent._children.splice(i, 1);
  36671. }
  36672. this._parent = null;
  36673. }
  36674. // Recurse dispose to children
  36675. if (this._children) {
  36676. while (this._children.length > 0) {
  36677. this._children[this._children.length - 1].dispose();
  36678. }
  36679. }
  36680. return true;
  36681. };
  36682. Prim2DBase.prototype.getActualZOffset = function () {
  36683. return this._zOrder || (1 - this._hierarchyDepthOffset);
  36684. };
  36685. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  36686. if (this._renderGroup) {
  36687. this._renderGroup._addPrimToDirtyList(this);
  36688. }
  36689. };
  36690. Prim2DBase.prototype._needPrepare = function () {
  36691. return this._visibilityChanged || this._modelDirty || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  36692. };
  36693. Prim2DBase.prototype._prepareRender = function (context) {
  36694. this._prepareRenderPre(context);
  36695. this._prepareRenderPost(context);
  36696. };
  36697. Prim2DBase.prototype._prepareRenderPre = function (context) {
  36698. };
  36699. Prim2DBase.prototype._prepareRenderPost = function (context) {
  36700. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  36701. if (this instanceof BABYLON.Group2D) {
  36702. var self = this;
  36703. if (self.isRenderableGroup) {
  36704. return;
  36705. }
  36706. }
  36707. // Check if we need to recurse the prepare to children primitives
  36708. // - must have children
  36709. // - the global transform of this level have changed, or
  36710. // - the visible state of primitive has changed
  36711. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  36712. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  36713. this._children.forEach(function (c) {
  36714. // As usual stop the recursion if we meet a renderable group
  36715. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  36716. c._prepareRender(context);
  36717. }
  36718. });
  36719. }
  36720. // Finally reset the dirty flags as we've processed everything
  36721. this._modelDirty = false;
  36722. this._instanceDirtyFlags = 0;
  36723. };
  36724. Prim2DBase.CheckParent = function (parent) {
  36725. if (!parent) {
  36726. throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  36727. }
  36728. };
  36729. Prim2DBase.prototype.updateGlobalTransVisOf = function (list, recurse) {
  36730. for (var _i = 0; _i < list.length; _i++) {
  36731. var cur = list[_i];
  36732. cur.updateGlobalTransVis(recurse);
  36733. }
  36734. };
  36735. Prim2DBase.prototype._updateLocalTransform = function () {
  36736. var tflags = Prim2DBase.positionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId;
  36737. if (this.checkPropertiesDirty(tflags)) {
  36738. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  36739. var local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, this._scale), rot, new BABYLON.Vector3(this._position.x, this._position.y, 0));
  36740. this._localTransform = local;
  36741. this.clearPropertiesDirty(tflags);
  36742. // this is important to access actualSize AFTER fetching a first version of the local transform and reset the dirty flag, because accessing actualSize on a Group2D which actualSize is built from its content will trigger a call to this very method on this very object. We won't mind about the origin offset not being computed, as long as we return a local transform based on the position/rotation/scale
  36743. //var actualSize = this.actualSize;
  36744. //if (!actualSize) {
  36745. // throw new Error(`The primitive type: ${Tools.getClassName(this)} must implement the actualSize get property!`);
  36746. //}
  36747. //local.m[12] -= (actualSize.width * this.origin.x) * local.m[0] + (actualSize.height * this.origin.y) * local.m[4];
  36748. //local.m[13] -= (actualSize.width * this.origin.x) * local.m[1] + (actualSize.height * this.origin.y) * local.m[5];
  36749. return true;
  36750. }
  36751. return false;
  36752. };
  36753. Prim2DBase.prototype.updateGlobalTransVis = function (recurse) {
  36754. if (this.isDisposed) {
  36755. return;
  36756. }
  36757. // Check if the parent is synced
  36758. if (this._parent && this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  36759. this._parent.updateGlobalTransVis(false);
  36760. }
  36761. // Check if we must update this prim
  36762. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  36763. var curVisibleState = this.isVisible;
  36764. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  36765. // Detect a change of visibility
  36766. this._visibilityChanged = curVisibleState !== this.isVisible;
  36767. // Get/compute the localTransform
  36768. var localDirty = this._updateLocalTransform();
  36769. // Check if we have to update the globalTransform
  36770. if (!this._globalTransform || localDirty || (this._parent && this._parent._globalTransformStep !== this._parentTransformStep)) {
  36771. this._globalTransform = this._parent ? this._localTransform.multiply(this._parent._globalTransform) : this._localTransform;
  36772. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  36773. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  36774. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  36775. }
  36776. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  36777. }
  36778. if (recurse) {
  36779. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  36780. var child = _a[_i];
  36781. // Stop the recursion if we meet a renderable group
  36782. child.updateGlobalTransVis(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  36783. }
  36784. }
  36785. };
  36786. Prim2DBase.PRIM2DBASE_PROPCOUNT = 10;
  36787. __decorate([
  36788. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.positionProperty = pi; }, false, true)
  36789. ], Prim2DBase.prototype, "position", null);
  36790. __decorate([
  36791. BABYLON.instanceLevelProperty(2, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  36792. ], Prim2DBase.prototype, "rotation", null);
  36793. __decorate([
  36794. BABYLON.instanceLevelProperty(3, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  36795. ], Prim2DBase.prototype, "scale", null);
  36796. __decorate([
  36797. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  36798. ], Prim2DBase.prototype, "origin", null);
  36799. __decorate([
  36800. BABYLON.dynamicLevelProperty(5, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  36801. ], Prim2DBase.prototype, "levelVisible", null);
  36802. __decorate([
  36803. BABYLON.instanceLevelProperty(6, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  36804. ], Prim2DBase.prototype, "isVisible", null);
  36805. __decorate([
  36806. BABYLON.instanceLevelProperty(7, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  36807. ], Prim2DBase.prototype, "zOrder", null);
  36808. Prim2DBase = __decorate([
  36809. BABYLON.className("Prim2DBase")
  36810. ], Prim2DBase);
  36811. return Prim2DBase;
  36812. })(BABYLON.SmartPropertyPrim);
  36813. BABYLON.Prim2DBase = Prim2DBase;
  36814. })(BABYLON || (BABYLON = {}));
  36815. var BABYLON;
  36816. (function (BABYLON) {
  36817. var GroupInstanceInfo = (function () {
  36818. function GroupInstanceInfo(owner, cache) {
  36819. this._owner = owner;
  36820. this._modelCache = cache;
  36821. this._modelCache.addRef();
  36822. this._instancesPartsData = new Array();
  36823. this._instancesPartsBuffer = new Array();
  36824. this._instancesPartsBufferSize = new Array();
  36825. this._partIndexFromId = new BABYLON.StringDictionary();
  36826. this._instancesPartsUsedShaderCategories = new Array();
  36827. }
  36828. GroupInstanceInfo.prototype.dispose = function () {
  36829. if (this._isDisposed) {
  36830. return false;
  36831. }
  36832. if (this._modelCache) {
  36833. this._modelCache.dispose();
  36834. }
  36835. var engine = this._owner.owner.engine;
  36836. if (this._instancesPartsBuffer) {
  36837. this._instancesPartsBuffer.forEach(function (b) {
  36838. engine._releaseBuffer(b);
  36839. });
  36840. }
  36841. this._partIndexFromId = null;
  36842. this._instancesPartsData = null;
  36843. this._instancesPartsBufferSize = null;
  36844. this._instancesPartsUsedShaderCategories = null;
  36845. return true;
  36846. };
  36847. return GroupInstanceInfo;
  36848. })();
  36849. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  36850. var ModelRenderCache = (function () {
  36851. function ModelRenderCache(engine, modelKey, isTransparent) {
  36852. this._engine = engine;
  36853. this._modelKey = modelKey;
  36854. this._isTransparent = isTransparent;
  36855. this._nextKey = 1;
  36856. this._refCounter = 1;
  36857. this._instancesData = new BABYLON.StringDictionary();
  36858. }
  36859. ModelRenderCache.prototype.dispose = function () {
  36860. if (--this._refCounter !== 0) {
  36861. return false;
  36862. }
  36863. // Remove the Model Render Cache from the global dictionary
  36864. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  36865. if (edata) {
  36866. edata.DisposeModelRenderCache(this);
  36867. }
  36868. return true;
  36869. };
  36870. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  36871. get: function () {
  36872. return this._refCounter <= 0;
  36873. },
  36874. enumerable: true,
  36875. configurable: true
  36876. });
  36877. ModelRenderCache.prototype.addRef = function () {
  36878. return ++this._refCounter;
  36879. };
  36880. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  36881. get: function () {
  36882. return this._modelKey;
  36883. },
  36884. enumerable: true,
  36885. configurable: true
  36886. });
  36887. /**
  36888. * Render the model instances
  36889. * @param instanceInfo
  36890. * @param context
  36891. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  36892. */
  36893. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  36894. return true;
  36895. };
  36896. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  36897. var key = this._nextKey.toString();
  36898. if (!this._instancesData.add(key, data)) {
  36899. throw Error("Key: " + key + " is already allocated");
  36900. }
  36901. ++this._nextKey;
  36902. return key;
  36903. };
  36904. ModelRenderCache.prototype.removeInstanceData = function (key) {
  36905. this._instancesData.remove(key);
  36906. };
  36907. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  36908. for (var i = 0; i < this._partIdList.length; i++) {
  36909. if (this._partIdList[i] === partId) {
  36910. return i;
  36911. }
  36912. }
  36913. return null;
  36914. };
  36915. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  36916. var i = this.getPartIndexFromId(partId);
  36917. if (i === null) {
  36918. return null;
  36919. }
  36920. var ci = this._partsClassInfo[i];
  36921. var categories = this._partsUsedCategories[i];
  36922. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  36923. return res;
  36924. };
  36925. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  36926. var offset = (this._partsDataStride[partIndex] / 4) * elementCount;
  36927. var pci = this._partsClassInfo[partIndex];
  36928. var self = this;
  36929. pci.fullContent.forEach(function (k, v) {
  36930. if (!v.category || self._partsUsedCategories[partIndex].indexOf(v.category) !== 1) {
  36931. switch (v.dataType) {
  36932. case 4 /* float */:
  36933. {
  36934. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36935. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  36936. break;
  36937. }
  36938. case 0 /* Vector2 */:
  36939. {
  36940. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36941. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  36942. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  36943. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  36944. break;
  36945. }
  36946. case 5 /* Color3 */:
  36947. case 1 /* Vector3 */:
  36948. {
  36949. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36950. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  36951. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  36952. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  36953. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  36954. break;
  36955. }
  36956. case 6 /* Color4 */:
  36957. case 2 /* Vector4 */:
  36958. {
  36959. var attribOffset = v.instanceOffset.get(self._partsJoinedUsedCategories[partIndex]);
  36960. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  36961. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  36962. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  36963. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  36964. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  36965. break;
  36966. }
  36967. default:
  36968. }
  36969. }
  36970. });
  36971. };
  36972. Object.defineProperty(ModelRenderCache.prototype, "isTransparent", {
  36973. get: function () {
  36974. return this._isTransparent;
  36975. },
  36976. enumerable: true,
  36977. configurable: true
  36978. });
  36979. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  36980. // let i = this.getPartIndexFromId(partId);
  36981. // if (i === null) {
  36982. // return null;
  36983. // }
  36984. // let pci = this._partsClassInfo[i];
  36985. // pci.fullContent.forEach((k, v) => {
  36986. // if (uniforms.indexOf(v.attributeName) !== -1) {
  36987. // v.uniformLocation = effect.getUniform(v.attributeName);
  36988. // }
  36989. // });
  36990. //}
  36991. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  36992. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  36993. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  36994. return ModelRenderCache;
  36995. })();
  36996. BABYLON.ModelRenderCache = ModelRenderCache;
  36997. })(BABYLON || (BABYLON = {}));
  36998. var BABYLON;
  36999. (function (BABYLON) {
  37000. var InstanceClassInfo = (function () {
  37001. function InstanceClassInfo(base) {
  37002. this._baseInfo = base;
  37003. this._nextOffset = new BABYLON.StringDictionary();
  37004. this._attributes = new Array();
  37005. }
  37006. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  37007. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  37008. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  37009. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  37010. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  37011. if (push) {
  37012. this._attributes.push(propInfo);
  37013. }
  37014. };
  37015. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  37016. var catInline = categories.join(";");
  37017. var res = new Array();
  37018. var curInfo = this;
  37019. while (curInfo) {
  37020. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  37021. var attrib = _a[_i];
  37022. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  37023. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  37024. var index = effect.getAttributeLocationByName(attrib.attributeName);
  37025. var iai = new BABYLON.InstancingAttributeInfo();
  37026. iai.index = index;
  37027. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  37028. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  37029. iai.attributeName = attrib.attributeName;
  37030. res.push(iai);
  37031. }
  37032. }
  37033. curInfo = curInfo._baseInfo;
  37034. }
  37035. return res;
  37036. };
  37037. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  37038. var res = new Array();
  37039. var curInfo = this;
  37040. while (curInfo) {
  37041. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  37042. var attrib = _a[_i];
  37043. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  37044. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  37045. res.push(attrib.attributeName);
  37046. }
  37047. }
  37048. curInfo = curInfo._baseInfo;
  37049. }
  37050. return res;
  37051. };
  37052. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  37053. var curOffset = 0;
  37054. var curBase = this._baseInfo;
  37055. while (curBase) {
  37056. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  37057. curBase = curBase._baseInfo;
  37058. }
  37059. return curOffset;
  37060. };
  37061. return InstanceClassInfo;
  37062. })();
  37063. BABYLON.InstanceClassInfo = InstanceClassInfo;
  37064. var InstancePropInfo = (function () {
  37065. //uniformLocation: WebGLUniformLocation;
  37066. function InstancePropInfo() {
  37067. this.instanceOffset = new BABYLON.StringDictionary();
  37068. }
  37069. InstancePropInfo.prototype.setSize = function (val) {
  37070. if (val instanceof BABYLON.Vector2) {
  37071. this.size = 8;
  37072. this.dataType = 0 /* Vector2 */;
  37073. return;
  37074. }
  37075. if (val instanceof BABYLON.Vector3) {
  37076. this.size = 12;
  37077. this.dataType = 1 /* Vector3 */;
  37078. return;
  37079. }
  37080. if (val instanceof BABYLON.Vector4) {
  37081. this.size = 16;
  37082. this.dataType = 2 /* Vector4 */;
  37083. return;
  37084. }
  37085. if (val instanceof BABYLON.Matrix) {
  37086. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  37087. }
  37088. if (typeof (val) === "number") {
  37089. this.size = 4;
  37090. this.dataType = 4 /* float */;
  37091. return;
  37092. }
  37093. if (val instanceof BABYLON.Color3) {
  37094. this.size = 12;
  37095. this.dataType = 5 /* Color3 */;
  37096. return;
  37097. }
  37098. if (val instanceof BABYLON.Color4) {
  37099. this.size = 16;
  37100. this.dataType = 6 /* Color4 */;
  37101. return;
  37102. }
  37103. return;
  37104. };
  37105. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  37106. switch (this.dataType) {
  37107. case 0 /* Vector2 */:
  37108. {
  37109. var v = val;
  37110. array[offset + 0] = v.x;
  37111. array[offset + 1] = v.y;
  37112. break;
  37113. }
  37114. case 1 /* Vector3 */:
  37115. {
  37116. var v = val;
  37117. array[offset + 0] = v.x;
  37118. array[offset + 1] = v.y;
  37119. array[offset + 2] = v.z;
  37120. break;
  37121. }
  37122. case 2 /* Vector4 */:
  37123. {
  37124. var v = val;
  37125. array[offset + 0] = v.x;
  37126. array[offset + 1] = v.y;
  37127. array[offset + 2] = v.z;
  37128. array[offset + 3] = v.w;
  37129. break;
  37130. }
  37131. case 5 /* Color3 */:
  37132. {
  37133. var v = val;
  37134. array[offset + 0] = v.r;
  37135. array[offset + 1] = v.g;
  37136. array[offset + 2] = v.b;
  37137. break;
  37138. }
  37139. case 6 /* Color4 */:
  37140. {
  37141. var v = val;
  37142. array[offset + 0] = v.r;
  37143. array[offset + 1] = v.g;
  37144. array[offset + 2] = v.b;
  37145. array[offset + 3] = v.a;
  37146. break;
  37147. }
  37148. case 4 /* float */:
  37149. {
  37150. var v = val;
  37151. array[offset] = v;
  37152. break;
  37153. }
  37154. case 3 /* Matrix */:
  37155. {
  37156. var v = val;
  37157. for (var i = 0; i < 16; i++) {
  37158. array[offset + i] = v.m[i];
  37159. }
  37160. break;
  37161. }
  37162. }
  37163. };
  37164. return InstancePropInfo;
  37165. })();
  37166. BABYLON.InstancePropInfo = InstancePropInfo;
  37167. function instanceData(category, shaderAttributeName) {
  37168. return function (target, propName, descriptor) {
  37169. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  37170. var node = dic.getLevelOf(target);
  37171. var instanceDataName = propName;
  37172. shaderAttributeName = shaderAttributeName || instanceDataName;
  37173. var info = node.levelContent.get(instanceDataName);
  37174. if (info) {
  37175. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  37176. }
  37177. info = new InstancePropInfo();
  37178. info.attributeName = shaderAttributeName;
  37179. info.category = category || null;
  37180. node.levelContent.add(instanceDataName, info);
  37181. descriptor.get = function () {
  37182. return null;
  37183. };
  37184. descriptor.set = function (val) {
  37185. if (!info.size) {
  37186. info.setSize(val);
  37187. node.classContent.mapProperty(info, true);
  37188. }
  37189. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  37190. node.classContent.mapProperty(info, false);
  37191. }
  37192. var obj = this;
  37193. if (obj.dataBuffer && obj.dataElements) {
  37194. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  37195. info.writeData(obj.dataBuffer.buffer, offset, val);
  37196. }
  37197. };
  37198. };
  37199. }
  37200. BABYLON.instanceData = instanceData;
  37201. var InstanceDataBase = (function () {
  37202. function InstanceDataBase(partId, dataElementCount) {
  37203. this.id = partId;
  37204. this.curElement = 0;
  37205. this.dataElementCount = dataElementCount;
  37206. }
  37207. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  37208. get: function () {
  37209. return null;
  37210. },
  37211. enumerable: true,
  37212. configurable: true
  37213. });
  37214. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  37215. get: function () {
  37216. return null;
  37217. },
  37218. enumerable: true,
  37219. configurable: true
  37220. });
  37221. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  37222. get: function () {
  37223. return null;
  37224. },
  37225. enumerable: true,
  37226. configurable: true
  37227. });
  37228. Object.defineProperty(InstanceDataBase.prototype, "origin", {
  37229. get: function () {
  37230. return null;
  37231. },
  37232. enumerable: true,
  37233. configurable: true
  37234. });
  37235. InstanceDataBase.prototype.getClassTreeInfo = function () {
  37236. if (!this.typeInfo) {
  37237. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  37238. }
  37239. return this.typeInfo;
  37240. };
  37241. InstanceDataBase.prototype.allocElements = function () {
  37242. if (!this.dataBuffer) {
  37243. return;
  37244. }
  37245. var res = new Array(this.dataElementCount);
  37246. for (var i = 0; i < this.dataElementCount; i++) {
  37247. res[i] = this.dataBuffer.allocElement();
  37248. }
  37249. this.dataElements = res;
  37250. };
  37251. InstanceDataBase.prototype.freeElements = function () {
  37252. if (!this.dataElements) {
  37253. return;
  37254. }
  37255. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  37256. var ei = _a[_i];
  37257. this.dataBuffer.freeElement(ei);
  37258. }
  37259. this.dataElements = null;
  37260. };
  37261. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  37262. get: function () {
  37263. return this._dataElementCount;
  37264. },
  37265. set: function (value) {
  37266. if (value === this._dataElementCount) {
  37267. return;
  37268. }
  37269. this.freeElements();
  37270. this._dataElementCount = value;
  37271. this.allocElements();
  37272. },
  37273. enumerable: true,
  37274. configurable: true
  37275. });
  37276. __decorate([
  37277. instanceData()
  37278. ], InstanceDataBase.prototype, "zBias", null);
  37279. __decorate([
  37280. instanceData()
  37281. ], InstanceDataBase.prototype, "transformX", null);
  37282. __decorate([
  37283. instanceData()
  37284. ], InstanceDataBase.prototype, "transformY", null);
  37285. __decorate([
  37286. instanceData()
  37287. ], InstanceDataBase.prototype, "origin", null);
  37288. return InstanceDataBase;
  37289. })();
  37290. BABYLON.InstanceDataBase = InstanceDataBase;
  37291. var RenderablePrim2D = (function (_super) {
  37292. __extends(RenderablePrim2D, _super);
  37293. function RenderablePrim2D() {
  37294. _super.apply(this, arguments);
  37295. }
  37296. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  37297. get: function () {
  37298. return this._isTransparent;
  37299. },
  37300. set: function (value) {
  37301. this._isTransparent = value;
  37302. },
  37303. enumerable: true,
  37304. configurable: true
  37305. });
  37306. RenderablePrim2D.prototype.setupRenderablePrim2D = function (owner, parent, id, position, isVisible) {
  37307. this.setupPrim2DBase(owner, parent, id, position);
  37308. this._isTransparent = false;
  37309. };
  37310. RenderablePrim2D.prototype.dispose = function () {
  37311. if (!_super.prototype.dispose.call(this)) {
  37312. return false;
  37313. }
  37314. if (this._modelRenderInstanceID) {
  37315. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  37316. this._modelRenderInstanceID = null;
  37317. }
  37318. if (this._modelRenderCache) {
  37319. this._modelRenderCache.dispose();
  37320. this._modelRenderCache = null;
  37321. }
  37322. if (this._instanceDataParts) {
  37323. this._instanceDataParts.forEach(function (p) {
  37324. p.freeElements();
  37325. });
  37326. this._instanceDataParts = null;
  37327. }
  37328. return true;
  37329. };
  37330. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  37331. var _this = this;
  37332. _super.prototype._prepareRenderPre.call(this, context);
  37333. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  37334. if (this._modelDirty && this._modelRenderInstanceID) {
  37335. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  37336. this._modelRenderInstanceID = null;
  37337. }
  37338. // Need to create the model?
  37339. var setupModelRenderCache = false;
  37340. if (!this._modelRenderCache || this._modelDirty) {
  37341. if (this._modelRenderCache) {
  37342. this._modelRenderCache.dispose();
  37343. }
  37344. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  37345. var mrc = _this.createModelRenderCache(key, _this.isTransparent);
  37346. setupModelRenderCache = true;
  37347. return mrc;
  37348. });
  37349. this._modelDirty = false;
  37350. // if this is still false it means the MRC already exists, so we add a reference to it
  37351. if (!setupModelRenderCache) {
  37352. this._modelRenderCache.addRef();
  37353. }
  37354. }
  37355. var gii;
  37356. var newInstance = false;
  37357. // Need to create the instance data parts?
  37358. if (!this._modelRenderInstanceID) {
  37359. // Yes, flag it for later, more processing will have to be done
  37360. newInstance = true;
  37361. // Create the instance data parts of the primitive and store them
  37362. var parts = this.createInstanceDataParts();
  37363. this._instanceDataParts = parts;
  37364. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  37365. if (!this._modelRenderCache._partsDataStride) {
  37366. var ctiArray = new Array();
  37367. var dataStrides = new Array();
  37368. var usedCatList = new Array();
  37369. var partIdList = new Array();
  37370. var joinedUsedCatList = new Array();
  37371. for (var _i = 0; _i < parts.length; _i++) {
  37372. var dataPart = parts[_i];
  37373. var cat = this.getUsedShaderCategories(dataPart);
  37374. var cti = dataPart.getClassTreeInfo();
  37375. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  37376. var curVisible = this.isVisible;
  37377. this.isVisible = true;
  37378. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  37379. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  37380. var joinCat = cat.join(";");
  37381. joinedUsedCatList.push(joinCat);
  37382. InstanceClassInfo._CurCategories = joinCat;
  37383. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  37384. this.refreshInstanceDataPart(dataPart);
  37385. this.afterRefreshForLayoutConstruction(dataPart, obj);
  37386. this.isVisible = curVisible;
  37387. var size = 0;
  37388. cti.fullContent.forEach(function (k, v) {
  37389. if (!v.category || cat.indexOf(v.category) !== -1) {
  37390. if (!v.size) {
  37391. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  37392. }
  37393. else {
  37394. size += v.size;
  37395. }
  37396. }
  37397. });
  37398. dataStrides.push(size);
  37399. usedCatList.push(cat);
  37400. ctiArray.push(cti);
  37401. partIdList.push(dataPart.id);
  37402. }
  37403. this._modelRenderCache._partsDataStride = dataStrides;
  37404. this._modelRenderCache._partsUsedCategories = usedCatList;
  37405. this._modelRenderCache._partsJoinedUsedCategories = joinedUsedCatList;
  37406. this._modelRenderCache._partsClassInfo = ctiArray;
  37407. this._modelRenderCache._partIdList = partIdList;
  37408. }
  37409. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  37410. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  37411. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  37412. gii = this.renderGroup._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) { return new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache); });
  37413. // First time init of the GroupInstanceInfo
  37414. if (gii._instancesPartsData.length === 0) {
  37415. for (var j = 0; j < this._modelRenderCache._partsDataStride.length; j++) {
  37416. var stride = this._modelRenderCache._partsDataStride[j];
  37417. gii._instancesPartsData.push(new BABYLON.DynamicFloatArray(stride / 4, 50));
  37418. gii._partIndexFromId.add(this._modelRenderCache._partIdList[j].toString(), j);
  37419. for (var _a = 0, _b = this._instanceDataParts; _a < _b.length; _a++) {
  37420. var part = _b[_a];
  37421. gii._instancesPartsUsedShaderCategories[gii._partIndexFromId.get(part.id.toString())] = this.getUsedShaderCategories(part).join(";");
  37422. }
  37423. }
  37424. }
  37425. // For each instance data part of the primitive, allocate the instanced element it needs for render
  37426. for (var i = 0; i < parts.length; i++) {
  37427. var part = parts[i];
  37428. part.dataBuffer = gii._instancesPartsData[i];
  37429. part.allocElements();
  37430. }
  37431. // Add the instance data parts in the ModelRenderCache they belong, track them by storing their ID in the primitive in case we need to change the model later on, so we'll have to release the allocated instance data parts because they won't fit anymore
  37432. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  37433. }
  37434. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  37435. if (setupModelRenderCache) {
  37436. this.setupModelRenderCache(this._modelRenderCache);
  37437. }
  37438. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  37439. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  37440. if (this._visibilityChanged || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  37441. // Fetch the GroupInstanceInfo if we don't already have it
  37442. if (!gii) {
  37443. gii = this.renderGroup._renderGroupInstancesInfo.get(this.modelKey);
  37444. }
  37445. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  37446. for (var _c = 0, _d = this._instanceDataParts; _c < _d.length; _c++) {
  37447. var part = _d[_c];
  37448. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  37449. if (this._visibilityChanged && !part.dataElements) {
  37450. part.allocElements();
  37451. }
  37452. InstanceClassInfo._CurCategories = gii._instancesPartsUsedShaderCategories[gii._partIndexFromId.get(part.id.toString())];
  37453. // Will return false if the instance should not be rendered (not visible or other any reasons)
  37454. if (!this.refreshInstanceDataPart(part)) {
  37455. // Free the data element
  37456. if (part.dataElements) {
  37457. part.freeElements();
  37458. }
  37459. }
  37460. }
  37461. this._instanceDirtyFlags = 0;
  37462. gii._dirtyInstancesData = true;
  37463. this._visibilityChanged = false; // Reset the flag as we've handled the case
  37464. }
  37465. };
  37466. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes) {
  37467. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  37468. if (!dataPart) {
  37469. return null;
  37470. }
  37471. var instancedArray = this.owner.supportInstancedArray;
  37472. var cti = dataPart.getClassTreeInfo();
  37473. var categories = this.getUsedShaderCategories(dataPart);
  37474. var att = cti.classContent.getShaderAttributes(categories);
  37475. var defines = "";
  37476. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  37477. if (instancedArray) {
  37478. defines += "#define Instanced\n";
  37479. }
  37480. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  37481. };
  37482. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  37483. get: function () {
  37484. return this._modelRenderCache;
  37485. },
  37486. enumerable: true,
  37487. configurable: true
  37488. });
  37489. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  37490. return null;
  37491. };
  37492. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  37493. };
  37494. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  37495. return null;
  37496. };
  37497. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  37498. return [];
  37499. };
  37500. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  37501. };
  37502. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  37503. };
  37504. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  37505. if (!this.isVisible) {
  37506. return false;
  37507. }
  37508. part.isVisible = this.isVisible;
  37509. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  37510. if (part.dataElementCount === 1) {
  37511. part.curElement = 0;
  37512. this.updateInstanceDataPart(part);
  37513. }
  37514. return true;
  37515. };
  37516. /**
  37517. * Update the instanceDataBase level properties of a part
  37518. * @param part the part to update
  37519. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text). You MUST also set customSize.
  37520. * @param customSize to use in multi part per primitive, this is the size of the overall primitive to display (the bounding rect's size of the Text, for instance). This is mandatory to compute correct transformation based on the Primitive's origin property.
  37521. */
  37522. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset, customSize) {
  37523. if (positionOffset === void 0) { positionOffset = null; }
  37524. if (customSize === void 0) { customSize = null; }
  37525. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  37526. var size = this.renderGroup.viewportSize;
  37527. var zBias = this.getActualZOffset();
  37528. var offX = 0;
  37529. var offY = 0;
  37530. // If there's an offset, apply the global transformation matrix on it to get a global offset
  37531. if (positionOffset && customSize) {
  37532. offX = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[0] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[4];
  37533. offY = (positionOffset.x - (customSize.width * this.origin.x)) * t.m[1] + (positionOffset.y - (customSize.height * this.origin.y)) * t.m[5];
  37534. }
  37535. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  37536. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  37537. // RenderGroup Width and Height are multiplied by zBias because the VertexShader will multiply X and Y by W, which is 1/zBias. As we divide our coordinate by these Width/Height, we will also divide by the zBias to compensate the operation made by the VertexShader.
  37538. // So for X:
  37539. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  37540. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1]. Don't forget it's -(1/zBias) and not -1 because everything need to be scaled by 1/zBias.
  37541. var w = size.width * zBias;
  37542. var h = size.height * zBias;
  37543. var invZBias = 1 / zBias;
  37544. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - (invZBias));
  37545. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - (invZBias));
  37546. part.transformX = tx;
  37547. part.transformY = ty;
  37548. part.origin = this.origin;
  37549. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  37550. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  37551. };
  37552. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  37553. __decorate([
  37554. BABYLON.modelLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  37555. ], RenderablePrim2D.prototype, "isTransparent", null);
  37556. RenderablePrim2D = __decorate([
  37557. BABYLON.className("RenderablePrim2D")
  37558. ], RenderablePrim2D);
  37559. return RenderablePrim2D;
  37560. })(BABYLON.Prim2DBase);
  37561. BABYLON.RenderablePrim2D = RenderablePrim2D;
  37562. })(BABYLON || (BABYLON = {}));
  37563. var BABYLON;
  37564. (function (BABYLON) {
  37565. var Shape2D = (function (_super) {
  37566. __extends(Shape2D, _super);
  37567. function Shape2D() {
  37568. _super.apply(this, arguments);
  37569. }
  37570. Object.defineProperty(Shape2D.prototype, "border", {
  37571. get: function () {
  37572. return this._border;
  37573. },
  37574. set: function (value) {
  37575. this._border = value;
  37576. this._updateTransparencyStatus();
  37577. },
  37578. enumerable: true,
  37579. configurable: true
  37580. });
  37581. Object.defineProperty(Shape2D.prototype, "fill", {
  37582. get: function () {
  37583. return this._fill;
  37584. },
  37585. set: function (value) {
  37586. this._fill = value;
  37587. this._updateTransparencyStatus();
  37588. },
  37589. enumerable: true,
  37590. configurable: true
  37591. });
  37592. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  37593. get: function () {
  37594. return this._borderThickness;
  37595. },
  37596. set: function (value) {
  37597. this._borderThickness = value;
  37598. },
  37599. enumerable: true,
  37600. configurable: true
  37601. });
  37602. Shape2D.prototype.setupShape2D = function (owner, parent, id, position, isVisible, fill, border, borderThickness) {
  37603. if (borderThickness === void 0) { borderThickness = 1.0; }
  37604. this.setupRenderablePrim2D(owner, parent, id, position, isVisible);
  37605. this.border = border;
  37606. this.fill = fill;
  37607. this.borderThickness = borderThickness;
  37608. };
  37609. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  37610. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  37611. // Fill Part
  37612. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  37613. var fill = this.fill;
  37614. if (fill instanceof BABYLON.SolidColorBrush2D) {
  37615. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  37616. }
  37617. if (fill instanceof BABYLON.GradientColorBrush2D) {
  37618. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  37619. }
  37620. }
  37621. // Border Part
  37622. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  37623. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  37624. var border = this.border;
  37625. if (border instanceof BABYLON.SolidColorBrush2D) {
  37626. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  37627. }
  37628. if (border instanceof BABYLON.GradientColorBrush2D) {
  37629. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  37630. }
  37631. }
  37632. return cat;
  37633. };
  37634. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  37635. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  37636. return false;
  37637. }
  37638. // Fill Part
  37639. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  37640. var d = part;
  37641. if (this.fill) {
  37642. var fill = this.fill;
  37643. if (fill instanceof BABYLON.SolidColorBrush2D) {
  37644. d.fillSolidColor = fill.color;
  37645. }
  37646. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  37647. d.fillGradientColor1 = fill.color1;
  37648. d.fillGradientColor2 = fill.color2;
  37649. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  37650. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  37651. d.fillGradientTY = ty;
  37652. }
  37653. }
  37654. }
  37655. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  37656. var d = part;
  37657. if (this.border) {
  37658. d.borderThickness = this.borderThickness;
  37659. var border = this.border;
  37660. if (border instanceof BABYLON.SolidColorBrush2D) {
  37661. d.borderSolidColor = border.color;
  37662. }
  37663. else if (border instanceof BABYLON.GradientColorBrush2D) {
  37664. d.borderGradientColor1 = border.color1;
  37665. d.borderGradientColor2 = border.color2;
  37666. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  37667. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  37668. d.borderGradientTY = ty;
  37669. }
  37670. }
  37671. }
  37672. return true;
  37673. };
  37674. Shape2D.prototype._updateTransparencyStatus = function () {
  37675. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent());
  37676. };
  37677. Shape2D.SHAPE2D_BORDERPARTID = 1;
  37678. Shape2D.SHAPE2D_FILLPARTID = 2;
  37679. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  37680. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  37681. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  37682. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  37683. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  37684. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  37685. __decorate([
  37686. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  37687. ], Shape2D.prototype, "border", null);
  37688. __decorate([
  37689. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  37690. ], Shape2D.prototype, "fill", null);
  37691. __decorate([
  37692. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  37693. ], Shape2D.prototype, "borderThickness", null);
  37694. Shape2D = __decorate([
  37695. BABYLON.className("Shape2D")
  37696. ], Shape2D);
  37697. return Shape2D;
  37698. })(BABYLON.RenderablePrim2D);
  37699. BABYLON.Shape2D = Shape2D;
  37700. var Shape2DInstanceData = (function (_super) {
  37701. __extends(Shape2DInstanceData, _super);
  37702. function Shape2DInstanceData() {
  37703. _super.apply(this, arguments);
  37704. }
  37705. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  37706. // FILL ATTRIBUTES
  37707. get: function () {
  37708. return null;
  37709. },
  37710. enumerable: true,
  37711. configurable: true
  37712. });
  37713. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  37714. get: function () {
  37715. return null;
  37716. },
  37717. enumerable: true,
  37718. configurable: true
  37719. });
  37720. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  37721. get: function () {
  37722. return null;
  37723. },
  37724. enumerable: true,
  37725. configurable: true
  37726. });
  37727. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  37728. get: function () {
  37729. return null;
  37730. },
  37731. enumerable: true,
  37732. configurable: true
  37733. });
  37734. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  37735. // BORDER ATTRIBUTES
  37736. get: function () {
  37737. return null;
  37738. },
  37739. enumerable: true,
  37740. configurable: true
  37741. });
  37742. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  37743. get: function () {
  37744. return null;
  37745. },
  37746. enumerable: true,
  37747. configurable: true
  37748. });
  37749. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  37750. get: function () {
  37751. return null;
  37752. },
  37753. enumerable: true,
  37754. configurable: true
  37755. });
  37756. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  37757. get: function () {
  37758. return null;
  37759. },
  37760. enumerable: true,
  37761. configurable: true
  37762. });
  37763. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  37764. get: function () {
  37765. return null;
  37766. },
  37767. enumerable: true,
  37768. configurable: true
  37769. });
  37770. __decorate([
  37771. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  37772. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  37773. __decorate([
  37774. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  37775. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  37776. __decorate([
  37777. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  37778. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  37779. __decorate([
  37780. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  37781. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  37782. __decorate([
  37783. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  37784. ], Shape2DInstanceData.prototype, "borderThickness", null);
  37785. __decorate([
  37786. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  37787. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  37788. __decorate([
  37789. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  37790. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  37791. __decorate([
  37792. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  37793. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  37794. __decorate([
  37795. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  37796. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  37797. return Shape2DInstanceData;
  37798. })(BABYLON.InstanceDataBase);
  37799. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  37800. })(BABYLON || (BABYLON = {}));
  37801. var BABYLON;
  37802. (function (BABYLON) {
  37803. var Group2D = (function (_super) {
  37804. __extends(Group2D, _super);
  37805. /**
  37806. * Don't invoke directly, rely on Group2D.CreateXXX methods
  37807. */
  37808. function Group2D() {
  37809. _super.call(this);
  37810. this._primDirtyList = new Array();
  37811. this._childrenRenderableGroups = new Array();
  37812. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  37813. }
  37814. Group2D.CreateGroup2D = function (parent, id, position, size, cacheBehabior) {
  37815. if (cacheBehabior === void 0) { cacheBehabior = Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY; }
  37816. BABYLON.Prim2DBase.CheckParent(parent);
  37817. var g = new Group2D();
  37818. g.setupGroup2D(parent.owner, parent, id, position, size, cacheBehabior);
  37819. return g;
  37820. };
  37821. Group2D._createCachedCanvasGroup = function (owner) {
  37822. var g = new Group2D();
  37823. g.setupGroup2D(owner, null, "__cachedCanvasGroup__", BABYLON.Vector2.Zero());
  37824. g.origin = BABYLON.Vector2.Zero();
  37825. return g;
  37826. };
  37827. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  37828. this._bindCacheTarget();
  37829. var uv = vertexData.uvs;
  37830. var nodeuv = this._cacheNode.UVs;
  37831. for (var i = 0; i < 4; i++) {
  37832. uv[i * 2 + 0] = nodeuv[i].x;
  37833. uv[i * 2 + 1] = nodeuv[i].y;
  37834. }
  37835. material.diffuseTexture = this._cacheTexture;
  37836. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  37837. this._cacheTexture.hasAlpha = true;
  37838. this._unbindCacheTarget();
  37839. };
  37840. /**
  37841. * Call this method to remove this Group and its children from the Canvas
  37842. */
  37843. Group2D.prototype.dispose = function () {
  37844. if (!_super.prototype.dispose.call(this)) {
  37845. return false;
  37846. }
  37847. if (this._cacheRenderSprite) {
  37848. this._cacheRenderSprite.dispose();
  37849. this._cacheRenderSprite = null;
  37850. }
  37851. if (this._cacheTexture && this._cacheNode) {
  37852. this._cacheTexture.freeRect(this._cacheNode);
  37853. this._cacheTexture = null;
  37854. this._cacheNode = null;
  37855. }
  37856. if (this._primDirtyList) {
  37857. this._primDirtyList.splice(0);
  37858. this._primDirtyList = null;
  37859. }
  37860. if (this._renderGroupInstancesInfo) {
  37861. this._renderGroupInstancesInfo.forEach(function (k, v) {
  37862. v.dispose();
  37863. });
  37864. this._renderGroupInstancesInfo = null;
  37865. }
  37866. return true;
  37867. };
  37868. Group2D.prototype.setupGroup2D = function (owner, parent, id, position, size, cacheBehavior) {
  37869. if (cacheBehavior === void 0) { cacheBehavior = Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY; }
  37870. this._cacheBehavior = cacheBehavior;
  37871. this.setupPrim2DBase(owner, parent, id, position);
  37872. this.size = size;
  37873. this._viewportPosition = BABYLON.Vector2.Zero();
  37874. };
  37875. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  37876. /**
  37877. * @returns Returns true if the Group render content, false if it's a logical group only
  37878. */
  37879. get: function () {
  37880. return this._isRenderableGroup;
  37881. },
  37882. enumerable: true,
  37883. configurable: true
  37884. });
  37885. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  37886. /**
  37887. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  37888. */
  37889. get: function () {
  37890. return this._isCachedGroup;
  37891. },
  37892. enumerable: true,
  37893. configurable: true
  37894. });
  37895. Object.defineProperty(Group2D.prototype, "size", {
  37896. get: function () {
  37897. return this._size;
  37898. },
  37899. /**
  37900. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  37901. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  37902. */
  37903. set: function (val) {
  37904. this._size = val;
  37905. },
  37906. enumerable: true,
  37907. configurable: true
  37908. });
  37909. Object.defineProperty(Group2D.prototype, "viewportSize", {
  37910. get: function () {
  37911. return this._viewportSize;
  37912. },
  37913. enumerable: true,
  37914. configurable: true
  37915. });
  37916. Object.defineProperty(Group2D.prototype, "actualSize", {
  37917. get: function () {
  37918. // The computed size will be floor on both width and height
  37919. var actualSize;
  37920. // Return the size if set by the user
  37921. if (this._size) {
  37922. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  37923. }
  37924. else {
  37925. var m = this.boundingInfo.max();
  37926. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  37927. }
  37928. // Compare the size with the one we previously had, if it differ we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  37929. if (!actualSize.equals(this._actualSize)) {
  37930. this._instanceDirtyFlags |= Group2D.actualSizeProperty.flagId;
  37931. this._actualSize = actualSize;
  37932. this.handleGroupChanged(Group2D.actualSizeProperty);
  37933. }
  37934. return actualSize;
  37935. },
  37936. enumerable: true,
  37937. configurable: true
  37938. });
  37939. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  37940. /**
  37941. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  37942. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  37943. */
  37944. get: function () {
  37945. return this._cacheBehavior;
  37946. },
  37947. enumerable: true,
  37948. configurable: true
  37949. });
  37950. Group2D.prototype._addPrimToDirtyList = function (prim) {
  37951. this._primDirtyList.push(prim);
  37952. };
  37953. Group2D.prototype._renderCachedCanvas = function (context) {
  37954. this.updateGlobalTransVis(true);
  37955. this._prepareGroupRender(context);
  37956. this._groupRender(context);
  37957. };
  37958. Group2D.prototype.levelIntersect = function (intersectInfo) {
  37959. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  37960. return true;
  37961. };
  37962. Group2D.prototype.updateLevelBoundingInfo = function () {
  37963. var size;
  37964. // If the size is set by the user, the boundingInfo is computed from this value
  37965. if (this.size) {
  37966. size = this.size;
  37967. }
  37968. else {
  37969. size = new BABYLON.Size(0, 0);
  37970. }
  37971. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  37972. };
  37973. // Method called only on renderable groups to prepare the rendering
  37974. Group2D.prototype._prepareGroupRender = function (context) {
  37975. var sortedDirtyList = null;
  37976. // Update the Global Transformation and visibility status of the changed primitives
  37977. if ((this._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  37978. sortedDirtyList = this._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  37979. this.updateGlobalTransVisOf(sortedDirtyList, true);
  37980. }
  37981. // Setup the size of the rendering viewport
  37982. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  37983. if (!this._isCachedGroup) {
  37984. // Compute the WebGL viewport's location/size
  37985. var t = this._globalTransform.getTranslation();
  37986. var s = this.actualSize.clone();
  37987. var rs = this.owner._renderingSize;
  37988. s.height = Math.min(s.height, rs.height - t.y);
  37989. s.width = Math.min(s.width, rs.width - t.x);
  37990. var x = t.x;
  37991. var y = t.y;
  37992. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  37993. this._viewportPosition.x = x;
  37994. this._viewportPosition.y = y;
  37995. var vw = s.width;
  37996. var vh = s.height;
  37997. if (!this._viewportSize) {
  37998. this._viewportSize = new BABYLON.Size(vw, vh);
  37999. }
  38000. else {
  38001. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  38002. context.forceRefreshPrimitive = true;
  38003. }
  38004. this._viewportSize.width = vw;
  38005. this._viewportSize.height = vh;
  38006. }
  38007. }
  38008. else {
  38009. var newSize = this.actualSize.clone();
  38010. if (!newSize.equals(this._viewportSize)) {
  38011. context.forceRefreshPrimitive = true;
  38012. }
  38013. this._viewportSize = newSize;
  38014. }
  38015. if ((this._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  38016. // If the group is cached, set the dirty flag to true because of the incoming changes
  38017. this._cacheGroupDirty = this._isCachedGroup;
  38018. // If it's a force refresh, prepare all the children
  38019. if (context.forceRefreshPrimitive) {
  38020. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  38021. var p = _a[_i];
  38022. p._prepareRender(context);
  38023. }
  38024. }
  38025. else {
  38026. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  38027. // the hierarchyDepth in order to prepare primitives from top to bottom
  38028. if (!sortedDirtyList) {
  38029. sortedDirtyList = this._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  38030. }
  38031. sortedDirtyList.forEach(function (p) {
  38032. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  38033. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  38034. if (!p.isDisposed && p._needPrepare()) {
  38035. p._prepareRender(context);
  38036. }
  38037. });
  38038. // Everything is updated, clear the dirty list
  38039. this._primDirtyList.splice(0);
  38040. }
  38041. }
  38042. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  38043. this._childrenRenderableGroups.forEach(function (g) {
  38044. g._prepareGroupRender(context);
  38045. });
  38046. };
  38047. Group2D.prototype._groupRender = function (context) {
  38048. var _this = this;
  38049. var engine = this.owner.engine;
  38050. var failedCount = 0;
  38051. // First recurse to children render group to render them (in their cache or on screen)
  38052. for (var _i = 0, _a = this._childrenRenderableGroups; _i < _a.length; _i++) {
  38053. var childGroup = _a[_i];
  38054. childGroup._groupRender(context);
  38055. }
  38056. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  38057. if (!this.isCachedGroup || this._cacheGroupDirty) {
  38058. if (this.isCachedGroup) {
  38059. this._bindCacheTarget();
  38060. }
  38061. else {
  38062. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  38063. }
  38064. // For each different model of primitive to render
  38065. var totalRenderCount = 0;
  38066. this._renderGroupInstancesInfo.forEach(function (k, v) {
  38067. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  38068. // Skip it if instanced arrays are not supported
  38069. if (_this.owner.supportInstancedArray) {
  38070. for (var i = 0; i < v._instancesPartsData.length; i++) {
  38071. // If the instances of the model was changed, pack the data
  38072. var array = v._instancesPartsData[i];
  38073. var instanceData_1 = array.pack();
  38074. totalRenderCount += array.usedElementCount;
  38075. // Compute the size the instance buffer should have
  38076. var neededSize = array.usedElementCount * array.stride * 4;
  38077. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  38078. if (!v._instancesPartsBuffer[i] || (v._instancesPartsBufferSize[i] < neededSize)) {
  38079. if (v._instancesPartsBuffer[i]) {
  38080. engine.deleteInstancesBuffer(v._instancesPartsBuffer[i]);
  38081. }
  38082. v._instancesPartsBuffer[i] = engine.createInstancesBuffer(neededSize);
  38083. v._instancesPartsBufferSize[i] = neededSize;
  38084. v._dirtyInstancesData = false;
  38085. // Update the WebGL buffer to match the new content of the instances data
  38086. engine._gl.bufferSubData(engine._gl.ARRAY_BUFFER, 0, instanceData_1);
  38087. }
  38088. else if (v._dirtyInstancesData) {
  38089. // Update the WebGL buffer to match the new content of the instances data
  38090. engine._gl.bindBuffer(engine._gl.ARRAY_BUFFER, v._instancesPartsBuffer[i]);
  38091. engine._gl.bufferSubData(engine._gl.ARRAY_BUFFER, 0, instanceData_1);
  38092. v._dirtyInstancesData = false;
  38093. }
  38094. }
  38095. }
  38096. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  38097. if (!_this.owner.supportInstancedArray || totalRenderCount > 0) {
  38098. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  38099. var renderFailed = !v._modelCache.render(v, context);
  38100. // Update dirty flag/related
  38101. v._dirtyInstancesData = renderFailed;
  38102. failedCount += renderFailed ? 1 : 0;
  38103. }
  38104. });
  38105. // The group's content is no longer dirty
  38106. this._cacheGroupDirty = failedCount !== 0;
  38107. if (this.isCachedGroup) {
  38108. this._unbindCacheTarget();
  38109. }
  38110. else {
  38111. if (curVP) {
  38112. engine.setViewport(curVP);
  38113. }
  38114. }
  38115. }
  38116. };
  38117. Group2D.prototype._bindCacheTarget = function () {
  38118. var curWidth;
  38119. var curHeight;
  38120. if (this._cacheNode) {
  38121. var size = this._cacheNode.contentSize;
  38122. var groupWidth = Math.ceil(this.actualSize.width);
  38123. var groupHeight = Math.ceil(this.actualSize.height);
  38124. if ((size.width < groupWidth) || (size.height < groupHeight)) {
  38125. curWidth = Math.floor(size.width * 1.07); // Grow 5% more to avoid frequent resizing for few pixels...
  38126. curHeight = Math.floor(size.height * 1.07);
  38127. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  38128. this._cacheTexture.freeRect(this._cacheNode);
  38129. this._cacheNode = null;
  38130. }
  38131. }
  38132. if (!this._cacheNode) {
  38133. // Check if we have to allocate a rendering zone in the global cache texture
  38134. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null);
  38135. this._cacheNode = res.node;
  38136. this._cacheTexture = res.texture;
  38137. this._cacheRenderSprite = res.sprite;
  38138. var size = this._cacheNode.contentSize;
  38139. }
  38140. var n = this._cacheNode;
  38141. this._cacheTexture.bindTextureForPosSize(n.pos, this.actualSize, true);
  38142. };
  38143. Group2D.prototype._unbindCacheTarget = function () {
  38144. if (this._cacheTexture) {
  38145. this._cacheTexture.unbindTexture();
  38146. }
  38147. };
  38148. Group2D.prototype.handleGroupChanged = function (prop) {
  38149. // This method is only for cachedGroup
  38150. if (!this.isCachedGroup || !this._cacheRenderSprite) {
  38151. return;
  38152. }
  38153. // For now we only support these property changes
  38154. // TODO: add more! :)
  38155. if (prop.id === BABYLON.Prim2DBase.positionProperty.id) {
  38156. this._cacheRenderSprite.position = this.position.clone();
  38157. }
  38158. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  38159. this._cacheRenderSprite.rotation = this.rotation;
  38160. }
  38161. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  38162. this._cacheRenderSprite.scale = this.scale;
  38163. }
  38164. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  38165. this._cacheRenderSprite.origin = this.origin.clone();
  38166. }
  38167. else if (prop.id === Group2D.actualSizeProperty.id) {
  38168. this._cacheRenderSprite.spriteSize = this.actualSize.clone();
  38169. }
  38170. };
  38171. Group2D.prototype.detectGroupStates = function () {
  38172. var isCanvas = this instanceof BABYLON.Canvas2D;
  38173. var canvasStrat = this.owner.cachingStrategy;
  38174. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  38175. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  38176. this._isRenderableGroup = isCanvas;
  38177. this._isCachedGroup = false;
  38178. }
  38179. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  38180. if (isCanvas) {
  38181. this._isRenderableGroup = true;
  38182. this._isCachedGroup = true;
  38183. }
  38184. else {
  38185. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  38186. this._isCachedGroup = false;
  38187. }
  38188. }
  38189. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  38190. if (isCanvas) {
  38191. this._isRenderableGroup = true;
  38192. this._isCachedGroup = false;
  38193. }
  38194. else {
  38195. if (this.hierarchyDepth === 1) {
  38196. this._isRenderableGroup = true;
  38197. this._isCachedGroup = true;
  38198. }
  38199. else {
  38200. this._isRenderableGroup = false;
  38201. this._isCachedGroup = false;
  38202. }
  38203. }
  38204. }
  38205. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  38206. var gcb = this.cacheBehavior;
  38207. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  38208. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  38209. this._isCachedGroup = false;
  38210. }
  38211. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  38212. this._isRenderableGroup = true;
  38213. this._isCachedGroup = true;
  38214. }
  38215. }
  38216. // If the group is tagged as renderable we add it to the renderable tree
  38217. if (this._isCachedGroup) {
  38218. var cur = this.parent;
  38219. while (cur) {
  38220. if (cur instanceof Group2D && cur._isRenderableGroup) {
  38221. cur._childrenRenderableGroups.push(this);
  38222. break;
  38223. }
  38224. cur = cur.parent;
  38225. }
  38226. }
  38227. };
  38228. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  38229. /**
  38230. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  38231. */
  38232. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  38233. /**
  38234. * When used, this group's content won't be cached, no matter which strategy used.
  38235. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  38236. */
  38237. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  38238. /**
  38239. * When used, the group's content will be cached in the nearest cached parent group/canvas
  38240. */
  38241. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  38242. __decorate([
  38243. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  38244. ], Group2D.prototype, "size", null);
  38245. __decorate([
  38246. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  38247. ], Group2D.prototype, "actualSize", null);
  38248. Group2D = __decorate([
  38249. BABYLON.className("Group2D")
  38250. ], Group2D);
  38251. return Group2D;
  38252. })(BABYLON.Prim2DBase);
  38253. BABYLON.Group2D = Group2D;
  38254. })(BABYLON || (BABYLON = {}));
  38255. var BABYLON;
  38256. (function (BABYLON) {
  38257. var Rectangle2DRenderCache = (function (_super) {
  38258. __extends(Rectangle2DRenderCache, _super);
  38259. function Rectangle2DRenderCache(engine, modelKey, isTransparent) {
  38260. _super.call(this, engine, modelKey, isTransparent);
  38261. }
  38262. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  38263. // Do nothing if the shader is still loading/preparing
  38264. if ((this.effectFill && !this.effectFill.isReady()) || (this.effectBorder && !this.effectBorder.isReady())) {
  38265. return false;
  38266. }
  38267. var engine = instanceInfo._owner.owner.engine;
  38268. var depthFunction = 0;
  38269. if (this.effectFill && this.effectBorder) {
  38270. depthFunction = engine.getDepthFunction();
  38271. engine.setDepthFunctionToLessOrEqual();
  38272. }
  38273. var cur;
  38274. if (this.isTransparent) {
  38275. cur = engine.getAlphaMode();
  38276. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38277. }
  38278. if (this.effectFill) {
  38279. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  38280. engine.enableEffect(this.effectFill);
  38281. engine.bindBuffers(this.fillVB, this.fillIB, [1], 4, this.effectFill);
  38282. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38283. if (instanceInfo._owner.owner.supportInstancedArray) {
  38284. if (!this.instancingFillAttributes) {
  38285. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  38286. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, this.effectFill);
  38287. }
  38288. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingFillAttributes);
  38289. engine.draw(true, 0, this.fillIndicesCount, count);
  38290. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingFillAttributes);
  38291. }
  38292. else {
  38293. for (var i = 0; i < count; i++) {
  38294. this.setupUniforms(this.effectFill, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38295. engine.draw(true, 0, this.fillIndicesCount);
  38296. }
  38297. }
  38298. }
  38299. if (this.effectBorder) {
  38300. var partIndex = instanceInfo._partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  38301. engine.enableEffect(this.effectBorder);
  38302. engine.bindBuffers(this.borderVB, this.borderIB, [1], 4, this.effectBorder);
  38303. var count = instanceInfo._instancesPartsData[partIndex].usedElementCount;
  38304. if (instanceInfo._owner.owner.supportInstancedArray) {
  38305. if (!this.instancingBorderAttributes) {
  38306. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, this.effectBorder);
  38307. }
  38308. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], null, this.instancingBorderAttributes);
  38309. engine.draw(true, 0, this.borderIndicesCount, count);
  38310. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[partIndex], this.instancingBorderAttributes);
  38311. }
  38312. else {
  38313. for (var i = 0; i < count; i++) {
  38314. this.setupUniforms(this.effectBorder, partIndex, instanceInfo._instancesPartsData[partIndex], i);
  38315. engine.draw(true, 0, this.borderIndicesCount);
  38316. }
  38317. }
  38318. }
  38319. if (this.isTransparent) {
  38320. engine.setAlphaMode(cur);
  38321. }
  38322. if (this.effectFill && this.effectBorder) {
  38323. engine.setDepthFunction(depthFunction);
  38324. }
  38325. return true;
  38326. };
  38327. Rectangle2DRenderCache.prototype.dispose = function () {
  38328. if (!_super.prototype.dispose.call(this)) {
  38329. return false;
  38330. }
  38331. if (this.fillVB) {
  38332. this._engine._releaseBuffer(this.fillVB);
  38333. this.fillVB = null;
  38334. }
  38335. if (this.fillIB) {
  38336. this._engine._releaseBuffer(this.fillIB);
  38337. this.fillIB = null;
  38338. }
  38339. if (this.effectFill) {
  38340. this._engine._releaseEffect(this.effectFill);
  38341. this.effectFill = null;
  38342. }
  38343. if (this.borderVB) {
  38344. this._engine._releaseBuffer(this.borderVB);
  38345. this.borderVB = null;
  38346. }
  38347. if (this.borderIB) {
  38348. this._engine._releaseBuffer(this.borderIB);
  38349. this.borderIB = null;
  38350. }
  38351. if (this.effectBorder) {
  38352. this._engine._releaseEffect(this.effectBorder);
  38353. this.effectBorder = null;
  38354. }
  38355. return true;
  38356. };
  38357. return Rectangle2DRenderCache;
  38358. })(BABYLON.ModelRenderCache);
  38359. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  38360. var Rectangle2DInstanceData = (function (_super) {
  38361. __extends(Rectangle2DInstanceData, _super);
  38362. function Rectangle2DInstanceData(partId) {
  38363. _super.call(this, partId, 1);
  38364. }
  38365. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  38366. get: function () {
  38367. return null;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. __decorate([
  38373. BABYLON.instanceData()
  38374. ], Rectangle2DInstanceData.prototype, "properties", null);
  38375. return Rectangle2DInstanceData;
  38376. })(BABYLON.Shape2DInstanceData);
  38377. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  38378. var Rectangle2D = (function (_super) {
  38379. __extends(Rectangle2D, _super);
  38380. function Rectangle2D() {
  38381. _super.apply(this, arguments);
  38382. }
  38383. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  38384. get: function () {
  38385. return this.size;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. Object.defineProperty(Rectangle2D.prototype, "size", {
  38391. get: function () {
  38392. return this._size;
  38393. },
  38394. set: function (value) {
  38395. this._size = value;
  38396. },
  38397. enumerable: true,
  38398. configurable: true
  38399. });
  38400. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  38401. get: function () {
  38402. return this._notRounded;
  38403. },
  38404. set: function (value) {
  38405. this._notRounded = value;
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  38411. get: function () {
  38412. return this._roundRadius;
  38413. },
  38414. set: function (value) {
  38415. this._roundRadius = value;
  38416. this.notRounded = value === 0;
  38417. },
  38418. enumerable: true,
  38419. configurable: true
  38420. });
  38421. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  38422. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  38423. if (this.notRounded) {
  38424. return true;
  38425. }
  38426. // Well, for now we neglect the area where the pickPosition could be outside due to the roundRadius...
  38427. // TODO make REAL intersection test here!
  38428. return true;
  38429. };
  38430. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  38431. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo, this.origin);
  38432. };
  38433. Rectangle2D.prototype.setupRectangle2D = function (owner, parent, id, position, size, roundRadius, fill, border, borderThickness) {
  38434. if (roundRadius === void 0) { roundRadius = 0; }
  38435. if (borderThickness === void 0) { borderThickness = 1; }
  38436. this.setupShape2D(owner, parent, id, position, true, fill, border, borderThickness);
  38437. this.size = size;
  38438. this.notRounded = !roundRadius;
  38439. this.roundRadius = roundRadius;
  38440. };
  38441. Rectangle2D.Create = function (parent, id, x, y, width, height, fill, border) {
  38442. BABYLON.Prim2DBase.CheckParent(parent);
  38443. var rect = new Rectangle2D();
  38444. rect.setupRectangle2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), new BABYLON.Size(width, height), null);
  38445. rect.fill = fill;
  38446. rect.border = border;
  38447. return rect;
  38448. };
  38449. Rectangle2D.CreateRounded = function (parent, id, x, y, width, height, roundRadius, fill, border) {
  38450. if (roundRadius === void 0) { roundRadius = 0; }
  38451. BABYLON.Prim2DBase.CheckParent(parent);
  38452. var rect = new Rectangle2D();
  38453. rect.setupRectangle2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), new BABYLON.Size(width, height), roundRadius);
  38454. rect.fill = fill || BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF");
  38455. rect.border = border;
  38456. return rect;
  38457. };
  38458. Rectangle2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  38459. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey, isTransparent);
  38460. return renderCache;
  38461. };
  38462. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38463. var renderCache = modelRenderCache;
  38464. var engine = this.owner.engine;
  38465. // Need to create WebGL resources for fill part?
  38466. if (this.fill) {
  38467. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  38468. var vb = new Float32Array(vbSize);
  38469. for (var i = 0; i < vbSize; i++) {
  38470. vb[i] = i;
  38471. }
  38472. renderCache.fillVB = engine.createVertexBuffer(vb);
  38473. var triCount = vbSize - 1;
  38474. var ib = new Float32Array(triCount * 3);
  38475. for (var i = 0; i < triCount; i++) {
  38476. ib[i * 3 + 0] = 0;
  38477. ib[i * 3 + 2] = i + 1;
  38478. ib[i * 3 + 1] = i + 2;
  38479. }
  38480. ib[triCount * 3 - 2] = 1;
  38481. renderCache.fillIB = engine.createIndexBuffer(ib);
  38482. renderCache.fillIndicesCount = triCount * 3;
  38483. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"]);
  38484. renderCache.effectFill = engine.createEffect({ vertex: "rect2d", fragment: "rect2d" }, ei.attributes, ei.uniforms, [], ei.defines, null, function (e) {
  38485. // renderCache.setupUniformsLocation(e, ei.uniforms, Shape2D.SHAPE2D_FILLPARTID);
  38486. });
  38487. }
  38488. // Need to create WebGL resource for border part?
  38489. if (this.border) {
  38490. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  38491. var vb = new Float32Array(vbSize);
  38492. for (var i = 0; i < vbSize; i++) {
  38493. vb[i] = i;
  38494. }
  38495. renderCache.borderVB = engine.createVertexBuffer(vb);
  38496. var triCount = vbSize;
  38497. var rs = triCount / 2;
  38498. var ib = new Float32Array(triCount * 3);
  38499. for (var i = 0; i < rs; i++) {
  38500. var r0 = i;
  38501. var r1 = (i + 1) % rs;
  38502. ib[i * 6 + 0] = rs + r1;
  38503. ib[i * 6 + 1] = rs + r0;
  38504. ib[i * 6 + 2] = r0;
  38505. ib[i * 6 + 3] = r1;
  38506. ib[i * 6 + 4] = rs + r1;
  38507. ib[i * 6 + 5] = r0;
  38508. }
  38509. renderCache.borderIB = engine.createIndexBuffer(ib);
  38510. renderCache.borderIndicesCount = triCount * 3;
  38511. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"]);
  38512. renderCache.effectBorder = engine.createEffect({ vertex: "rect2d", fragment: "rect2d" }, ei.attributes, ei.uniforms, [], ei.defines, null, function (e) {
  38513. // renderCache.setupUniformsLocation(e, ei.uniforms, Shape2D.SHAPE2D_BORDERPARTID);
  38514. });
  38515. }
  38516. return renderCache;
  38517. };
  38518. Rectangle2D.prototype.createInstanceDataParts = function () {
  38519. var res = new Array();
  38520. if (this.border) {
  38521. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  38522. }
  38523. if (this.fill) {
  38524. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  38525. }
  38526. return res;
  38527. };
  38528. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  38529. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38530. return false;
  38531. }
  38532. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  38533. var d = part;
  38534. var size = this.size;
  38535. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  38536. }
  38537. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  38538. var d = part;
  38539. var size = this.size;
  38540. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  38541. }
  38542. return true;
  38543. };
  38544. Rectangle2D.roundSubdivisions = 16;
  38545. __decorate([
  38546. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.sizeProperty = pi; }, false, true)
  38547. ], Rectangle2D.prototype, "size", null);
  38548. __decorate([
  38549. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  38550. ], Rectangle2D.prototype, "notRounded", null);
  38551. __decorate([
  38552. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  38553. ], Rectangle2D.prototype, "roundRadius", null);
  38554. Rectangle2D = __decorate([
  38555. BABYLON.className("Rectangle2D")
  38556. ], Rectangle2D);
  38557. return Rectangle2D;
  38558. })(BABYLON.Shape2D);
  38559. BABYLON.Rectangle2D = Rectangle2D;
  38560. })(BABYLON || (BABYLON = {}));
  38561. var BABYLON;
  38562. (function (BABYLON) {
  38563. var Sprite2DRenderCache = (function (_super) {
  38564. __extends(Sprite2DRenderCache, _super);
  38565. function Sprite2DRenderCache() {
  38566. _super.apply(this, arguments);
  38567. }
  38568. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  38569. // Do nothing if the shader is still loading/preparing
  38570. if (!this.effect.isReady() || !this.texture.isReady()) {
  38571. return false;
  38572. }
  38573. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  38574. var engine = instanceInfo._owner.owner.engine;
  38575. engine.enableEffect(this.effect);
  38576. this.effect.setTexture("diffuseSampler", this.texture);
  38577. engine.bindBuffers(this.vb, this.ib, [1], 4, this.effect);
  38578. var cur = engine.getAlphaMode();
  38579. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38580. var count = instanceInfo._instancesPartsData[0].usedElementCount;
  38581. if (instanceInfo._owner.owner.supportInstancedArray) {
  38582. if (!this.instancingAttributes) {
  38583. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, this.effect);
  38584. }
  38585. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], null, this.instancingAttributes);
  38586. engine.draw(true, 0, 6, count);
  38587. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], this.instancingAttributes);
  38588. }
  38589. else {
  38590. for (var i = 0; i < count; i++) {
  38591. this.setupUniforms(this.effect, 0, instanceInfo._instancesPartsData[0], i);
  38592. engine.draw(true, 0, 6);
  38593. }
  38594. }
  38595. engine.setAlphaMode(cur);
  38596. return true;
  38597. };
  38598. Sprite2DRenderCache.prototype.dispose = function () {
  38599. if (!_super.prototype.dispose.call(this)) {
  38600. return false;
  38601. }
  38602. if (this.vb) {
  38603. this._engine._releaseBuffer(this.vb);
  38604. this.vb = null;
  38605. }
  38606. if (this.ib) {
  38607. this._engine._releaseBuffer(this.ib);
  38608. this.ib = null;
  38609. }
  38610. if (this.texture) {
  38611. this.texture.dispose();
  38612. this.texture = null;
  38613. }
  38614. if (this.effect) {
  38615. this._engine._releaseEffect(this.effect);
  38616. this.effect = null;
  38617. }
  38618. return true;
  38619. };
  38620. return Sprite2DRenderCache;
  38621. })(BABYLON.ModelRenderCache);
  38622. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  38623. var Sprite2DInstanceData = (function (_super) {
  38624. __extends(Sprite2DInstanceData, _super);
  38625. function Sprite2DInstanceData(partId) {
  38626. _super.call(this, partId, 1);
  38627. }
  38628. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  38629. get: function () {
  38630. return null;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  38636. get: function () {
  38637. return null;
  38638. },
  38639. enumerable: true,
  38640. configurable: true
  38641. });
  38642. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  38643. get: function () {
  38644. return null;
  38645. },
  38646. enumerable: true,
  38647. configurable: true
  38648. });
  38649. Object.defineProperty(Sprite2DInstanceData.prototype, "frame", {
  38650. get: function () {
  38651. return null;
  38652. },
  38653. enumerable: true,
  38654. configurable: true
  38655. });
  38656. Object.defineProperty(Sprite2DInstanceData.prototype, "invertY", {
  38657. get: function () {
  38658. return null;
  38659. },
  38660. enumerable: true,
  38661. configurable: true
  38662. });
  38663. __decorate([
  38664. BABYLON.instanceData()
  38665. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  38666. __decorate([
  38667. BABYLON.instanceData()
  38668. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  38669. __decorate([
  38670. BABYLON.instanceData()
  38671. ], Sprite2DInstanceData.prototype, "textureSize", null);
  38672. __decorate([
  38673. BABYLON.instanceData()
  38674. ], Sprite2DInstanceData.prototype, "frame", null);
  38675. __decorate([
  38676. BABYLON.instanceData()
  38677. ], Sprite2DInstanceData.prototype, "invertY", null);
  38678. return Sprite2DInstanceData;
  38679. })(BABYLON.InstanceDataBase);
  38680. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  38681. var Sprite2D = (function (_super) {
  38682. __extends(Sprite2D, _super);
  38683. function Sprite2D() {
  38684. _super.apply(this, arguments);
  38685. }
  38686. Object.defineProperty(Sprite2D.prototype, "texture", {
  38687. get: function () {
  38688. return this._texture;
  38689. },
  38690. set: function (value) {
  38691. this._texture = value;
  38692. },
  38693. enumerable: true,
  38694. configurable: true
  38695. });
  38696. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  38697. get: function () {
  38698. return this.spriteSize;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  38704. get: function () {
  38705. return this._size;
  38706. },
  38707. set: function (value) {
  38708. this._size = value;
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  38714. get: function () {
  38715. return this._location;
  38716. },
  38717. set: function (value) {
  38718. this._location = value;
  38719. },
  38720. enumerable: true,
  38721. configurable: true
  38722. });
  38723. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  38724. get: function () {
  38725. return this._spriteFrame;
  38726. },
  38727. set: function (value) {
  38728. this._spriteFrame = value;
  38729. },
  38730. enumerable: true,
  38731. configurable: true
  38732. });
  38733. Object.defineProperty(Sprite2D.prototype, "invertY", {
  38734. get: function () {
  38735. return this._invertY;
  38736. },
  38737. set: function (value) {
  38738. this._invertY = value;
  38739. },
  38740. enumerable: true,
  38741. configurable: true
  38742. });
  38743. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  38744. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.spriteSize, this._levelBoundingInfo, this.origin);
  38745. };
  38746. Sprite2D.prototype.getAnimatables = function () {
  38747. var res = new Array();
  38748. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  38749. res.push(this.texture);
  38750. }
  38751. return res;
  38752. };
  38753. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  38754. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  38755. return true;
  38756. };
  38757. Sprite2D.prototype.setupSprite2D = function (owner, parent, id, position, texture, spriteSize, spriteLocation, invertY) {
  38758. this.setupRenderablePrim2D(owner, parent, id, position, true);
  38759. this.texture = texture;
  38760. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38761. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38762. this.spriteSize = spriteSize;
  38763. this.spriteLocation = spriteLocation;
  38764. this.spriteFrame = 0;
  38765. this.invertY = invertY;
  38766. this._isTransparent = true;
  38767. };
  38768. Sprite2D.Create = function (parent, id, x, y, texture, spriteSize, spriteLocation, invertY) {
  38769. if (invertY === void 0) { invertY = false; }
  38770. BABYLON.Prim2DBase.CheckParent(parent);
  38771. var sprite = new Sprite2D();
  38772. sprite.setupSprite2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), texture, spriteSize, spriteLocation, invertY);
  38773. return sprite;
  38774. };
  38775. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  38776. var sprite = new Sprite2D();
  38777. sprite.setupSprite2D(owner, null, "__cachedCanvasSprite__", new BABYLON.Vector2(0, 0), texture, size, pos, false);
  38778. return sprite;
  38779. };
  38780. Sprite2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  38781. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey, isTransparent);
  38782. return renderCache;
  38783. };
  38784. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  38785. var renderCache = modelRenderCache;
  38786. var engine = this.owner.engine;
  38787. var vb = new Float32Array(4);
  38788. for (var i = 0; i < 4; i++) {
  38789. vb[i] = i;
  38790. }
  38791. renderCache.vb = engine.createVertexBuffer(vb);
  38792. var ib = new Float32Array(6);
  38793. ib[0] = 0;
  38794. ib[1] = 2;
  38795. ib[2] = 1;
  38796. ib[3] = 0;
  38797. ib[4] = 3;
  38798. ib[5] = 2;
  38799. renderCache.ib = engine.createIndexBuffer(ib);
  38800. renderCache.texture = this.texture;
  38801. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"]);
  38802. renderCache.effect = engine.createEffect({ vertex: "sprite2d", fragment: "sprite2d" }, ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null, function (e) {
  38803. // renderCache.setupUniformsLocation(e, ei.uniforms, Sprite2D.SPRITE2D_MAINPARTID);
  38804. });
  38805. return renderCache;
  38806. };
  38807. Sprite2D.prototype.createInstanceDataParts = function () {
  38808. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  38809. };
  38810. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  38811. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  38812. return false;
  38813. }
  38814. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  38815. var d = this._instanceDataParts[0];
  38816. var ts = this.texture.getSize();
  38817. var sl = this.spriteLocation;
  38818. var ss = this.spriteSize;
  38819. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  38820. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  38821. d.sizeUV = suv;
  38822. d.frame = this.spriteFrame;
  38823. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  38824. d.invertY = this.invertY ? 1 : 0;
  38825. }
  38826. return true;
  38827. };
  38828. Sprite2D.SPRITE2D_MAINPARTID = 1;
  38829. __decorate([
  38830. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  38831. ], Sprite2D.prototype, "texture", null);
  38832. __decorate([
  38833. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.spriteSizeProperty = pi; }, false, true)
  38834. ], Sprite2D.prototype, "spriteSize", null);
  38835. __decorate([
  38836. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  38837. ], Sprite2D.prototype, "spriteLocation", null);
  38838. __decorate([
  38839. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  38840. ], Sprite2D.prototype, "spriteFrame", null);
  38841. __decorate([
  38842. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  38843. ], Sprite2D.prototype, "invertY", null);
  38844. Sprite2D = __decorate([
  38845. BABYLON.className("Sprite2D")
  38846. ], Sprite2D);
  38847. return Sprite2D;
  38848. })(BABYLON.RenderablePrim2D);
  38849. BABYLON.Sprite2D = Sprite2D;
  38850. })(BABYLON || (BABYLON = {}));
  38851. var BABYLON;
  38852. (function (BABYLON) {
  38853. var Text2DRenderCache = (function (_super) {
  38854. __extends(Text2DRenderCache, _super);
  38855. function Text2DRenderCache() {
  38856. _super.apply(this, arguments);
  38857. }
  38858. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  38859. // Do nothing if the shader is still loading/preparing
  38860. if (!this.effect.isReady() || !this.fontTexture.isReady()) {
  38861. return false;
  38862. }
  38863. // Compute the offset locations of the attributes in the vertexshader that will be mapped to the instance buffer data
  38864. if (!this.instancingAttributes) {
  38865. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, this.effect);
  38866. }
  38867. var engine = instanceInfo._owner.owner.engine;
  38868. this.fontTexture.update();
  38869. engine.enableEffect(this.effect);
  38870. this.effect.setTexture("diffuseSampler", this.fontTexture);
  38871. engine.bindBuffers(this.vb, this.ib, [1], 4, this.effect);
  38872. var cur = engine.getAlphaMode();
  38873. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  38874. var count = instanceInfo._instancesPartsData[0].usedElementCount;
  38875. if (instanceInfo._owner.owner.supportInstancedArray) {
  38876. engine.updateAndBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], null, this.instancingAttributes);
  38877. engine.draw(true, 0, 6, count);
  38878. engine.unBindInstancesBuffer(instanceInfo._instancesPartsBuffer[0], this.instancingAttributes);
  38879. }
  38880. else {
  38881. for (var i = 0; i < count; i++) {
  38882. this.setupUniforms(this.effect, 0, instanceInfo._instancesPartsData[0], i);
  38883. engine.draw(true, 0, 6);
  38884. }
  38885. }
  38886. engine.setAlphaMode(cur);
  38887. return true;
  38888. };
  38889. Text2DRenderCache.prototype.dispose = function () {
  38890. if (!_super.prototype.dispose.call(this)) {
  38891. return false;
  38892. }
  38893. if (this.vb) {
  38894. this._engine._releaseBuffer(this.vb);
  38895. this.vb = null;
  38896. }
  38897. if (this.ib) {
  38898. this._engine._releaseBuffer(this.ib);
  38899. this.ib = null;
  38900. }
  38901. if (this.fontTexture) {
  38902. this.fontTexture.dispose();
  38903. this.fontTexture = null;
  38904. }
  38905. if (this.effect) {
  38906. this._engine._releaseEffect(this.effect);
  38907. this.effect = null;
  38908. }
  38909. return true;
  38910. };
  38911. return Text2DRenderCache;
  38912. })(BABYLON.ModelRenderCache);
  38913. BABYLON.Text2DRenderCache = Text2DRenderCache;
  38914. var Text2DInstanceData = (function (_super) {
  38915. __extends(Text2DInstanceData, _super);
  38916. function Text2DInstanceData(partId, dataElementCount) {
  38917. _super.call(this, partId, dataElementCount);
  38918. }
  38919. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  38920. get: function () {
  38921. return null;
  38922. },
  38923. enumerable: true,
  38924. configurable: true
  38925. });
  38926. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  38927. get: function () {
  38928. return null;
  38929. },
  38930. enumerable: true,
  38931. configurable: true
  38932. });
  38933. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  38934. get: function () {
  38935. return null;
  38936. },
  38937. enumerable: true,
  38938. configurable: true
  38939. });
  38940. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  38941. get: function () {
  38942. return null;
  38943. },
  38944. enumerable: true,
  38945. configurable: true
  38946. });
  38947. __decorate([
  38948. BABYLON.instanceData()
  38949. ], Text2DInstanceData.prototype, "topLeftUV", null);
  38950. __decorate([
  38951. BABYLON.instanceData()
  38952. ], Text2DInstanceData.prototype, "sizeUV", null);
  38953. __decorate([
  38954. BABYLON.instanceData()
  38955. ], Text2DInstanceData.prototype, "textureSize", null);
  38956. __decorate([
  38957. BABYLON.instanceData()
  38958. ], Text2DInstanceData.prototype, "color", null);
  38959. return Text2DInstanceData;
  38960. })(BABYLON.InstanceDataBase);
  38961. BABYLON.Text2DInstanceData = Text2DInstanceData;
  38962. var Text2D = (function (_super) {
  38963. __extends(Text2D, _super);
  38964. function Text2D() {
  38965. _super.apply(this, arguments);
  38966. }
  38967. Object.defineProperty(Text2D.prototype, "fontName", {
  38968. get: function () {
  38969. return this._fontName;
  38970. },
  38971. set: function (value) {
  38972. if (this._fontName) {
  38973. throw new Error("Font Name change is not supported right now.");
  38974. }
  38975. this._fontName = value;
  38976. },
  38977. enumerable: true,
  38978. configurable: true
  38979. });
  38980. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  38981. get: function () {
  38982. return this._defaultFontColor;
  38983. },
  38984. set: function (value) {
  38985. this._defaultFontColor = value;
  38986. },
  38987. enumerable: true,
  38988. configurable: true
  38989. });
  38990. Object.defineProperty(Text2D.prototype, "text", {
  38991. get: function () {
  38992. return this._text;
  38993. },
  38994. set: function (value) {
  38995. this._text = value;
  38996. this._actualSize = null; // A change of text will reset the Actual Area Size which will be recomputed next time it's used
  38997. this._updateCharCount();
  38998. },
  38999. enumerable: true,
  39000. configurable: true
  39001. });
  39002. Object.defineProperty(Text2D.prototype, "areaSize", {
  39003. get: function () {
  39004. return this._areaSize;
  39005. },
  39006. set: function (value) {
  39007. this._areaSize = value;
  39008. },
  39009. enumerable: true,
  39010. configurable: true
  39011. });
  39012. Object.defineProperty(Text2D.prototype, "vAlign", {
  39013. get: function () {
  39014. return this._vAlign;
  39015. },
  39016. set: function (value) {
  39017. this._vAlign = value;
  39018. },
  39019. enumerable: true,
  39020. configurable: true
  39021. });
  39022. Object.defineProperty(Text2D.prototype, "hAlign", {
  39023. get: function () {
  39024. return this._hAlign;
  39025. },
  39026. set: function (value) {
  39027. this._hAlign = value;
  39028. },
  39029. enumerable: true,
  39030. configurable: true
  39031. });
  39032. Object.defineProperty(Text2D.prototype, "actualSize", {
  39033. get: function () {
  39034. if (this.areaSize) {
  39035. return this.areaSize;
  39036. }
  39037. if (this._actualSize) {
  39038. return this._actualSize;
  39039. }
  39040. this._actualSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  39041. return this._actualSize;
  39042. },
  39043. enumerable: true,
  39044. configurable: true
  39045. });
  39046. Object.defineProperty(Text2D.prototype, "fontTexture", {
  39047. get: function () {
  39048. if (this._fontTexture) {
  39049. return this._fontTexture;
  39050. }
  39051. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName);
  39052. return this._fontTexture;
  39053. },
  39054. enumerable: true,
  39055. configurable: true
  39056. });
  39057. Text2D.prototype.dispose = function () {
  39058. if (!_super.prototype.dispose.call(this)) {
  39059. return false;
  39060. }
  39061. if (this._fontTexture) {
  39062. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName);
  39063. this._fontTexture = null;
  39064. }
  39065. return true;
  39066. };
  39067. Text2D.prototype.updateLevelBoundingInfo = function () {
  39068. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo, this.origin);
  39069. };
  39070. Text2D.prototype.setupText2D = function (owner, parent, id, position, fontName, text, areaSize, defaultFontColor, vAlign, hAlign, tabulationSize) {
  39071. this.setupRenderablePrim2D(owner, parent, id, position, true);
  39072. this.fontName = fontName;
  39073. this.defaultFontColor = defaultFontColor;
  39074. this.text = text;
  39075. this.areaSize = areaSize;
  39076. this.vAlign = vAlign;
  39077. this.hAlign = hAlign;
  39078. this._tabulationSize = tabulationSize;
  39079. this._isTransparent = true;
  39080. };
  39081. Text2D.Create = function (parent, id, x, y, fontName, text, defaultFontColor, areaSize, vAlign, hAlign, tabulationSize) {
  39082. if (vAlign === void 0) { vAlign = Text2D.TEXT2D_VALIGN_TOP; }
  39083. if (hAlign === void 0) { hAlign = Text2D.TEXT2D_HALIGN_LEFT; }
  39084. if (tabulationSize === void 0) { tabulationSize = 4; }
  39085. BABYLON.Prim2DBase.CheckParent(parent);
  39086. var text2d = new Text2D();
  39087. text2d.setupText2D(parent.owner, parent, id, new BABYLON.Vector2(x, y), fontName, text, areaSize, defaultFontColor || new BABYLON.Color4(0, 0, 0, 1), vAlign, hAlign, tabulationSize);
  39088. return text2d;
  39089. };
  39090. Text2D.prototype.levelIntersect = function (intersectInfo) {
  39091. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  39092. return true;
  39093. };
  39094. Text2D.prototype.createModelRenderCache = function (modelKey, isTransparent) {
  39095. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey, isTransparent);
  39096. return renderCache;
  39097. };
  39098. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  39099. var renderCache = modelRenderCache;
  39100. var engine = this.owner.engine;
  39101. renderCache.fontTexture = this.fontTexture;
  39102. var vb = new Float32Array(4);
  39103. for (var i = 0; i < 4; i++) {
  39104. vb[i] = i;
  39105. }
  39106. renderCache.vb = engine.createVertexBuffer(vb);
  39107. var ib = new Float32Array(6);
  39108. ib[0] = 0;
  39109. ib[1] = 2;
  39110. ib[2] = 1;
  39111. ib[3] = 0;
  39112. ib[4] = 3;
  39113. ib[5] = 2;
  39114. renderCache.ib = engine.createIndexBuffer(ib);
  39115. // Effects
  39116. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"]);
  39117. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  39118. return renderCache;
  39119. };
  39120. Text2D.prototype.createInstanceDataParts = function () {
  39121. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  39122. };
  39123. // Looks like a hack!? Yes! Because that's what it is!
  39124. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  39125. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  39126. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  39127. if (!this._charCount) {
  39128. var curText = this._text;
  39129. this.text = "A";
  39130. return curText;
  39131. }
  39132. };
  39133. // if obj contains something, we restore the _text property
  39134. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  39135. if (obj !== undefined) {
  39136. this.text = obj;
  39137. }
  39138. };
  39139. Text2D.prototype.refreshInstanceDataPart = function (part) {
  39140. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  39141. return false;
  39142. }
  39143. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  39144. var d = part;
  39145. var texture = this.fontTexture;
  39146. var ts = texture.getSize();
  39147. var textSize = texture.measureText(this.text, this._tabulationSize);
  39148. var offset = BABYLON.Vector2.Zero();
  39149. var charxpos = 0;
  39150. d.dataElementCount = this._charCount;
  39151. d.curElement = 0;
  39152. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  39153. var char = _a[_i];
  39154. // Line feed
  39155. if (char === "\n") {
  39156. offset.x = 0;
  39157. offset.y -= texture.lineHeight;
  39158. }
  39159. // Tabulation ?
  39160. if (char === "\t") {
  39161. var nextPos = charxpos + this._tabulationSize;
  39162. nextPos = nextPos - (nextPos % this._tabulationSize);
  39163. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  39164. charxpos = nextPos;
  39165. continue;
  39166. }
  39167. if (char < " ") {
  39168. continue;
  39169. }
  39170. this.updateInstanceDataPart(d, offset, textSize);
  39171. var ci = texture.getChar(char);
  39172. offset.x += ci.charWidth;
  39173. d.topLeftUV = ci.topLeftUV;
  39174. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  39175. d.sizeUV = suv;
  39176. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  39177. d.color = this.defaultFontColor;
  39178. ++d.curElement;
  39179. }
  39180. }
  39181. return true;
  39182. };
  39183. Text2D.prototype._updateCharCount = function () {
  39184. var count = 0;
  39185. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  39186. var char = _a[_i];
  39187. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  39188. continue;
  39189. }
  39190. ++count;
  39191. }
  39192. this._charCount = count;
  39193. };
  39194. Text2D.TEXT2D_MAINPARTID = 1;
  39195. Text2D.TEXT2D_VALIGN_TOP = 1;
  39196. Text2D.TEXT2D_VALIGN_CENTER = 2;
  39197. Text2D.TEXT2D_VALIGN_BOTTOM = 3;
  39198. Text2D.TEXT2D_HALIGN_LEFT = 1;
  39199. Text2D.TEXT2D_HALIGN_CENTER = 2;
  39200. Text2D.TEXT2D_HALIGN_RIGHT = 3;
  39201. __decorate([
  39202. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  39203. ], Text2D.prototype, "fontName", null);
  39204. __decorate([
  39205. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  39206. ], Text2D.prototype, "defaultFontColor", null);
  39207. __decorate([
  39208. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  39209. ], Text2D.prototype, "text", null);
  39210. __decorate([
  39211. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.areaSizeProperty = pi; })
  39212. ], Text2D.prototype, "areaSize", null);
  39213. __decorate([
  39214. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D.vAlignProperty = pi; })
  39215. ], Text2D.prototype, "vAlign", null);
  39216. __decorate([
  39217. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D.hAlignProperty = pi; })
  39218. ], Text2D.prototype, "hAlign", null);
  39219. Text2D = __decorate([
  39220. BABYLON.className("Text2D")
  39221. ], Text2D);
  39222. return Text2D;
  39223. })(BABYLON.RenderablePrim2D);
  39224. BABYLON.Text2D = Text2D;
  39225. })(BABYLON || (BABYLON = {}));
  39226. var BABYLON;
  39227. (function (BABYLON) {
  39228. var Canvas2DEngineBoundData = (function () {
  39229. function Canvas2DEngineBoundData() {
  39230. this._modelCache = new BABYLON.StringDictionary();
  39231. }
  39232. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  39233. return this._modelCache.getOrAddWithFactory(key, factory);
  39234. };
  39235. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  39236. if (!modelRenderCache.isDisposed) {
  39237. return false;
  39238. }
  39239. this._modelCache.remove(modelRenderCache.modelKey);
  39240. return true;
  39241. };
  39242. return Canvas2DEngineBoundData;
  39243. })();
  39244. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  39245. var Canvas2D = (function (_super) {
  39246. __extends(Canvas2D, _super);
  39247. function Canvas2D() {
  39248. _super.apply(this, arguments);
  39249. this._notifDebugMode = false;
  39250. this._mapCounter = 0;
  39251. }
  39252. /**
  39253. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the top/left corner of the screen.
  39254. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  39255. * All caching strategies will be available.
  39256. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  39257. * @param scene the Scene that owns the Canvas
  39258. * @param name the name of the Canvas, for information purpose only
  39259. * @param pos the position of the canvas, relative from the bottom/left of the scene's viewport
  39260. * @param size the Size of the canvas. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  39261. * @param cachingStrategy either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information.
  39262. */
  39263. Canvas2D.CreateScreenSpace = function (scene, name, pos, size, cachingStrategy, enableInteraction) {
  39264. if (cachingStrategy === void 0) { cachingStrategy = Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS; }
  39265. if (enableInteraction === void 0) { enableInteraction = true; }
  39266. var c = new Canvas2D();
  39267. c.setupCanvas(scene, name, size, true, cachingStrategy, enableInteraction);
  39268. c.position = pos;
  39269. c.origin = BABYLON.Vector2.Zero();
  39270. return c;
  39271. };
  39272. /**
  39273. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  39274. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  39275. * @param scene the Scene that owns the Canvas
  39276. * @param name the name of the Canvas, for information purpose only
  39277. * @param position the position of the Canvas in World Space
  39278. * @param rotation the rotation of the Canvas in World Space
  39279. * @param size the dimension of the Canvas in World Space
  39280. * @param renderScaleFactor A scale factor applied to create the rendering texture that will be mapped in the Scene Rectangle. If you set 2 for instance the texture will be twice large in width and height. A greater value will allow to achieve a better rendering quality.
  39281. * BE AWARE that the Canvas true dimension will be size*renderScaleFactor, then all coordinates and size will have to be express regarding this size.
  39282. * TIPS: if you want a renderScaleFactor independent reference of frame, create a child Group2D in the Canvas with position 0,0 and size set to null, then set its scale property to the same amount than the renderScaleFactor, put all your primitive inside using coordinates regarding the size property you pick for the Canvas and you'll be fine.
  39283. * @param sideOrientation Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one.
  39284. * @param cachingStrategy Must be CACHESTRATEGY_CANVAS for now
  39285. */
  39286. Canvas2D.CreateWorldSpace = function (scene, name, position, rotation, size, renderScaleFactor, sideOrientation, cachingStrategy, enableInteraction) {
  39287. if (renderScaleFactor === void 0) { renderScaleFactor = 1; }
  39288. if (cachingStrategy === void 0) { cachingStrategy = Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS; }
  39289. if (enableInteraction === void 0) { enableInteraction = true; }
  39290. if (cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  39291. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  39292. }
  39293. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  39294. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  39295. //}
  39296. if (!sideOrientation) {
  39297. sideOrientation = BABYLON.Mesh.DEFAULTSIDE;
  39298. }
  39299. var c = new Canvas2D();
  39300. c.setupCanvas(scene, name, new BABYLON.Size(size.width * renderScaleFactor, size.height * renderScaleFactor), false, cachingStrategy, enableInteraction);
  39301. var plane = new BABYLON.WorldSpaceCanvas2d(name, scene, c);
  39302. var vertexData = BABYLON.VertexData.CreatePlane({ width: size.width / 2, height: size.height / 2, sideOrientation: sideOrientation });
  39303. var mtl = new BABYLON.StandardMaterial(name + "_Material", scene);
  39304. c.applyCachedTexture(vertexData, mtl);
  39305. vertexData.applyToMesh(plane, false);
  39306. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  39307. mtl.disableLighting = true;
  39308. mtl.useAlphaFromDiffuseTexture = true;
  39309. plane.position = position;
  39310. plane.rotationQuaternion = rotation;
  39311. plane.material = mtl;
  39312. c._worldSpaceNode = plane;
  39313. return c;
  39314. };
  39315. Canvas2D.prototype.setupCanvas = function (scene, name, size, isScreenSpace, cachingstrategy, enableInteraction) {
  39316. var _this = this;
  39317. var engine = scene.getEngine();
  39318. this._fitRenderingDevice = !size;
  39319. if (!size) {
  39320. size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  39321. }
  39322. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  39323. this._cachingStrategy = cachingstrategy;
  39324. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  39325. this._capturedPointers = new BABYLON.StringDictionary();
  39326. this._pickStartingPosition = BABYLON.Vector2.Zero();
  39327. this.setupGroup2D(this, null, name, BABYLON.Vector2.Zero(), size, this._cachingStrategy === Canvas2D.CACHESTRATEGY_ALLGROUPS ? BABYLON.Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE : BABYLON.Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY);
  39328. this._hierarchyLevelMaxSiblingCount = 100;
  39329. this._hierarchyDepthOffset = 0;
  39330. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  39331. this._scene = scene;
  39332. this._engine = engine;
  39333. this._renderingSize = new BABYLON.Size(0, 0);
  39334. // Register scene dispose to also dispose the canvas when it'll happens
  39335. scene.onDisposeObservable.add(function (d, s) {
  39336. _this.dispose();
  39337. });
  39338. if (cachingstrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  39339. this._background = BABYLON.Rectangle2D.Create(this, "###CANVAS BACKGROUND###", 0, 0, size.width, size.height);
  39340. this._background.isPickable = false;
  39341. this._background.origin = BABYLON.Vector2.Zero();
  39342. this._background.levelVisible = false;
  39343. }
  39344. this._isScreeSpace = isScreenSpace;
  39345. if (this._isScreeSpace) {
  39346. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  39347. _this._engine.clear(null, false, true);
  39348. _this._render();
  39349. });
  39350. }
  39351. else {
  39352. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  39353. _this._render();
  39354. });
  39355. }
  39356. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  39357. // this._supprtInstancedArray = false; // TODO REMOVE!!!
  39358. this._setupInteraction(enableInteraction);
  39359. };
  39360. Object.defineProperty(Canvas2D.prototype, "hierarchyLevelMaxSiblingCount", {
  39361. get: function () {
  39362. return this._hierarchyLevelMaxSiblingCount;
  39363. },
  39364. enumerable: true,
  39365. configurable: true
  39366. });
  39367. Canvas2D.prototype._setupInteraction = function (enable) {
  39368. var _this = this;
  39369. // No change detection
  39370. if (enable === this._interactionEnabled) {
  39371. return;
  39372. }
  39373. // Set the new state
  39374. this._interactionEnabled = enable;
  39375. // Disable interaction
  39376. if (!enable) {
  39377. if (this._scenePrePointerObserver) {
  39378. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  39379. this._scenePrePointerObserver = null;
  39380. }
  39381. return;
  39382. }
  39383. // Enable Interaction
  39384. // Register the observable
  39385. this.scene.onPrePointerObservable.add(function (e, s) { return _this._handlePointerEventForInteraction(e, s); });
  39386. };
  39387. /**
  39388. * Internal method, you should use the Prim2DBase version instead
  39389. */
  39390. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  39391. if (this.isPointerCaptured(pointerId)) {
  39392. return false;
  39393. }
  39394. // Try to capture the pointer on the HTML side
  39395. try {
  39396. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  39397. }
  39398. catch (e) {
  39399. }
  39400. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  39401. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  39402. this._capturedPointers.add(pointerId.toString(), primitive);
  39403. return true;
  39404. };
  39405. /**
  39406. * Internal method, you should use the Prim2DBase version instead
  39407. */
  39408. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  39409. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  39410. return false;
  39411. }
  39412. // Try to release the pointer on the HTML side
  39413. try {
  39414. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  39415. }
  39416. catch (e) {
  39417. }
  39418. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  39419. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  39420. this._capturedPointers.remove(pointerId.toString());
  39421. return true;
  39422. };
  39423. /**
  39424. * Determine if the given pointer is captured or not
  39425. * @param pointerId the Id of the pointer
  39426. * @return true if it's captured, false otherwise
  39427. */
  39428. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  39429. return this._capturedPointers.contains(pointerId.toString());
  39430. };
  39431. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  39432. // Avoid unnecessary lookup
  39433. if (this._capturedPointers.count === 0) {
  39434. return null;
  39435. }
  39436. return this._capturedPointers.get(pointerId.toString());
  39437. };
  39438. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, eventState) {
  39439. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  39440. this._updatePointerInfo(eventData);
  39441. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  39442. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  39443. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  39444. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  39445. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  39446. this._updateOverStatus();
  39447. // Check if we have nothing to raise
  39448. if (!this._actualOverPrimitive && !capturedPrim) {
  39449. return;
  39450. }
  39451. // Update the relatedTarget info with the over primitive or the captured one (if any)
  39452. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  39453. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  39454. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  39455. // Analyze the pointer event type and fire proper events on the primitive
  39456. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  39457. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  39458. }
  39459. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39460. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  39461. }
  39462. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  39463. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  39464. }
  39465. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  39466. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  39467. }
  39468. };
  39469. Canvas2D.prototype._updatePointerInfo = function (eventData) {
  39470. var pii = this._primPointerInfo;
  39471. if (!pii.canvasPointerPos) {
  39472. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  39473. }
  39474. pii.canvasPointerPos.x = eventData.localPosition.x - this.position.x;
  39475. pii.canvasPointerPos.y = (this.engine.getRenderHeight() - eventData.localPosition.y) - this.position.y;
  39476. pii.mouseWheelDelta = 0;
  39477. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  39478. var event = eventData.event;
  39479. if (event.wheelDelta) {
  39480. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  39481. }
  39482. else if (event.detail) {
  39483. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  39484. }
  39485. }
  39486. else {
  39487. var pe = eventData.event;
  39488. pii.ctrlKey = pe.ctrlKey;
  39489. pii.altKey = pe.altKey;
  39490. pii.shiftKey = pe.shiftKey;
  39491. pii.metaKey = pe.metaKey;
  39492. pii.button = pe.button;
  39493. pii.buttons = pe.buttons;
  39494. pii.pointerId = pe.pointerId;
  39495. pii.width = pe.width;
  39496. pii.height = pe.height;
  39497. pii.presssure = pe.pressure;
  39498. pii.tilt.x = pe.tiltX;
  39499. pii.tilt.y = pe.tiltY;
  39500. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  39501. }
  39502. };
  39503. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  39504. if (this.scene.getRenderId() === this._intersectionRenderId) {
  39505. return;
  39506. }
  39507. var ii = Canvas2D._interInfo;
  39508. ii.pickPosition.x = mouseLocalPos.x;
  39509. ii.pickPosition.y = mouseLocalPos.y;
  39510. ii.findFirstOnly = false;
  39511. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  39512. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  39513. this._previousIntersectionList = this._actualIntersectionList;
  39514. this._actualIntersectionList = null;
  39515. this._previousOverPrimitive = this._actualOverPrimitive;
  39516. this._actualOverPrimitive = null;
  39517. return;
  39518. }
  39519. this._updateCanvasState();
  39520. this.intersect(ii);
  39521. this._previousIntersectionList = this._actualIntersectionList;
  39522. this._actualIntersectionList = ii.intersectedPrimitives;
  39523. this._previousOverPrimitive = this._actualOverPrimitive;
  39524. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  39525. this._intersectionRenderId = this.scene.getRenderId();
  39526. };
  39527. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  39528. Canvas2D.prototype._updateOverStatus = function () {
  39529. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  39530. return;
  39531. }
  39532. // Detect a change of over
  39533. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  39534. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  39535. if (prevPrim !== actualPrim) {
  39536. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  39537. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  39538. // Notify the previous "over" prim that the pointer is no longer over it
  39539. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  39540. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  39541. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  39542. }
  39543. // Notify the new "over" prim that the pointer is over it
  39544. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  39545. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  39546. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  39547. }
  39548. }
  39549. this._hoverStatusRenderId = this.scene.getRenderId();
  39550. };
  39551. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  39552. if (this._primPointerInfo.isCaptured) {
  39553. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  39554. }
  39555. else {
  39556. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  39557. var pii = _a[_i];
  39558. if (pii.prim === prim) {
  39559. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  39560. return;
  39561. }
  39562. }
  39563. }
  39564. };
  39565. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  39566. if (!this._notifDebugMode) {
  39567. return;
  39568. }
  39569. var debug = "";
  39570. for (var i = 0; i < prim.hierarchyDepth; i++) {
  39571. debug += " ";
  39572. }
  39573. var pii = this._primPointerInfo;
  39574. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  39575. console.log(debug);
  39576. };
  39577. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  39578. var ppi = this._primPointerInfo;
  39579. // In case of PointerOver/Out we will first notify the children (but the deepest to the closest) with PointerEnter/Leave
  39580. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  39581. this._notifChildren(prim, mask);
  39582. }
  39583. var bubbleCancelled = false;
  39584. var cur = prim;
  39585. while (cur) {
  39586. // Only trigger the observers if the primitive is intersected (except for out)
  39587. if (!bubbleCancelled) {
  39588. this._updatePrimPointerPos(cur);
  39589. // Exec the observers
  39590. this._debugExecObserver(cur, mask);
  39591. cur._pointerEventObservable.notifyObservers(ppi, mask);
  39592. this._triggerActionManager(cur, ppi, mask, eventData);
  39593. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  39594. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  39595. if (ppi.cancelBubble) {
  39596. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  39597. return;
  39598. }
  39599. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  39600. bubbleCancelled = true;
  39601. }
  39602. }
  39603. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  39604. if (bubbleCancelled) {
  39605. this._updatePrimPointerPos(cur);
  39606. }
  39607. // Trigger a PointerEnter corresponding to the PointerOver
  39608. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  39609. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  39610. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  39611. }
  39612. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  39613. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  39614. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  39615. }
  39616. // Loop to the parent
  39617. cur = cur.parent;
  39618. }
  39619. };
  39620. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  39621. var _this = this;
  39622. // Process Trigger related to PointerDown
  39623. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  39624. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  39625. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  39626. this._pickStartingTime = new Date().getTime();
  39627. this._pickedDownPrim = null;
  39628. if (prim.actionManager) {
  39629. this._pickedDownPrim = prim;
  39630. if (prim.actionManager.hasPickTriggers) {
  39631. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  39632. switch (eventData.button) {
  39633. case 0:
  39634. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  39635. break;
  39636. case 1:
  39637. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  39638. break;
  39639. case 2:
  39640. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  39641. break;
  39642. }
  39643. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  39644. }
  39645. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  39646. window.setTimeout(function () {
  39647. var ppi = _this._primPointerInfo;
  39648. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  39649. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  39650. var ii = new BABYLON.IntersectInfo2D();
  39651. ii.pickPosition = ppi.canvasPointerPos.clone();
  39652. ii.findFirstOnly = false;
  39653. _this.intersect(ii);
  39654. if (ii.isPrimIntersected(prim) !== null) {
  39655. if (prim.actionManager) {
  39656. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  39657. _this._pickStartingTime = 0;
  39658. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  39659. }
  39660. }
  39661. }
  39662. }, BABYLON.ActionManager.LongPressDelay);
  39663. }
  39664. }
  39665. }
  39666. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  39667. this._pickStartingTime = 0;
  39668. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  39669. if (prim.actionManager) {
  39670. // OnPickUpTrigger
  39671. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  39672. // OnPickTrigger
  39673. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  39674. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  39675. }
  39676. }
  39677. // OnPickOutTrigger
  39678. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  39679. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  39680. }
  39681. }
  39682. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  39683. if (prim.actionManager) {
  39684. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  39685. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  39686. }
  39687. }
  39688. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  39689. if (prim.actionManager) {
  39690. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  39691. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  39692. }
  39693. }
  39694. };
  39695. Canvas2D.prototype._notifChildren = function (prim, mask) {
  39696. var _this = this;
  39697. var pii = this._primPointerInfo;
  39698. prim.children.forEach(function (curChild) {
  39699. // Recurse first, we want the deepest to be notified first
  39700. _this._notifChildren(curChild, mask);
  39701. _this._updatePrimPointerPos(curChild);
  39702. // Fire the proper notification
  39703. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  39704. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerEnter);
  39705. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  39706. }
  39707. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  39708. _this._debugExecObserver(curChild, BABYLON.PrimitivePointerInfo.PointerLeave);
  39709. curChild._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  39710. }
  39711. });
  39712. };
  39713. /**
  39714. * Don't forget to call the dispose method when you're done with the Canvas instance.
  39715. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  39716. */
  39717. Canvas2D.prototype.dispose = function () {
  39718. if (!_super.prototype.dispose.call(this)) {
  39719. return false;
  39720. }
  39721. if (this.interactionEnabled) {
  39722. this._setupInteraction(false);
  39723. }
  39724. if (this._beforeRenderObserver) {
  39725. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  39726. this._beforeRenderObserver = null;
  39727. }
  39728. if (this._afterRenderObserver) {
  39729. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  39730. this._afterRenderObserver = null;
  39731. }
  39732. if (this._groupCacheMaps) {
  39733. this._groupCacheMaps.forEach(function (m) { return m.dispose(); });
  39734. this._groupCacheMaps = null;
  39735. }
  39736. };
  39737. Object.defineProperty(Canvas2D.prototype, "scene", {
  39738. /**
  39739. * Accessor to the Scene that owns the Canvas
  39740. * @returns The instance of the Scene object
  39741. */
  39742. get: function () {
  39743. return this._scene;
  39744. },
  39745. enumerable: true,
  39746. configurable: true
  39747. });
  39748. Object.defineProperty(Canvas2D.prototype, "engine", {
  39749. /**
  39750. * Accessor to the Engine that drives the Scene used by this Canvas
  39751. * @returns The instance of the Engine object
  39752. */
  39753. get: function () {
  39754. return this._engine;
  39755. },
  39756. enumerable: true,
  39757. configurable: true
  39758. });
  39759. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  39760. /**
  39761. * Accessor of the Caching Strategy used by this Canvas.
  39762. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  39763. * @returns the value corresponding to the used strategy.
  39764. */
  39765. get: function () {
  39766. return this._cachingStrategy;
  39767. },
  39768. enumerable: true,
  39769. configurable: true
  39770. });
  39771. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  39772. /**
  39773. * Only valid for World Space Canvas, returns the scene node that display the canvas
  39774. */
  39775. get: function () {
  39776. return this._worldSpaceNode;
  39777. },
  39778. enumerable: true,
  39779. configurable: true
  39780. });
  39781. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  39782. /**
  39783. * Check if the WebGL Instanced Array extension is supported or not
  39784. * @returns {}
  39785. */
  39786. get: function () {
  39787. return this._supprtInstancedArray;
  39788. },
  39789. enumerable: true,
  39790. configurable: true
  39791. });
  39792. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  39793. /**
  39794. * Property that defines the fill object used to draw the background of the Canvas.
  39795. * Note that Canvas with a Caching Strategy of
  39796. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  39797. */
  39798. get: function () {
  39799. if (!this._background || !this._background.isVisible) {
  39800. return null;
  39801. }
  39802. return this._background.fill;
  39803. },
  39804. set: function (value) {
  39805. this.checkBackgroundAvailability();
  39806. if (value === this._background.fill) {
  39807. return;
  39808. }
  39809. this._background.fill = value;
  39810. this._background.levelVisible = true;
  39811. },
  39812. enumerable: true,
  39813. configurable: true
  39814. });
  39815. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  39816. /**
  39817. * Property that defines the border object used to draw the background of the Canvas.
  39818. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  39819. */
  39820. get: function () {
  39821. if (!this._background || !this._background.isVisible) {
  39822. return null;
  39823. }
  39824. return this._background.border;
  39825. },
  39826. set: function (value) {
  39827. this.checkBackgroundAvailability();
  39828. if (value === this._background.border) {
  39829. return;
  39830. }
  39831. this._background.border = value;
  39832. this._background.levelVisible = true;
  39833. },
  39834. enumerable: true,
  39835. configurable: true
  39836. });
  39837. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  39838. /**
  39839. * You can set the roundRadius of the background
  39840. * @returns The current roundRadius
  39841. */
  39842. get: function () {
  39843. if (!this._background || !this._background.isVisible) {
  39844. return null;
  39845. }
  39846. return this._background.roundRadius;
  39847. },
  39848. set: function (value) {
  39849. this.checkBackgroundAvailability();
  39850. if (value === this._background.roundRadius) {
  39851. return;
  39852. }
  39853. this._background.roundRadius = value;
  39854. this._background.levelVisible = true;
  39855. },
  39856. enumerable: true,
  39857. configurable: true
  39858. });
  39859. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  39860. /**
  39861. * Enable/Disable interaction for this Canvas
  39862. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  39863. */
  39864. get: function () {
  39865. return this._interactionEnabled;
  39866. },
  39867. set: function (enable) {
  39868. this._setupInteraction(enable);
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  39874. get: function () {
  39875. return this.__engineData;
  39876. },
  39877. enumerable: true,
  39878. configurable: true
  39879. });
  39880. Canvas2D.prototype.checkBackgroundAvailability = function () {
  39881. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  39882. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  39883. }
  39884. };
  39885. Canvas2D.prototype._updateCanvasState = function () {
  39886. // Check if the update has already been made for this render Frame
  39887. if (this.scene.getRenderId() === this._updateRenderId) {
  39888. return;
  39889. }
  39890. this._renderingSize.width = this.engine.getRenderWidth();
  39891. this._renderingSize.height = this.engine.getRenderHeight();
  39892. if (this._fitRenderingDevice) {
  39893. this.size = this._renderingSize;
  39894. if (this._background) {
  39895. this._background.size = this.size;
  39896. }
  39897. }
  39898. var context = new BABYLON.Render2DContext();
  39899. context.forceRefreshPrimitive = false;
  39900. ++this._globalTransformProcessStep;
  39901. this.updateGlobalTransVis(false);
  39902. this._prepareGroupRender(context);
  39903. this._updateRenderId = this.scene.getRenderId();
  39904. };
  39905. /**
  39906. * Method that renders the Canvas, you should not invoke
  39907. */
  39908. Canvas2D.prototype._render = function () {
  39909. this._updateCanvasState();
  39910. if (this._primPointerInfo.canvasPointerPos) {
  39911. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  39912. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  39913. }
  39914. var context = new BABYLON.Render2DContext();
  39915. this._groupRender(context);
  39916. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  39917. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  39918. this._cachedCanvasGroup._renderCachedCanvas(context);
  39919. }
  39920. };
  39921. /**
  39922. * Internal method that allocate a cache for the given group.
  39923. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  39924. * @param group The group to allocate the cache of.
  39925. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  39926. */
  39927. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize) {
  39928. // Determine size
  39929. var size = group.actualSize;
  39930. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  39931. if (minSize) {
  39932. size.width = Math.max(minSize.width, size.width);
  39933. size.height = Math.max(minSize.height, size.height);
  39934. }
  39935. if (!this._groupCacheMaps) {
  39936. this._groupCacheMaps = new Array();
  39937. }
  39938. // Try to find a spot in one of the cached texture
  39939. var res = null;
  39940. for (var _i = 0, _a = this._groupCacheMaps; _i < _a.length; _i++) {
  39941. var map = _a[_i];
  39942. var node = map.allocateRect(size);
  39943. if (node) {
  39944. res = { node: node, texture: map };
  39945. break;
  39946. }
  39947. }
  39948. // Couldn't find a map that could fit the rect, create a new map for it
  39949. if (!res) {
  39950. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  39951. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  39952. if (size.width > mapSize.width || size.height > mapSize.height) {
  39953. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  39954. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  39955. }
  39956. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  39957. map = new BABYLON.MapTexture(id, this._scene, mapSize);
  39958. this._groupCacheMaps.push(map);
  39959. var node = map.allocateRect(size);
  39960. res = { node: node, texture: map };
  39961. }
  39962. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  39963. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  39964. if (group !== this || this._isScreeSpace) {
  39965. var node = res.node;
  39966. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  39967. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  39968. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  39969. var sprite = BABYLON.Sprite2D.Create(this._cachedCanvasGroup, "__cachedCanvasSprite__", 0, 0, map, node.contentSize, node.pos);
  39970. sprite.zOrder = 1;
  39971. sprite.origin = BABYLON.Vector2.Zero();
  39972. }
  39973. else {
  39974. var sprite = BABYLON.Sprite2D.Create(parent, "__cachedSpriteOfGroup__" + group.id, group.position.x, group.position.y, map, node.contentSize, node.pos, false);
  39975. sprite.origin = group.origin.clone();
  39976. res.sprite = sprite;
  39977. }
  39978. }
  39979. return res;
  39980. };
  39981. /**
  39982. * Get a Solid Color Brush instance matching the given color.
  39983. * @param color The color to retrieve
  39984. * @return A shared instance of the SolidColorBrush2D class that use the given color
  39985. */
  39986. Canvas2D.GetSolidColorBrush = function (color) {
  39987. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  39988. };
  39989. /**
  39990. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  39991. * @param color The color to retrieve
  39992. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  39993. */
  39994. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  39995. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  39996. };
  39997. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  39998. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  39999. if (rotation === void 0) { rotation = 0; }
  40000. if (scale === void 0) { scale = 1; }
  40001. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  40002. };
  40003. /**
  40004. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  40005. * This strategy doesn't allow primitives added directly as children of the Canvas.
  40006. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  40007. */
  40008. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  40009. /**
  40010. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  40011. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  40012. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  40013. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  40014. */
  40015. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  40016. /**
  40017. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  40018. */
  40019. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  40020. /**
  40021. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  40022. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  40023. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  40024. */
  40025. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  40026. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  40027. /**
  40028. * Define the default size used for both the width and height of a MapTexture to allocate.
  40029. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  40030. */
  40031. Canvas2D._groupTextureCacheSize = 1024;
  40032. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  40033. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  40034. Canvas2D = __decorate([
  40035. BABYLON.className("Canvas2D")
  40036. ], Canvas2D);
  40037. return Canvas2D;
  40038. })(BABYLON.Group2D);
  40039. BABYLON.Canvas2D = Canvas2D;
  40040. })(BABYLON || (BABYLON = {}));
  40041. var BABYLON;
  40042. (function (BABYLON) {
  40043. /**
  40044. * This is the class that is used to display a World Space Canvas into a scene
  40045. */
  40046. var WorldSpaceCanvas2d = (function (_super) {
  40047. __extends(WorldSpaceCanvas2d, _super);
  40048. function WorldSpaceCanvas2d(name, scene, canvas) {
  40049. _super.call(this, name, scene);
  40050. this._canvas = canvas;
  40051. }
  40052. WorldSpaceCanvas2d.prototype.dispose = function () {
  40053. _super.prototype.dispose.call(this);
  40054. if (this._canvas) {
  40055. this._canvas.dispose();
  40056. this._canvas = null;
  40057. }
  40058. };
  40059. return WorldSpaceCanvas2d;
  40060. })(BABYLON.Mesh);
  40061. BABYLON.WorldSpaceCanvas2d = WorldSpaceCanvas2d;
  40062. })(BABYLON || (BABYLON = {}));
  40063. var BABYLON;
  40064. (function (BABYLON) {
  40065. var ShaderMaterial = (function (_super) {
  40066. __extends(ShaderMaterial, _super);
  40067. function ShaderMaterial(name, scene, shaderPath, options) {
  40068. _super.call(this, name, scene);
  40069. this._textures = {};
  40070. this._floats = {};
  40071. this._floatsArrays = {};
  40072. this._colors3 = {};
  40073. this._colors4 = {};
  40074. this._vectors2 = {};
  40075. this._vectors3 = {};
  40076. this._vectors4 = {};
  40077. this._matrices = {};
  40078. this._matrices3x3 = {};
  40079. this._matrices2x2 = {};
  40080. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40081. this._shaderPath = shaderPath;
  40082. options.needAlphaBlending = options.needAlphaBlending || false;
  40083. options.needAlphaTesting = options.needAlphaTesting || false;
  40084. options.attributes = options.attributes || ["position", "normal", "uv"];
  40085. options.uniforms = options.uniforms || ["worldViewProjection"];
  40086. options.samplers = options.samplers || [];
  40087. options.defines = options.defines || [];
  40088. this._options = options;
  40089. }
  40090. ShaderMaterial.prototype.needAlphaBlending = function () {
  40091. return this._options.needAlphaBlending;
  40092. };
  40093. ShaderMaterial.prototype.needAlphaTesting = function () {
  40094. return this._options.needAlphaTesting;
  40095. };
  40096. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40097. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40098. this._options.uniforms.push(uniformName);
  40099. }
  40100. };
  40101. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40102. if (this._options.samplers.indexOf(name) === -1) {
  40103. this._options.samplers.push(name);
  40104. }
  40105. this._textures[name] = texture;
  40106. return this;
  40107. };
  40108. ShaderMaterial.prototype.setFloat = function (name, value) {
  40109. this._checkUniform(name);
  40110. this._floats[name] = value;
  40111. return this;
  40112. };
  40113. ShaderMaterial.prototype.setFloats = function (name, value) {
  40114. this._checkUniform(name);
  40115. this._floatsArrays[name] = value;
  40116. return this;
  40117. };
  40118. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40119. this._checkUniform(name);
  40120. this._colors3[name] = value;
  40121. return this;
  40122. };
  40123. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40124. this._checkUniform(name);
  40125. this._colors4[name] = value;
  40126. return this;
  40127. };
  40128. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40129. this._checkUniform(name);
  40130. this._vectors2[name] = value;
  40131. return this;
  40132. };
  40133. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40134. this._checkUniform(name);
  40135. this._vectors3[name] = value;
  40136. return this;
  40137. };
  40138. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40139. this._checkUniform(name);
  40140. this._vectors4[name] = value;
  40141. return this;
  40142. };
  40143. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40144. this._checkUniform(name);
  40145. this._matrices[name] = value;
  40146. return this;
  40147. };
  40148. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40149. this._checkUniform(name);
  40150. this._matrices3x3[name] = value;
  40151. return this;
  40152. };
  40153. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40154. this._checkUniform(name);
  40155. this._matrices2x2[name] = value;
  40156. return this;
  40157. };
  40158. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40159. var scene = this.getScene();
  40160. var engine = scene.getEngine();
  40161. if (!this.checkReadyOnEveryCall) {
  40162. if (this._renderId === scene.getRenderId()) {
  40163. return true;
  40164. }
  40165. }
  40166. // Instances
  40167. var defines = [];
  40168. var fallbacks = new BABYLON.EffectFallbacks();
  40169. if (useInstances) {
  40170. defines.push("#define INSTANCES");
  40171. }
  40172. for (var index = 0; index < this._options.defines.length; index++) {
  40173. defines.push(this._options.defines[index]);
  40174. }
  40175. // Bones
  40176. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40177. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40178. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40179. fallbacks.addCPUSkinningFallback(0, mesh);
  40180. }
  40181. // Alpha test
  40182. if (engine.getAlphaTesting()) {
  40183. defines.push("#define ALPHATEST");
  40184. }
  40185. var previousEffect = this._effect;
  40186. var join = defines.join("\n");
  40187. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40188. if (!this._effect.isReady()) {
  40189. return false;
  40190. }
  40191. if (previousEffect !== this._effect) {
  40192. scene.resetCachedMaterial();
  40193. }
  40194. this._renderId = scene.getRenderId();
  40195. return true;
  40196. };
  40197. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40198. var scene = this.getScene();
  40199. if (this._options.uniforms.indexOf("world") !== -1) {
  40200. this._effect.setMatrix("world", world);
  40201. }
  40202. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40203. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40204. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40205. }
  40206. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40207. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40208. }
  40209. };
  40210. ShaderMaterial.prototype.bind = function (world, mesh) {
  40211. // Std values
  40212. this.bindOnlyWorldMatrix(world);
  40213. if (this.getScene().getCachedMaterial() !== this) {
  40214. if (this._options.uniforms.indexOf("view") !== -1) {
  40215. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40216. }
  40217. if (this._options.uniforms.indexOf("projection") !== -1) {
  40218. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40219. }
  40220. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40221. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40222. }
  40223. // Bones
  40224. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40225. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40226. }
  40227. // Texture
  40228. for (var name in this._textures) {
  40229. this._effect.setTexture(name, this._textures[name]);
  40230. }
  40231. // Float
  40232. for (name in this._floats) {
  40233. this._effect.setFloat(name, this._floats[name]);
  40234. }
  40235. // Float s
  40236. for (name in this._floatsArrays) {
  40237. this._effect.setArray(name, this._floatsArrays[name]);
  40238. }
  40239. // Color3
  40240. for (name in this._colors3) {
  40241. this._effect.setColor3(name, this._colors3[name]);
  40242. }
  40243. // Color4
  40244. for (name in this._colors4) {
  40245. var color = this._colors4[name];
  40246. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40247. }
  40248. // Vector2
  40249. for (name in this._vectors2) {
  40250. this._effect.setVector2(name, this._vectors2[name]);
  40251. }
  40252. // Vector3
  40253. for (name in this._vectors3) {
  40254. this._effect.setVector3(name, this._vectors3[name]);
  40255. }
  40256. // Vector4
  40257. for (name in this._vectors4) {
  40258. this._effect.setVector4(name, this._vectors4[name]);
  40259. }
  40260. // Matrix
  40261. for (name in this._matrices) {
  40262. this._effect.setMatrix(name, this._matrices[name]);
  40263. }
  40264. // Matrix 3x3
  40265. for (name in this._matrices3x3) {
  40266. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40267. }
  40268. // Matrix 2x2
  40269. for (name in this._matrices2x2) {
  40270. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40271. }
  40272. }
  40273. _super.prototype.bind.call(this, world, mesh);
  40274. };
  40275. ShaderMaterial.prototype.clone = function (name) {
  40276. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40277. return newShaderMaterial;
  40278. };
  40279. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40280. if (forceDisposeTextures) {
  40281. for (var name in this._textures) {
  40282. this._textures[name].dispose();
  40283. }
  40284. }
  40285. this._textures = {};
  40286. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40287. };
  40288. ShaderMaterial.prototype.serialize = function () {
  40289. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40290. serializationObject.customType = "BABYLON.ShaderMaterial";
  40291. serializationObject.options = this._options;
  40292. serializationObject.shaderPath = this._shaderPath;
  40293. // Texture
  40294. serializationObject.textures = {};
  40295. for (var name in this._textures) {
  40296. serializationObject.textures[name] = this._textures[name].serialize();
  40297. }
  40298. // Float
  40299. serializationObject.floats = {};
  40300. for (name in this._floats) {
  40301. serializationObject.floats[name] = this._floats[name];
  40302. }
  40303. // Float s
  40304. serializationObject.floatArrays = {};
  40305. for (name in this._floatsArrays) {
  40306. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40307. }
  40308. // Color3
  40309. serializationObject.colors3 = {};
  40310. for (name in this._colors3) {
  40311. serializationObject.colors3[name] = this._colors3[name].asArray();
  40312. }
  40313. // Color4
  40314. serializationObject.colors4 = {};
  40315. for (name in this._colors4) {
  40316. serializationObject.colors4[name] = this._colors4[name].asArray();
  40317. }
  40318. // Vector2
  40319. serializationObject.vectors2 = {};
  40320. for (name in this._vectors2) {
  40321. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40322. }
  40323. // Vector3
  40324. serializationObject.vectors3 = {};
  40325. for (name in this._vectors3) {
  40326. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40327. }
  40328. // Vector4
  40329. serializationObject.vectors4 = {};
  40330. for (name in this._vectors4) {
  40331. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40332. }
  40333. // Matrix
  40334. serializationObject.matrices = {};
  40335. for (name in this._matrices) {
  40336. serializationObject.matrices[name] = this._matrices[name].asArray();
  40337. }
  40338. // Matrix 3x3
  40339. serializationObject.matrices3x3 = {};
  40340. for (name in this._matrices3x3) {
  40341. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40342. }
  40343. // Matrix 2x2
  40344. serializationObject.matrices2x2 = {};
  40345. for (name in this._matrices2x2) {
  40346. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40347. }
  40348. return serializationObject;
  40349. };
  40350. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40351. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40352. // Texture
  40353. for (var name in source.textures) {
  40354. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40355. }
  40356. // Float
  40357. for (name in source.floats) {
  40358. material.setFloat(name, source.floats[name]);
  40359. }
  40360. // Float s
  40361. for (name in source.floatsArrays) {
  40362. material.setFloats(name, source.floatsArrays[name]);
  40363. }
  40364. // Color3
  40365. for (name in source.colors3) {
  40366. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40367. }
  40368. // Color4
  40369. for (name in source.colors4) {
  40370. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40371. }
  40372. // Vector2
  40373. for (name in source.vectors2) {
  40374. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40375. }
  40376. // Vector3
  40377. for (name in source.vectors3) {
  40378. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40379. }
  40380. // Vector4
  40381. for (name in source.vectors4) {
  40382. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40383. }
  40384. // Matrix
  40385. for (name in source.matrices) {
  40386. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40387. }
  40388. // Matrix 3x3
  40389. for (name in source.matrices3x3) {
  40390. material.setMatrix3x3(name, source.matrices3x3[name]);
  40391. }
  40392. // Matrix 2x2
  40393. for (name in source.matrices2x2) {
  40394. material.setMatrix2x2(name, source.matrices2x2[name]);
  40395. }
  40396. return material;
  40397. };
  40398. return ShaderMaterial;
  40399. })(BABYLON.Material);
  40400. BABYLON.ShaderMaterial = ShaderMaterial;
  40401. })(BABYLON || (BABYLON = {}));
  40402. var BABYLON;
  40403. (function (BABYLON) {
  40404. var Internals;
  40405. (function (Internals) {
  40406. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40407. // All values and structures referenced from:
  40408. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40409. var DDS_MAGIC = 0x20534444;
  40410. 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;
  40411. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40412. 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;
  40413. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40414. function FourCCToInt32(value) {
  40415. return value.charCodeAt(0) +
  40416. (value.charCodeAt(1) << 8) +
  40417. (value.charCodeAt(2) << 16) +
  40418. (value.charCodeAt(3) << 24);
  40419. }
  40420. function Int32ToFourCC(value) {
  40421. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40422. }
  40423. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40424. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40425. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40426. var headerLengthInt = 31; // The header length in 32 bit ints
  40427. // Offsets into the header array
  40428. var off_magic = 0;
  40429. var off_size = 1;
  40430. var off_flags = 2;
  40431. var off_height = 3;
  40432. var off_width = 4;
  40433. var off_mipmapCount = 7;
  40434. var off_pfFlags = 20;
  40435. var off_pfFourCC = 21;
  40436. var off_RGBbpp = 22;
  40437. var off_RMask = 23;
  40438. var off_GMask = 24;
  40439. var off_BMask = 25;
  40440. var off_AMask = 26;
  40441. var off_caps1 = 27;
  40442. var off_caps2 = 28;
  40443. ;
  40444. var DDSTools = (function () {
  40445. function DDSTools() {
  40446. }
  40447. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40448. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40449. var mipmapCount = 1;
  40450. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40451. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40452. }
  40453. return {
  40454. width: header[off_width],
  40455. height: header[off_height],
  40456. mipmapCount: mipmapCount,
  40457. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40458. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40459. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40460. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40461. };
  40462. };
  40463. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40464. var byteArray = new Uint8Array(dataLength);
  40465. var srcData = new Uint8Array(arrayBuffer);
  40466. var index = 0;
  40467. for (var y = height - 1; y >= 0; y--) {
  40468. for (var x = 0; x < width; x++) {
  40469. var srcPos = dataOffset + (x + y * width) * 4;
  40470. byteArray[index + 2] = srcData[srcPos];
  40471. byteArray[index + 1] = srcData[srcPos + 1];
  40472. byteArray[index] = srcData[srcPos + 2];
  40473. byteArray[index + 3] = srcData[srcPos + 3];
  40474. index += 4;
  40475. }
  40476. }
  40477. return byteArray;
  40478. };
  40479. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40480. var byteArray = new Uint8Array(dataLength);
  40481. var srcData = new Uint8Array(arrayBuffer);
  40482. var index = 0;
  40483. for (var y = height - 1; y >= 0; y--) {
  40484. for (var x = 0; x < width; x++) {
  40485. var srcPos = dataOffset + (x + y * width) * 3;
  40486. byteArray[index + 2] = srcData[srcPos];
  40487. byteArray[index + 1] = srcData[srcPos + 1];
  40488. byteArray[index] = srcData[srcPos + 2];
  40489. index += 3;
  40490. }
  40491. }
  40492. return byteArray;
  40493. };
  40494. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40495. var byteArray = new Uint8Array(dataLength);
  40496. var srcData = new Uint8Array(arrayBuffer);
  40497. var index = 0;
  40498. for (var y = height - 1; y >= 0; y--) {
  40499. for (var x = 0; x < width; x++) {
  40500. var srcPos = dataOffset + (x + y * width);
  40501. byteArray[index] = srcData[srcPos];
  40502. index++;
  40503. }
  40504. }
  40505. return byteArray;
  40506. };
  40507. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40508. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40509. if (header[off_magic] != DDS_MAGIC) {
  40510. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40511. return;
  40512. }
  40513. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40514. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40515. return;
  40516. }
  40517. if (info.isFourCC) {
  40518. fourCC = header[off_pfFourCC];
  40519. switch (fourCC) {
  40520. case FOURCC_DXT1:
  40521. blockBytes = 8;
  40522. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40523. break;
  40524. case FOURCC_DXT3:
  40525. blockBytes = 16;
  40526. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40527. break;
  40528. case FOURCC_DXT5:
  40529. blockBytes = 16;
  40530. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40531. break;
  40532. default:
  40533. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40534. return;
  40535. }
  40536. }
  40537. mipmapCount = 1;
  40538. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40539. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40540. }
  40541. var bpp = header[off_RGBbpp];
  40542. for (var face = 0; face < faces; face++) {
  40543. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40544. width = header[off_width];
  40545. height = header[off_height];
  40546. dataOffset = header[off_size] + 4;
  40547. for (i = 0; i < mipmapCount; ++i) {
  40548. if (info.isRGB) {
  40549. if (bpp === 24) {
  40550. dataLength = width * height * 3;
  40551. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40552. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  40553. }
  40554. else {
  40555. dataLength = width * height * 4;
  40556. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40557. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  40558. }
  40559. }
  40560. else if (info.isLuminance) {
  40561. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  40562. var unpaddedRowSize = width;
  40563. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  40564. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  40565. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40566. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  40567. }
  40568. else {
  40569. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  40570. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  40571. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  40572. }
  40573. dataOffset += dataLength;
  40574. width *= 0.5;
  40575. height *= 0.5;
  40576. width = Math.max(1.0, width);
  40577. height = Math.max(1.0, height);
  40578. }
  40579. }
  40580. };
  40581. return DDSTools;
  40582. })();
  40583. Internals.DDSTools = DDSTools;
  40584. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40585. })(BABYLON || (BABYLON = {}));
  40586. var BABYLON;
  40587. (function (BABYLON) {
  40588. var CannonJSPlugin = (function () {
  40589. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  40590. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  40591. if (iterations === void 0) { iterations = 10; }
  40592. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  40593. this.name = "CannonJSPlugin";
  40594. this._physicsMaterials = [];
  40595. this._fixedTimeStep = 1 / 60;
  40596. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40597. this._currentCollisionGroup = 2;
  40598. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  40599. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  40600. this._tmpPosition = BABYLON.Vector3.Zero();
  40601. this._tmpQuaternion = new BABYLON.Quaternion();
  40602. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  40603. this._tmpDeltaRotation = new BABYLON.Quaternion();
  40604. this._tmpUnityRotation = new BABYLON.Quaternion();
  40605. if (!this.isSupported()) {
  40606. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  40607. return;
  40608. }
  40609. this.world = new CANNON.World();
  40610. this.world.broadphase = new CANNON.NaiveBroadphase();
  40611. this.world.solver.iterations = iterations;
  40612. }
  40613. CannonJSPlugin.prototype.setGravity = function (gravity) {
  40614. this.world.gravity.copy(gravity);
  40615. };
  40616. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  40617. this._fixedTimeStep = timeStep;
  40618. };
  40619. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  40620. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  40621. };
  40622. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40623. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40624. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40625. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40626. };
  40627. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40628. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40629. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40630. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40631. };
  40632. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40633. //parent-child relationship. Does this impostor has a parent impostor?
  40634. if (impostor.parent) {
  40635. if (impostor.physicsBody) {
  40636. this.removePhysicsBody(impostor);
  40637. //TODO is that needed?
  40638. impostor.forceUpdate();
  40639. }
  40640. return;
  40641. }
  40642. //should a new body be created for this impostor?
  40643. if (impostor.isBodyInitRequired()) {
  40644. var shape = this._createShape(impostor);
  40645. //unregister events, if body is being changed
  40646. var oldBody = impostor.physicsBody;
  40647. if (oldBody) {
  40648. this.removePhysicsBody(impostor);
  40649. }
  40650. //create the body and material
  40651. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  40652. var bodyCreationObject = {
  40653. mass: impostor.getParam("mass"),
  40654. material: material
  40655. };
  40656. // A simple extend, in case native options were used.
  40657. var nativeOptions = impostor.getParam("nativeOptions");
  40658. for (var key in nativeOptions) {
  40659. if (nativeOptions.hasOwnProperty(key)) {
  40660. bodyCreationObject[key] = nativeOptions[key];
  40661. }
  40662. }
  40663. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  40664. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  40665. this.world.addEventListener("preStep", impostor.beforeStep);
  40666. this.world.addEventListener("postStep", impostor.afterStep);
  40667. impostor.physicsBody.addShape(shape);
  40668. this.world.add(impostor.physicsBody);
  40669. //try to keep the body moving in the right direction by taking old properties.
  40670. //Should be tested!
  40671. if (oldBody) {
  40672. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  40673. impostor.physicsBody[param].copy(oldBody[param]);
  40674. });
  40675. }
  40676. this._processChildMeshes(impostor);
  40677. }
  40678. //now update the body's transformation
  40679. this._updatePhysicsBodyTransformation(impostor);
  40680. };
  40681. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  40682. var _this = this;
  40683. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  40684. if (meshChildren.length) {
  40685. var processMesh = function (localPosition, mesh) {
  40686. var childImpostor = mesh.getPhysicsImpostor();
  40687. if (childImpostor) {
  40688. var parent = childImpostor.parent;
  40689. if (parent !== mainImpostor) {
  40690. var localPosition = mesh.position;
  40691. if (childImpostor.physicsBody) {
  40692. _this.removePhysicsBody(childImpostor);
  40693. childImpostor.physicsBody = null;
  40694. }
  40695. childImpostor.parent = mainImpostor;
  40696. childImpostor.resetUpdateFlags();
  40697. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  40698. //Add the mass of the children.
  40699. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  40700. }
  40701. }
  40702. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  40703. };
  40704. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  40705. }
  40706. };
  40707. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40708. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  40709. this.world.removeEventListener("preStep", impostor.beforeStep);
  40710. this.world.removeEventListener("postStep", impostor.afterStep);
  40711. this.world.remove(impostor.physicsBody);
  40712. };
  40713. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40714. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40715. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40716. if (!mainBody || !connectedBody) {
  40717. return;
  40718. }
  40719. var constraint;
  40720. var jointData = impostorJoint.joint.jointData;
  40721. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40722. var constraintData = {
  40723. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  40724. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  40725. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  40726. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  40727. maxForce: jointData.nativeParams.maxForce,
  40728. collideConnected: !!jointData.collision
  40729. };
  40730. //Not needed, Cannon has a collideConnected flag
  40731. /*if (!jointData.collision) {
  40732. //add 1st body to a collision group of its own, if it is not in 1
  40733. if (mainBody.collisionFilterGroup === 1) {
  40734. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  40735. this._currentCollisionGroup <<= 1;
  40736. }
  40737. if (connectedBody.collisionFilterGroup === 1) {
  40738. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  40739. this._currentCollisionGroup <<= 1;
  40740. }
  40741. //add their mask to the collisionFilterMask of each other:
  40742. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  40743. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  40744. }*/
  40745. switch (impostorJoint.joint.type) {
  40746. case BABYLON.PhysicsJoint.HingeJoint:
  40747. case BABYLON.PhysicsJoint.Hinge2Joint:
  40748. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  40749. break;
  40750. case BABYLON.PhysicsJoint.DistanceJoint:
  40751. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  40752. break;
  40753. case BABYLON.PhysicsJoint.SpringJoint:
  40754. var springData = jointData;
  40755. constraint = new CANNON.Spring(mainBody, connectedBody, {
  40756. restLength: springData.length,
  40757. stiffness: springData.stiffness,
  40758. damping: springData.damping,
  40759. localAnchorA: constraintData.pivotA,
  40760. localAnchorB: constraintData.pivotB
  40761. });
  40762. break;
  40763. case BABYLON.PhysicsJoint.PointToPointJoint:
  40764. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40765. default:
  40766. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  40767. break;
  40768. }
  40769. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  40770. constraint.collideConnected = !!jointData.collision;
  40771. impostorJoint.joint.physicsJoint = constraint;
  40772. //don't add spring as constraint, as it is not one.
  40773. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  40774. this.world.addConstraint(constraint);
  40775. }
  40776. else {
  40777. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  40778. constraint.applyForce();
  40779. });
  40780. }
  40781. };
  40782. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40783. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  40784. };
  40785. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  40786. var index;
  40787. var mat;
  40788. for (index = 0; index < this._physicsMaterials.length; index++) {
  40789. mat = this._physicsMaterials[index];
  40790. if (mat.friction === friction && mat.restitution === restitution) {
  40791. return mat;
  40792. }
  40793. }
  40794. var currentMat = new CANNON.Material(name);
  40795. currentMat.friction = friction;
  40796. currentMat.restitution = restitution;
  40797. this._physicsMaterials.push(currentMat);
  40798. return currentMat;
  40799. };
  40800. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  40801. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  40802. };
  40803. CannonJSPlugin.prototype._createShape = function (impostor) {
  40804. var object = impostor.object;
  40805. var returnValue;
  40806. var extendSize = impostor.getObjectExtendSize();
  40807. switch (impostor.type) {
  40808. case BABYLON.PhysicsEngine.SphereImpostor:
  40809. var radiusX = extendSize.x;
  40810. var radiusY = extendSize.y;
  40811. var radiusZ = extendSize.z;
  40812. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40813. break;
  40814. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40815. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40816. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40817. break;
  40818. case BABYLON.PhysicsImpostor.BoxImpostor:
  40819. var box = extendSize.scale(0.5);
  40820. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40821. break;
  40822. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40823. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40824. returnValue = new CANNON.Plane();
  40825. break;
  40826. case BABYLON.PhysicsImpostor.MeshImpostor:
  40827. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40828. var rawFaces = object.getIndices ? object.getIndices() : [];
  40829. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40830. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40831. break;
  40832. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40833. returnValue = this._createHeightmap(object);
  40834. break;
  40835. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40836. returnValue = new CANNON.Particle();
  40837. break;
  40838. }
  40839. return returnValue;
  40840. };
  40841. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40842. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40843. var matrix = [];
  40844. //For now pointDepth will not be used and will be automatically calculated.
  40845. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40846. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40847. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40848. var elementSize = dim * 2 / arraySize;
  40849. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40850. for (var i = 0; i < pos.length; i = i + 3) {
  40851. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40852. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40853. var y = pos[i + 1] + minY;
  40854. if (!matrix[x]) {
  40855. matrix[x] = [];
  40856. }
  40857. if (!matrix[x][z]) {
  40858. matrix[x][z] = y;
  40859. }
  40860. matrix[x][z] = Math.max(y, matrix[x][z]);
  40861. }
  40862. for (var x = 0; x <= arraySize; ++x) {
  40863. if (!matrix[x]) {
  40864. var loc = 1;
  40865. while (!matrix[(x + loc) % arraySize]) {
  40866. loc++;
  40867. }
  40868. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40869. }
  40870. for (var z = 0; z <= arraySize; ++z) {
  40871. if (!matrix[x][z]) {
  40872. var loc = 1;
  40873. var newValue;
  40874. while (newValue === undefined) {
  40875. newValue = matrix[x][(z + loc++) % arraySize];
  40876. }
  40877. matrix[x][z] = newValue;
  40878. }
  40879. }
  40880. }
  40881. var shape = new CANNON.Heightfield(matrix, {
  40882. elementSize: elementSize
  40883. });
  40884. //For future reference, needed for body transformation
  40885. shape.minY = minY;
  40886. return shape;
  40887. };
  40888. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40889. var object = impostor.object;
  40890. //make sure it is updated...
  40891. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40892. // The delta between the mesh position and the mesh bounding box center
  40893. var center = impostor.getObjectCenter();
  40894. var extendSize = impostor.getObjectExtendSize();
  40895. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40896. this._tmpPosition.copyFrom(center);
  40897. var quaternion = object.rotationQuaternion;
  40898. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40899. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40900. //-90 DEG in X, precalculated
  40901. quaternion = quaternion.multiply(this._minus90X);
  40902. //Invert! (Precalculated, 90 deg in X)
  40903. //No need to clone. this will never change.
  40904. impostor.setDeltaRotation(this._plus90X);
  40905. }
  40906. //If it is a heightfield, if should be centered.
  40907. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40908. var mesh = object;
  40909. //calculate the correct body position:
  40910. var rotationQuaternion = mesh.rotationQuaternion;
  40911. mesh.rotationQuaternion = this._tmpUnityRotation;
  40912. mesh.computeWorldMatrix(true);
  40913. //get original center with no rotation
  40914. var c = center.clone();
  40915. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40916. //rotation is back
  40917. mesh.rotationQuaternion = rotationQuaternion;
  40918. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40919. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40920. mesh.setPivotMatrix(p);
  40921. mesh.computeWorldMatrix(true);
  40922. //calculate the translation
  40923. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40924. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40925. //add it inverted to the delta
  40926. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40927. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40928. mesh.setPivotMatrix(oldPivot);
  40929. mesh.computeWorldMatrix(true);
  40930. }
  40931. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40932. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40933. this._tmpPosition.copyFrom(object.position);
  40934. }
  40935. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40936. //Now update the impostor object
  40937. impostor.physicsBody.position.copy(this._tmpPosition);
  40938. impostor.physicsBody.quaternion.copy(quaternion);
  40939. };
  40940. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40941. impostor.object.position.copyFrom(impostor.physicsBody.position);
  40942. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  40943. };
  40944. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40945. impostor.physicsBody.position.copy(newPosition);
  40946. impostor.physicsBody.quaternion.copy(newRotation);
  40947. };
  40948. CannonJSPlugin.prototype.isSupported = function () {
  40949. return window.CANNON !== undefined;
  40950. };
  40951. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40952. impostor.physicsBody.velocity.copy(velocity);
  40953. };
  40954. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40955. impostor.physicsBody.angularVelocity.copy(velocity);
  40956. };
  40957. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40958. var v = impostor.physicsBody.velocity;
  40959. if (!v)
  40960. return null;
  40961. return new BABYLON.Vector3(v.x, v.y, v.z);
  40962. };
  40963. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40964. var v = impostor.physicsBody.angularVelocity;
  40965. if (!v)
  40966. return null;
  40967. return new BABYLON.Vector3(v.x, v.y, v.z);
  40968. };
  40969. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40970. impostor.physicsBody.mass = mass;
  40971. impostor.physicsBody.updateMassProperties();
  40972. };
  40973. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  40974. impostor.physicsBody.sleep();
  40975. };
  40976. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  40977. impostor.physicsBody.wakeUp();
  40978. };
  40979. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40980. joint.physicsJoint.distance = maxDistance;
  40981. };
  40982. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  40983. if (!motorIndex) {
  40984. joint.physicsJoint.enableMotor();
  40985. }
  40986. };
  40987. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  40988. if (!motorIndex) {
  40989. joint.physicsJoint.disableMotor();
  40990. }
  40991. };
  40992. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40993. if (!motorIndex) {
  40994. joint.physicsJoint.enableMotor();
  40995. joint.physicsJoint.setMotorSpeed(speed);
  40996. if (maxForce) {
  40997. this.setLimit(joint, maxForce);
  40998. }
  40999. }
  41000. };
  41001. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41002. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41003. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41004. };
  41005. CannonJSPlugin.prototype.dispose = function () {
  41006. //nothing to do, actually.
  41007. };
  41008. return CannonJSPlugin;
  41009. })();
  41010. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41011. })(BABYLON || (BABYLON = {}));
  41012. var BABYLON;
  41013. (function (BABYLON) {
  41014. var OimoJSPlugin = (function () {
  41015. function OimoJSPlugin(iterations) {
  41016. this.name = "OimoJSPlugin";
  41017. this._tmpImpostorsArray = [];
  41018. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41019. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41020. this.world.clear();
  41021. //making sure no stats are calculated
  41022. this.world.isNoStat = true;
  41023. }
  41024. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41025. this.world.gravity.copy(gravity);
  41026. };
  41027. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41028. this.world.timeStep = timeStep;
  41029. };
  41030. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41031. var _this = this;
  41032. impostors.forEach(function (impostor) {
  41033. impostor.beforeStep();
  41034. });
  41035. this.world.step();
  41036. impostors.forEach(function (impostor) {
  41037. impostor.afterStep();
  41038. //update the ordered impostors array
  41039. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41040. });
  41041. //check for collisions
  41042. var contact = this.world.contacts;
  41043. while (contact !== null) {
  41044. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41045. contact = contact.next;
  41046. continue;
  41047. }
  41048. //is this body colliding with any other? get the impostor
  41049. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41050. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41051. if (!mainImpostor || !collidingImpostor) {
  41052. contact = contact.next;
  41053. continue;
  41054. }
  41055. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41056. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41057. contact = contact.next;
  41058. }
  41059. };
  41060. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41061. var mass = impostor.physicsBody.massInfo.mass;
  41062. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41063. };
  41064. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41065. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41066. this.applyImpulse(impostor, force, contactPoint);
  41067. };
  41068. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41069. var _this = this;
  41070. //parent-child relationship. Does this impostor has a parent impostor?
  41071. if (impostor.parent) {
  41072. if (impostor.physicsBody) {
  41073. this.removePhysicsBody(impostor);
  41074. //TODO is that needed?
  41075. impostor.forceUpdate();
  41076. }
  41077. return;
  41078. }
  41079. if (impostor.isBodyInitRequired()) {
  41080. var bodyConfig = {
  41081. name: impostor.uniqueId,
  41082. //Oimo must have mass, also for static objects.
  41083. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41084. size: [],
  41085. type: [],
  41086. pos: [],
  41087. rot: [],
  41088. move: impostor.getParam("mass") !== 0,
  41089. //Supporting older versions of Oimo
  41090. world: this.world
  41091. };
  41092. var impostors = [impostor];
  41093. function addToArray(parent) {
  41094. if (!parent.getChildMeshes)
  41095. return;
  41096. parent.getChildMeshes().forEach(function (m) {
  41097. if (m.physicsImpostor) {
  41098. impostors.push(m.physicsImpostor);
  41099. m.physicsImpostor._init();
  41100. }
  41101. });
  41102. }
  41103. addToArray(impostor.object);
  41104. function checkWithEpsilon(value) {
  41105. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41106. }
  41107. impostors.forEach(function (i) {
  41108. //get the correct bounding box
  41109. var oldQuaternion = i.object.rotationQuaternion;
  41110. var rot = new OIMO.Euler().setFromQuaternion({
  41111. x: impostor.object.rotationQuaternion.x,
  41112. y: impostor.object.rotationQuaternion.y,
  41113. z: impostor.object.rotationQuaternion.z,
  41114. s: impostor.object.rotationQuaternion.w
  41115. });
  41116. var extendSize = i.getObjectExtendSize();
  41117. if (i === impostor) {
  41118. var center = impostor.getObjectCenter();
  41119. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41120. //Can also use Array.prototype.push.apply
  41121. bodyConfig.pos.push(center.x);
  41122. bodyConfig.pos.push(center.y);
  41123. bodyConfig.pos.push(center.z);
  41124. //tmp solution
  41125. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41126. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41127. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41128. }
  41129. else {
  41130. bodyConfig.pos.push(i.object.position.x);
  41131. bodyConfig.pos.push(i.object.position.y);
  41132. bodyConfig.pos.push(i.object.position.z);
  41133. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41134. bodyConfig.rot.push(0);
  41135. bodyConfig.rot.push(0);
  41136. bodyConfig.rot.push(0);
  41137. }
  41138. // register mesh
  41139. switch (i.type) {
  41140. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41141. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41142. case BABYLON.PhysicsImpostor.SphereImpostor:
  41143. var radiusX = extendSize.x;
  41144. var radiusY = extendSize.y;
  41145. var radiusZ = extendSize.z;
  41146. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  41147. bodyConfig.type.push('sphere');
  41148. //due to the way oimo works with compounds, add 3 times
  41149. bodyConfig.size.push(size);
  41150. bodyConfig.size.push(size);
  41151. bodyConfig.size.push(size);
  41152. break;
  41153. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41154. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  41155. var sizeY = checkWithEpsilon(extendSize.y);
  41156. bodyConfig.type.push('cylinder');
  41157. bodyConfig.size.push(sizeX);
  41158. bodyConfig.size.push(sizeY);
  41159. //due to the way oimo works with compounds, add one more value.
  41160. bodyConfig.size.push(sizeY);
  41161. break;
  41162. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41163. case BABYLON.PhysicsImpostor.BoxImpostor:
  41164. default:
  41165. var sizeX = checkWithEpsilon(extendSize.x);
  41166. var sizeY = checkWithEpsilon(extendSize.y);
  41167. var sizeZ = checkWithEpsilon(extendSize.z);
  41168. bodyConfig.type.push('box');
  41169. bodyConfig.size.push(sizeX);
  41170. bodyConfig.size.push(sizeY);
  41171. bodyConfig.size.push(sizeZ);
  41172. break;
  41173. }
  41174. //actually not needed, but hey...
  41175. i.object.rotationQuaternion = oldQuaternion;
  41176. });
  41177. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41178. }
  41179. else {
  41180. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41181. }
  41182. impostor.setDeltaPosition(this._tmpPositionVector);
  41183. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41184. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41185. };
  41186. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41187. //impostor.physicsBody.dispose();
  41188. //Same as : (older oimo versions)
  41189. this.world.removeRigidBody(impostor.physicsBody);
  41190. };
  41191. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41192. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41193. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41194. if (!mainBody || !connectedBody) {
  41195. return;
  41196. }
  41197. var jointData = impostorJoint.joint.jointData;
  41198. var options = jointData.nativeParams || {};
  41199. var type;
  41200. var nativeJointData = {
  41201. body1: mainBody,
  41202. body2: connectedBody,
  41203. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41204. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41205. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41206. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41207. min: options.min,
  41208. max: options.max,
  41209. collision: options.collision || jointData.collision,
  41210. spring: options.spring,
  41211. //supporting older version of Oimo
  41212. world: this.world
  41213. };
  41214. switch (impostorJoint.joint.type) {
  41215. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41216. type = "jointBall";
  41217. break;
  41218. case BABYLON.PhysicsJoint.SpringJoint:
  41219. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41220. var springData = jointData;
  41221. nativeJointData.min = springData.length || nativeJointData.min;
  41222. //Max should also be set, just make sure it is at least min
  41223. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41224. case BABYLON.PhysicsJoint.DistanceJoint:
  41225. type = "jointDistance";
  41226. nativeJointData.max = jointData.maxDistance;
  41227. break;
  41228. case BABYLON.PhysicsJoint.PrismaticJoint:
  41229. type = "jointPrisme";
  41230. break;
  41231. case BABYLON.PhysicsJoint.SliderJoint:
  41232. type = "jointSlide";
  41233. break;
  41234. case BABYLON.PhysicsJoint.WheelJoint:
  41235. type = "jointWheel";
  41236. break;
  41237. case BABYLON.PhysicsJoint.HingeJoint:
  41238. default:
  41239. type = "jointHinge";
  41240. break;
  41241. }
  41242. nativeJointData.type = type;
  41243. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41244. };
  41245. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41246. //Bug in Oimo prevents us from disposing a joint in the playground
  41247. //joint.joint.physicsJoint.dispose();
  41248. //So we will bruteforce it!
  41249. try {
  41250. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41251. }
  41252. catch (e) {
  41253. BABYLON.Tools.Warn(e);
  41254. }
  41255. };
  41256. OimoJSPlugin.prototype.isSupported = function () {
  41257. return OIMO !== undefined;
  41258. };
  41259. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41260. if (!impostor.physicsBody.sleeping) {
  41261. //TODO check that
  41262. if (impostor.physicsBody.shapes.next) {
  41263. var parentShape = this._getLastShape(impostor.physicsBody);
  41264. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41265. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41266. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41267. }
  41268. else {
  41269. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41270. }
  41271. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41272. }
  41273. };
  41274. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41275. var body = impostor.physicsBody;
  41276. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41277. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41278. body.syncShapes();
  41279. body.awake();
  41280. };
  41281. OimoJSPlugin.prototype._getLastShape = function (body) {
  41282. var lastShape = body.shapes;
  41283. while (lastShape.next) {
  41284. lastShape = lastShape.next;
  41285. }
  41286. return lastShape;
  41287. };
  41288. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41289. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41290. };
  41291. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41292. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41293. };
  41294. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41295. var v = impostor.physicsBody.linearVelocity;
  41296. if (!v)
  41297. return null;
  41298. return new BABYLON.Vector3(v.x, v.y, v.z);
  41299. };
  41300. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41301. var v = impostor.physicsBody.angularVelocity;
  41302. if (!v)
  41303. return null;
  41304. return new BABYLON.Vector3(v.x, v.y, v.z);
  41305. };
  41306. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41307. var staticBody = mass === 0;
  41308. //this will actually set the body's density and not its mass.
  41309. //But this is how oimo treats the mass variable.
  41310. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41311. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41312. };
  41313. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41314. impostor.physicsBody.sleep();
  41315. };
  41316. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41317. impostor.physicsBody.awake();
  41318. };
  41319. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41320. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  41321. if (minDistance !== void 0) {
  41322. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  41323. }
  41324. };
  41325. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41326. //TODO separate rotational and transational motors.
  41327. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41328. if (motor) {
  41329. motor.setMotor(speed, maxForce);
  41330. }
  41331. };
  41332. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41333. //TODO separate rotational and transational motors.
  41334. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41335. if (motor) {
  41336. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41337. }
  41338. };
  41339. OimoJSPlugin.prototype.dispose = function () {
  41340. this.world.clear();
  41341. };
  41342. return OimoJSPlugin;
  41343. })();
  41344. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41345. })(BABYLON || (BABYLON = {}));
  41346. var BABYLON;
  41347. (function (BABYLON) {
  41348. var DisplayPassPostProcess = (function (_super) {
  41349. __extends(DisplayPassPostProcess, _super);
  41350. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  41351. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  41352. }
  41353. return DisplayPassPostProcess;
  41354. })(BABYLON.PostProcess);
  41355. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41356. })(BABYLON || (BABYLON = {}));
  41357. var BABYLON;
  41358. (function (BABYLON) {
  41359. var SimplificationSettings = (function () {
  41360. function SimplificationSettings(quality, distance, optimizeMesh) {
  41361. this.quality = quality;
  41362. this.distance = distance;
  41363. this.optimizeMesh = optimizeMesh;
  41364. }
  41365. return SimplificationSettings;
  41366. })();
  41367. BABYLON.SimplificationSettings = SimplificationSettings;
  41368. var SimplificationQueue = (function () {
  41369. function SimplificationQueue() {
  41370. this.running = false;
  41371. this._simplificationArray = [];
  41372. }
  41373. SimplificationQueue.prototype.addTask = function (task) {
  41374. this._simplificationArray.push(task);
  41375. };
  41376. SimplificationQueue.prototype.executeNext = function () {
  41377. var task = this._simplificationArray.pop();
  41378. if (task) {
  41379. this.running = true;
  41380. this.runSimplification(task);
  41381. }
  41382. else {
  41383. this.running = false;
  41384. }
  41385. };
  41386. SimplificationQueue.prototype.runSimplification = function (task) {
  41387. var _this = this;
  41388. if (task.parallelProcessing) {
  41389. //parallel simplifier
  41390. task.settings.forEach(function (setting) {
  41391. var simplifier = _this.getSimplifier(task);
  41392. simplifier.simplify(setting, function (newMesh) {
  41393. task.mesh.addLODLevel(setting.distance, newMesh);
  41394. newMesh.isVisible = true;
  41395. //check if it is the last
  41396. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41397. //all done, run the success callback.
  41398. task.successCallback();
  41399. }
  41400. _this.executeNext();
  41401. });
  41402. });
  41403. }
  41404. else {
  41405. //single simplifier.
  41406. var simplifier = this.getSimplifier(task);
  41407. var runDecimation = function (setting, callback) {
  41408. simplifier.simplify(setting, function (newMesh) {
  41409. task.mesh.addLODLevel(setting.distance, newMesh);
  41410. newMesh.isVisible = true;
  41411. //run the next quality level
  41412. callback();
  41413. });
  41414. };
  41415. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41416. runDecimation(task.settings[loop.index], function () {
  41417. loop.executeNext();
  41418. });
  41419. }, function () {
  41420. //execution ended, run the success callback.
  41421. if (task.successCallback) {
  41422. task.successCallback();
  41423. }
  41424. _this.executeNext();
  41425. });
  41426. }
  41427. };
  41428. SimplificationQueue.prototype.getSimplifier = function (task) {
  41429. switch (task.simplificationType) {
  41430. case SimplificationType.QUADRATIC:
  41431. default:
  41432. return new QuadraticErrorSimplification(task.mesh);
  41433. }
  41434. };
  41435. return SimplificationQueue;
  41436. })();
  41437. BABYLON.SimplificationQueue = SimplificationQueue;
  41438. /**
  41439. * The implemented types of simplification.
  41440. * At the moment only Quadratic Error Decimation is implemented.
  41441. */
  41442. (function (SimplificationType) {
  41443. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41444. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41445. var SimplificationType = BABYLON.SimplificationType;
  41446. var DecimationTriangle = (function () {
  41447. function DecimationTriangle(vertices) {
  41448. this.vertices = vertices;
  41449. this.error = new Array(4);
  41450. this.deleted = false;
  41451. this.isDirty = false;
  41452. this.deletePending = false;
  41453. this.borderFactor = 0;
  41454. }
  41455. return DecimationTriangle;
  41456. })();
  41457. BABYLON.DecimationTriangle = DecimationTriangle;
  41458. var DecimationVertex = (function () {
  41459. function DecimationVertex(position, id) {
  41460. this.position = position;
  41461. this.id = id;
  41462. this.isBorder = true;
  41463. this.q = new QuadraticMatrix();
  41464. this.triangleCount = 0;
  41465. this.triangleStart = 0;
  41466. this.originalOffsets = [];
  41467. }
  41468. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41469. this.position.copyFrom(newPosition);
  41470. };
  41471. return DecimationVertex;
  41472. })();
  41473. BABYLON.DecimationVertex = DecimationVertex;
  41474. var QuadraticMatrix = (function () {
  41475. function QuadraticMatrix(data) {
  41476. this.data = new Array(10);
  41477. for (var i = 0; i < 10; ++i) {
  41478. if (data && data[i]) {
  41479. this.data[i] = data[i];
  41480. }
  41481. else {
  41482. this.data[i] = 0;
  41483. }
  41484. }
  41485. }
  41486. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41487. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41488. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41489. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41490. return det;
  41491. };
  41492. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41493. for (var i = 0; i < 10; ++i) {
  41494. this.data[i] += matrix.data[i];
  41495. }
  41496. };
  41497. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41498. for (var i = 0; i < 10; ++i) {
  41499. this.data[i] += data[i];
  41500. }
  41501. };
  41502. QuadraticMatrix.prototype.add = function (matrix) {
  41503. var m = new QuadraticMatrix();
  41504. for (var i = 0; i < 10; ++i) {
  41505. m.data[i] = this.data[i] + matrix.data[i];
  41506. }
  41507. return m;
  41508. };
  41509. QuadraticMatrix.FromData = function (a, b, c, d) {
  41510. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41511. };
  41512. //returning an array to avoid garbage collection
  41513. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41514. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41515. };
  41516. return QuadraticMatrix;
  41517. })();
  41518. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41519. var Reference = (function () {
  41520. function Reference(vertexId, triangleId) {
  41521. this.vertexId = vertexId;
  41522. this.triangleId = triangleId;
  41523. }
  41524. return Reference;
  41525. })();
  41526. BABYLON.Reference = Reference;
  41527. /**
  41528. * An implementation of the Quadratic Error simplification algorithm.
  41529. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41530. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41531. * @author RaananW
  41532. */
  41533. var QuadraticErrorSimplification = (function () {
  41534. function QuadraticErrorSimplification(_mesh) {
  41535. this._mesh = _mesh;
  41536. this.initialized = false;
  41537. this.syncIterations = 5000;
  41538. this.aggressiveness = 7;
  41539. this.decimationIterations = 100;
  41540. this.boundingBoxEpsilon = BABYLON.Epsilon;
  41541. }
  41542. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  41543. var _this = this;
  41544. this.initDecimatedMesh();
  41545. //iterating through the submeshes array, one after the other.
  41546. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  41547. _this.initWithMesh(loop.index, function () {
  41548. _this.runDecimation(settings, loop.index, function () {
  41549. loop.executeNext();
  41550. });
  41551. }, settings.optimizeMesh);
  41552. }, function () {
  41553. setTimeout(function () {
  41554. successCallback(_this._reconstructedMesh);
  41555. }, 0);
  41556. });
  41557. };
  41558. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  41559. var _this = this;
  41560. var gCount = 0;
  41561. triangle.vertices.forEach(function (vertex) {
  41562. var count = 0;
  41563. var vPos = vertex.position;
  41564. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  41565. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  41566. ++count;
  41567. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  41568. ++count;
  41569. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  41570. ++count;
  41571. if (count > 1) {
  41572. ++gCount;
  41573. }
  41574. ;
  41575. });
  41576. if (gCount > 1) {
  41577. console.log(triangle, gCount);
  41578. }
  41579. return gCount > 1;
  41580. };
  41581. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  41582. var _this = this;
  41583. var targetCount = ~~(this.triangles.length * settings.quality);
  41584. var deletedTriangles = 0;
  41585. var triangleCount = this.triangles.length;
  41586. var iterationFunction = function (iteration, callback) {
  41587. setTimeout(function () {
  41588. if (iteration % 5 === 0) {
  41589. _this.updateMesh(iteration === 0);
  41590. }
  41591. for (var i = 0; i < _this.triangles.length; ++i) {
  41592. _this.triangles[i].isDirty = false;
  41593. }
  41594. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  41595. var trianglesIterator = function (i) {
  41596. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  41597. var t = _this.triangles[tIdx];
  41598. if (!t)
  41599. return;
  41600. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  41601. return;
  41602. }
  41603. for (var j = 0; j < 3; ++j) {
  41604. if (t.error[j] < threshold) {
  41605. var deleted0 = [];
  41606. var deleted1 = [];
  41607. var v0 = t.vertices[j];
  41608. var v1 = t.vertices[(j + 1) % 3];
  41609. if (v0.isBorder || v1.isBorder)
  41610. continue;
  41611. var p = BABYLON.Vector3.Zero();
  41612. var n = BABYLON.Vector3.Zero();
  41613. var uv = BABYLON.Vector2.Zero();
  41614. var color = new BABYLON.Color4(0, 0, 0, 1);
  41615. _this.calculateError(v0, v1, p, n, uv, color);
  41616. var delTr = [];
  41617. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  41618. continue;
  41619. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  41620. continue;
  41621. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  41622. continue;
  41623. var uniqueArray = [];
  41624. delTr.forEach(function (deletedT) {
  41625. if (uniqueArray.indexOf(deletedT) === -1) {
  41626. deletedT.deletePending = true;
  41627. uniqueArray.push(deletedT);
  41628. }
  41629. });
  41630. if (uniqueArray.length % 2 !== 0) {
  41631. continue;
  41632. }
  41633. v0.q = v1.q.add(v0.q);
  41634. v0.updatePosition(p);
  41635. var tStart = _this.references.length;
  41636. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  41637. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  41638. var tCount = _this.references.length - tStart;
  41639. if (tCount <= v0.triangleCount) {
  41640. if (tCount) {
  41641. for (var c = 0; c < tCount; c++) {
  41642. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  41643. }
  41644. }
  41645. }
  41646. else {
  41647. v0.triangleStart = tStart;
  41648. }
  41649. v0.triangleCount = tCount;
  41650. break;
  41651. }
  41652. }
  41653. };
  41654. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  41655. }, 0);
  41656. };
  41657. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  41658. if (triangleCount - deletedTriangles <= targetCount)
  41659. loop.breakLoop();
  41660. else {
  41661. iterationFunction(loop.index, function () {
  41662. loop.executeNext();
  41663. });
  41664. }
  41665. }, function () {
  41666. setTimeout(function () {
  41667. //reconstruct this part of the mesh
  41668. _this.reconstructMesh(submeshIndex);
  41669. successCallback();
  41670. }, 0);
  41671. });
  41672. };
  41673. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  41674. var _this = this;
  41675. this.vertices = [];
  41676. this.triangles = [];
  41677. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41678. var indices = this._mesh.getIndices();
  41679. var submesh = this._mesh.subMeshes[submeshIndex];
  41680. var findInVertices = function (positionToSearch) {
  41681. if (optimizeMesh) {
  41682. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  41683. if (_this.vertices[ii].position.equals(positionToSearch)) {
  41684. return _this.vertices[ii];
  41685. }
  41686. }
  41687. }
  41688. return null;
  41689. };
  41690. var vertexReferences = [];
  41691. var vertexInit = function (i) {
  41692. var offset = i + submesh.verticesStart;
  41693. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  41694. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  41695. vertex.originalOffsets.push(offset);
  41696. if (vertex.id === _this.vertices.length) {
  41697. _this.vertices.push(vertex);
  41698. }
  41699. vertexReferences.push(vertex.id);
  41700. };
  41701. //var totalVertices = mesh.getTotalVertices();
  41702. var totalVertices = submesh.verticesCount;
  41703. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  41704. var indicesInit = function (i) {
  41705. var offset = (submesh.indexStart / 3) + i;
  41706. var pos = (offset * 3);
  41707. var i0 = indices[pos + 0];
  41708. var i1 = indices[pos + 1];
  41709. var i2 = indices[pos + 2];
  41710. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  41711. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  41712. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  41713. var triangle = new DecimationTriangle([v0, v1, v2]);
  41714. triangle.originalOffset = pos;
  41715. _this.triangles.push(triangle);
  41716. };
  41717. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  41718. _this.init(callback);
  41719. });
  41720. });
  41721. };
  41722. QuadraticErrorSimplification.prototype.init = function (callback) {
  41723. var _this = this;
  41724. var triangleInit1 = function (i) {
  41725. var t = _this.triangles[i];
  41726. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  41727. for (var j = 0; j < 3; j++) {
  41728. 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))));
  41729. }
  41730. };
  41731. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  41732. var triangleInit2 = function (i) {
  41733. var t = _this.triangles[i];
  41734. for (var j = 0; j < 3; ++j) {
  41735. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  41736. }
  41737. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41738. };
  41739. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  41740. _this.initialized = true;
  41741. callback();
  41742. });
  41743. });
  41744. };
  41745. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  41746. var newTriangles = [];
  41747. var i;
  41748. for (i = 0; i < this.vertices.length; ++i) {
  41749. this.vertices[i].triangleCount = 0;
  41750. }
  41751. var t;
  41752. var j;
  41753. for (i = 0; i < this.triangles.length; ++i) {
  41754. if (!this.triangles[i].deleted) {
  41755. t = this.triangles[i];
  41756. for (j = 0; j < 3; ++j) {
  41757. t.vertices[j].triangleCount = 1;
  41758. }
  41759. newTriangles.push(t);
  41760. }
  41761. }
  41762. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  41763. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  41764. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  41765. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  41766. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41767. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41768. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41769. var vertexCount = 0;
  41770. for (i = 0; i < this.vertices.length; ++i) {
  41771. var vertex = this.vertices[i];
  41772. vertex.id = vertexCount;
  41773. if (vertex.triangleCount) {
  41774. vertex.originalOffsets.forEach(function (originalOffset) {
  41775. newPositionData.push(vertex.position.x);
  41776. newPositionData.push(vertex.position.y);
  41777. newPositionData.push(vertex.position.z);
  41778. newNormalData.push(normalData[originalOffset * 3]);
  41779. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  41780. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  41781. if (uvs && uvs.length) {
  41782. newUVsData.push(uvs[(originalOffset * 2)]);
  41783. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  41784. }
  41785. else if (colorsData && colorsData.length) {
  41786. newColorsData.push(colorsData[(originalOffset * 4)]);
  41787. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  41788. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  41789. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  41790. }
  41791. ++vertexCount;
  41792. });
  41793. }
  41794. }
  41795. var startingIndex = this._reconstructedMesh.getTotalIndices();
  41796. var startingVertex = this._reconstructedMesh.getTotalVertices();
  41797. var submeshesArray = this._reconstructedMesh.subMeshes;
  41798. this._reconstructedMesh.subMeshes = [];
  41799. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  41800. var originalIndices = this._mesh.getIndices();
  41801. for (i = 0; i < newTriangles.length; ++i) {
  41802. t = newTriangles[i]; //now get the new referencing point for each vertex
  41803. [0, 1, 2].forEach(function (idx) {
  41804. var id = originalIndices[t.originalOffset + idx];
  41805. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  41806. if (offset < 0)
  41807. offset = 0;
  41808. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41809. });
  41810. }
  41811. //overwriting the old vertex buffers and indices.
  41812. this._reconstructedMesh.setIndices(newIndicesArray);
  41813. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41814. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41815. if (newUVsData.length > 0)
  41816. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41817. if (newColorsData.length > 0)
  41818. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41819. //create submesh
  41820. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41821. if (submeshIndex > 0) {
  41822. this._reconstructedMesh.subMeshes = [];
  41823. submeshesArray.forEach(function (submesh) {
  41824. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41825. });
  41826. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41827. }
  41828. };
  41829. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41830. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41831. this._reconstructedMesh.material = this._mesh.material;
  41832. this._reconstructedMesh.parent = this._mesh.parent;
  41833. this._reconstructedMesh.isVisible = false;
  41834. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41835. };
  41836. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41837. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41838. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41839. if (t.deleted)
  41840. continue;
  41841. var s = this.references[vertex1.triangleStart + i].vertexId;
  41842. var v1 = t.vertices[(s + 1) % 3];
  41843. var v2 = t.vertices[(s + 2) % 3];
  41844. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41845. deletedArray[i] = true;
  41846. delTr.push(t);
  41847. continue;
  41848. }
  41849. var d1 = v1.position.subtract(point);
  41850. d1 = d1.normalize();
  41851. var d2 = v2.position.subtract(point);
  41852. d2 = d2.normalize();
  41853. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41854. return true;
  41855. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41856. deletedArray[i] = false;
  41857. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41858. return true;
  41859. }
  41860. return false;
  41861. };
  41862. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41863. var newDeleted = deletedTriangles;
  41864. for (var i = 0; i < vertex.triangleCount; ++i) {
  41865. var ref = this.references[vertex.triangleStart + i];
  41866. var t = this.triangles[ref.triangleId];
  41867. if (t.deleted)
  41868. continue;
  41869. if (deletedArray[i] && t.deletePending) {
  41870. t.deleted = true;
  41871. newDeleted++;
  41872. continue;
  41873. }
  41874. t.vertices[ref.vertexId] = origVertex;
  41875. t.isDirty = true;
  41876. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41877. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41878. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41879. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41880. this.references.push(ref);
  41881. }
  41882. return newDeleted;
  41883. };
  41884. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41885. for (var i = 0; i < this.vertices.length; ++i) {
  41886. var vCount = [];
  41887. var vId = [];
  41888. var v = this.vertices[i];
  41889. var j;
  41890. for (j = 0; j < v.triangleCount; ++j) {
  41891. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41892. for (var ii = 0; ii < 3; ii++) {
  41893. var ofs = 0;
  41894. var vv = triangle.vertices[ii];
  41895. while (ofs < vCount.length) {
  41896. if (vId[ofs] === vv.id)
  41897. break;
  41898. ++ofs;
  41899. }
  41900. if (ofs === vCount.length) {
  41901. vCount.push(1);
  41902. vId.push(vv.id);
  41903. }
  41904. else {
  41905. vCount[ofs]++;
  41906. }
  41907. }
  41908. }
  41909. for (j = 0; j < vCount.length; ++j) {
  41910. if (vCount[j] === 1) {
  41911. this.vertices[vId[j]].isBorder = true;
  41912. }
  41913. else {
  41914. this.vertices[vId[j]].isBorder = false;
  41915. }
  41916. }
  41917. }
  41918. };
  41919. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41920. if (identifyBorders === void 0) { identifyBorders = false; }
  41921. var i;
  41922. if (!identifyBorders) {
  41923. var newTrianglesVector = [];
  41924. for (i = 0; i < this.triangles.length; ++i) {
  41925. if (!this.triangles[i].deleted) {
  41926. newTrianglesVector.push(this.triangles[i]);
  41927. }
  41928. }
  41929. this.triangles = newTrianglesVector;
  41930. }
  41931. for (i = 0; i < this.vertices.length; ++i) {
  41932. this.vertices[i].triangleCount = 0;
  41933. this.vertices[i].triangleStart = 0;
  41934. }
  41935. var t;
  41936. var j;
  41937. var v;
  41938. for (i = 0; i < this.triangles.length; ++i) {
  41939. t = this.triangles[i];
  41940. for (j = 0; j < 3; ++j) {
  41941. v = t.vertices[j];
  41942. v.triangleCount++;
  41943. }
  41944. }
  41945. var tStart = 0;
  41946. for (i = 0; i < this.vertices.length; ++i) {
  41947. this.vertices[i].triangleStart = tStart;
  41948. tStart += this.vertices[i].triangleCount;
  41949. this.vertices[i].triangleCount = 0;
  41950. }
  41951. var newReferences = new Array(this.triangles.length * 3);
  41952. for (i = 0; i < this.triangles.length; ++i) {
  41953. t = this.triangles[i];
  41954. for (j = 0; j < 3; ++j) {
  41955. v = t.vertices[j];
  41956. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  41957. v.triangleCount++;
  41958. }
  41959. }
  41960. this.references = newReferences;
  41961. if (identifyBorders) {
  41962. this.identifyBorder();
  41963. }
  41964. };
  41965. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  41966. var x = point.x;
  41967. var y = point.y;
  41968. var z = point.z;
  41969. 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
  41970. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  41971. };
  41972. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  41973. var q = vertex1.q.add(vertex2.q);
  41974. var border = vertex1.isBorder && vertex2.isBorder;
  41975. var error = 0;
  41976. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  41977. if (qDet !== 0 && !border) {
  41978. if (!pointResult) {
  41979. pointResult = BABYLON.Vector3.Zero();
  41980. }
  41981. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  41982. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  41983. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  41984. error = this.vertexError(q, pointResult);
  41985. }
  41986. else {
  41987. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  41988. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  41989. var error1 = this.vertexError(q, vertex1.position);
  41990. var error2 = this.vertexError(q, vertex2.position);
  41991. var error3 = this.vertexError(q, p3);
  41992. error = Math.min(error1, error2, error3);
  41993. if (error === error1) {
  41994. if (pointResult) {
  41995. pointResult.copyFrom(vertex1.position);
  41996. }
  41997. }
  41998. else if (error === error2) {
  41999. if (pointResult) {
  42000. pointResult.copyFrom(vertex2.position);
  42001. }
  42002. }
  42003. else {
  42004. if (pointResult) {
  42005. pointResult.copyFrom(p3);
  42006. }
  42007. }
  42008. }
  42009. return error;
  42010. };
  42011. return QuadraticErrorSimplification;
  42012. })();
  42013. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42014. })(BABYLON || (BABYLON = {}));
  42015. var BABYLON;
  42016. (function (BABYLON) {
  42017. var serializedGeometries = [];
  42018. var serializeGeometry = function (geometry, serializationGeometries) {
  42019. if (serializedGeometries[geometry.id]) {
  42020. return;
  42021. }
  42022. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42023. serializationGeometries.boxes.push(geometry.serialize());
  42024. }
  42025. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42026. serializationGeometries.spheres.push(geometry.serialize());
  42027. }
  42028. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42029. serializationGeometries.cylinders.push(geometry.serialize());
  42030. }
  42031. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42032. serializationGeometries.toruses.push(geometry.serialize());
  42033. }
  42034. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42035. serializationGeometries.grounds.push(geometry.serialize());
  42036. }
  42037. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42038. serializationGeometries.planes.push(geometry.serialize());
  42039. }
  42040. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42041. serializationGeometries.torusKnots.push(geometry.serialize());
  42042. }
  42043. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42044. throw new Error("Unknown primitive type");
  42045. }
  42046. else {
  42047. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42048. }
  42049. serializedGeometries[geometry.id] = true;
  42050. };
  42051. var serializeMesh = function (mesh, serializationScene) {
  42052. var serializationObject = {};
  42053. serializationObject.name = mesh.name;
  42054. serializationObject.id = mesh.id;
  42055. if (BABYLON.Tags.HasTags(mesh)) {
  42056. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42057. }
  42058. serializationObject.position = mesh.position.asArray();
  42059. if (mesh.rotationQuaternion) {
  42060. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42061. }
  42062. else if (mesh.rotation) {
  42063. serializationObject.rotation = mesh.rotation.asArray();
  42064. }
  42065. serializationObject.scaling = mesh.scaling.asArray();
  42066. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42067. serializationObject.isEnabled = mesh.isEnabled();
  42068. serializationObject.isVisible = mesh.isVisible;
  42069. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42070. serializationObject.pickable = mesh.isPickable;
  42071. serializationObject.receiveShadows = mesh.receiveShadows;
  42072. serializationObject.billboardMode = mesh.billboardMode;
  42073. serializationObject.visibility = mesh.visibility;
  42074. serializationObject.checkCollisions = mesh.checkCollisions;
  42075. // Parent
  42076. if (mesh.parent) {
  42077. serializationObject.parentId = mesh.parent.id;
  42078. }
  42079. // Geometry
  42080. var geometry = mesh._geometry;
  42081. if (geometry) {
  42082. var geometryId = geometry.id;
  42083. serializationObject.geometryId = geometryId;
  42084. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42085. // 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
  42086. serializeGeometry(geometry, serializationScene.geometries);
  42087. }
  42088. // SubMeshes
  42089. serializationObject.subMeshes = [];
  42090. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42091. var subMesh = mesh.subMeshes[subIndex];
  42092. serializationObject.subMeshes.push({
  42093. materialIndex: subMesh.materialIndex,
  42094. verticesStart: subMesh.verticesStart,
  42095. verticesCount: subMesh.verticesCount,
  42096. indexStart: subMesh.indexStart,
  42097. indexCount: subMesh.indexCount
  42098. });
  42099. }
  42100. }
  42101. // Material
  42102. if (mesh.material) {
  42103. serializationObject.materialId = mesh.material.id;
  42104. }
  42105. else {
  42106. mesh.material = null;
  42107. }
  42108. // Skeleton
  42109. if (mesh.skeleton) {
  42110. serializationObject.skeletonId = mesh.skeleton.id;
  42111. }
  42112. // Physics
  42113. //TODO implement correct serialization for physics impostors.
  42114. if (mesh.getPhysicsImpostor()) {
  42115. serializationObject.physicsMass = mesh.getPhysicsMass();
  42116. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42117. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42118. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42119. }
  42120. // Instances
  42121. serializationObject.instances = [];
  42122. for (var index = 0; index < mesh.instances.length; index++) {
  42123. var instance = mesh.instances[index];
  42124. var serializationInstance = {
  42125. name: instance.name,
  42126. position: instance.position.asArray(),
  42127. scaling: instance.scaling.asArray()
  42128. };
  42129. if (instance.rotationQuaternion) {
  42130. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42131. }
  42132. else if (instance.rotation) {
  42133. serializationInstance.rotation = instance.rotation.asArray();
  42134. }
  42135. serializationObject.instances.push(serializationInstance);
  42136. // Animations
  42137. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42138. serializationInstance.ranges = instance.serializeAnimationRanges();
  42139. }
  42140. // Animations
  42141. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42142. serializationObject.ranges = mesh.serializeAnimationRanges();
  42143. // Layer mask
  42144. serializationObject.layerMask = mesh.layerMask;
  42145. // Action Manager
  42146. if (mesh.actionManager) {
  42147. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42148. }
  42149. return serializationObject;
  42150. };
  42151. var finalizeSingleMesh = function (mesh, serializationObject) {
  42152. //only works if the mesh is already loaded
  42153. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42154. //serialize material
  42155. if (mesh.material) {
  42156. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42157. serializationObject.materials = serializationObject.materials || [];
  42158. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42159. serializationObject.materials.push(mesh.material.serialize());
  42160. }
  42161. }
  42162. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42163. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42164. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42165. serializationObject.multiMaterials.push(mesh.material.serialize());
  42166. }
  42167. }
  42168. }
  42169. //serialize geometry
  42170. var geometry = mesh._geometry;
  42171. if (geometry) {
  42172. if (!serializationObject.geometries) {
  42173. serializationObject.geometries = {};
  42174. serializationObject.geometries.boxes = [];
  42175. serializationObject.geometries.spheres = [];
  42176. serializationObject.geometries.cylinders = [];
  42177. serializationObject.geometries.toruses = [];
  42178. serializationObject.geometries.grounds = [];
  42179. serializationObject.geometries.planes = [];
  42180. serializationObject.geometries.torusKnots = [];
  42181. serializationObject.geometries.vertexData = [];
  42182. }
  42183. serializeGeometry(geometry, serializationObject.geometries);
  42184. }
  42185. // Skeletons
  42186. if (mesh.skeleton) {
  42187. serializationObject.skeletons = serializationObject.skeletons || [];
  42188. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42189. }
  42190. //serialize the actual mesh
  42191. serializationObject.meshes = serializationObject.meshes || [];
  42192. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42193. }
  42194. };
  42195. var SceneSerializer = (function () {
  42196. function SceneSerializer() {
  42197. }
  42198. SceneSerializer.ClearCache = function () {
  42199. serializedGeometries = [];
  42200. };
  42201. SceneSerializer.Serialize = function (scene) {
  42202. var serializationObject = {};
  42203. // Scene
  42204. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42205. serializationObject.autoClear = scene.autoClear;
  42206. serializationObject.clearColor = scene.clearColor.asArray();
  42207. serializationObject.ambientColor = scene.ambientColor.asArray();
  42208. serializationObject.gravity = scene.gravity.asArray();
  42209. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42210. serializationObject.workerCollisions = scene.workerCollisions;
  42211. // Fog
  42212. if (scene.fogMode && scene.fogMode !== 0) {
  42213. serializationObject.fogMode = scene.fogMode;
  42214. serializationObject.fogColor = scene.fogColor.asArray();
  42215. serializationObject.fogStart = scene.fogStart;
  42216. serializationObject.fogEnd = scene.fogEnd;
  42217. serializationObject.fogDensity = scene.fogDensity;
  42218. }
  42219. //Physics
  42220. if (scene.isPhysicsEnabled()) {
  42221. serializationObject.physicsEnabled = true;
  42222. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42223. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42224. }
  42225. // Lights
  42226. serializationObject.lights = [];
  42227. var index;
  42228. var light;
  42229. for (index = 0; index < scene.lights.length; index++) {
  42230. light = scene.lights[index];
  42231. serializationObject.lights.push(light.serialize());
  42232. }
  42233. // Cameras
  42234. serializationObject.cameras = [];
  42235. for (index = 0; index < scene.cameras.length; index++) {
  42236. var camera = scene.cameras[index];
  42237. serializationObject.cameras.push(camera.serialize());
  42238. }
  42239. if (scene.activeCamera) {
  42240. serializationObject.activeCameraID = scene.activeCamera.id;
  42241. }
  42242. // Animations
  42243. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42244. // Materials
  42245. serializationObject.materials = [];
  42246. serializationObject.multiMaterials = [];
  42247. var material;
  42248. for (index = 0; index < scene.materials.length; index++) {
  42249. material = scene.materials[index];
  42250. serializationObject.materials.push(material.serialize());
  42251. }
  42252. // MultiMaterials
  42253. serializationObject.multiMaterials = [];
  42254. for (index = 0; index < scene.multiMaterials.length; index++) {
  42255. var multiMaterial = scene.multiMaterials[index];
  42256. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42257. }
  42258. // Skeletons
  42259. serializationObject.skeletons = [];
  42260. for (index = 0; index < scene.skeletons.length; index++) {
  42261. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42262. }
  42263. // Geometries
  42264. serializationObject.geometries = {};
  42265. serializationObject.geometries.boxes = [];
  42266. serializationObject.geometries.spheres = [];
  42267. serializationObject.geometries.cylinders = [];
  42268. serializationObject.geometries.toruses = [];
  42269. serializationObject.geometries.grounds = [];
  42270. serializationObject.geometries.planes = [];
  42271. serializationObject.geometries.torusKnots = [];
  42272. serializationObject.geometries.vertexData = [];
  42273. serializedGeometries = [];
  42274. var geometries = scene.getGeometries();
  42275. for (index = 0; index < geometries.length; index++) {
  42276. var geometry = geometries[index];
  42277. if (geometry.isReady()) {
  42278. serializeGeometry(geometry, serializationObject.geometries);
  42279. }
  42280. }
  42281. // Meshes
  42282. serializationObject.meshes = [];
  42283. for (index = 0; index < scene.meshes.length; index++) {
  42284. var abstractMesh = scene.meshes[index];
  42285. if (abstractMesh instanceof BABYLON.Mesh) {
  42286. var mesh = abstractMesh;
  42287. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42288. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42289. }
  42290. }
  42291. }
  42292. // Particles Systems
  42293. serializationObject.particleSystems = [];
  42294. for (index = 0; index < scene.particleSystems.length; index++) {
  42295. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42296. }
  42297. // Lens flares
  42298. serializationObject.lensFlareSystems = [];
  42299. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42300. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42301. }
  42302. // Shadows
  42303. serializationObject.shadowGenerators = [];
  42304. for (index = 0; index < scene.lights.length; index++) {
  42305. light = scene.lights[index];
  42306. if (light.getShadowGenerator()) {
  42307. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  42308. }
  42309. }
  42310. // Action Manager
  42311. if (scene.actionManager) {
  42312. serializationObject.actions = scene.actionManager.serialize("scene");
  42313. }
  42314. return serializationObject;
  42315. };
  42316. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42317. if (withParents === void 0) { withParents = false; }
  42318. if (withChildren === void 0) { withChildren = false; }
  42319. var serializationObject = {};
  42320. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42321. if (withParents || withChildren) {
  42322. //deliberate for loop! not for each, appended should be processed as well.
  42323. for (var i = 0; i < toSerialize.length; ++i) {
  42324. if (withChildren) {
  42325. toSerialize[i].getDescendants().forEach(function (node) {
  42326. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42327. toSerialize.push(node);
  42328. }
  42329. });
  42330. }
  42331. //make sure the array doesn't contain the object already
  42332. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42333. toSerialize.push(toSerialize[i].parent);
  42334. }
  42335. }
  42336. }
  42337. toSerialize.forEach(function (mesh) {
  42338. finalizeSingleMesh(mesh, serializationObject);
  42339. });
  42340. return serializationObject;
  42341. };
  42342. return SceneSerializer;
  42343. })();
  42344. BABYLON.SceneSerializer = SceneSerializer;
  42345. })(BABYLON || (BABYLON = {}));
  42346. var BABYLON;
  42347. (function (BABYLON) {
  42348. // Unique ID when we import meshes from Babylon to CSG
  42349. var currentCSGMeshId = 0;
  42350. // # class Vertex
  42351. // Represents a vertex of a polygon. Use your own vertex class instead of this
  42352. // one to provide additional features like texture coordinates and vertex
  42353. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  42354. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  42355. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  42356. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  42357. // is not used anywhere else.
  42358. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  42359. var Vertex = (function () {
  42360. function Vertex(pos, normal, uv) {
  42361. this.pos = pos;
  42362. this.normal = normal;
  42363. this.uv = uv;
  42364. }
  42365. Vertex.prototype.clone = function () {
  42366. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  42367. };
  42368. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  42369. // orientation of a polygon is flipped.
  42370. Vertex.prototype.flip = function () {
  42371. this.normal = this.normal.scale(-1);
  42372. };
  42373. // Create a new vertex between this vertex and `other` by linearly
  42374. // interpolating all properties using a parameter of `t`. Subclasses should
  42375. // override this to interpolate additional properties.
  42376. Vertex.prototype.interpolate = function (other, t) {
  42377. 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));
  42378. };
  42379. return Vertex;
  42380. })();
  42381. // # class Plane
  42382. // Represents a plane in 3D space.
  42383. var Plane = (function () {
  42384. function Plane(normal, w) {
  42385. this.normal = normal;
  42386. this.w = w;
  42387. }
  42388. Plane.FromPoints = function (a, b, c) {
  42389. var v0 = c.subtract(a);
  42390. var v1 = b.subtract(a);
  42391. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  42392. return null;
  42393. }
  42394. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  42395. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  42396. };
  42397. Plane.prototype.clone = function () {
  42398. return new Plane(this.normal.clone(), this.w);
  42399. };
  42400. Plane.prototype.flip = function () {
  42401. this.normal.scaleInPlace(-1);
  42402. this.w = -this.w;
  42403. };
  42404. // Split `polygon` by this plane if needed, then put the polygon or polygon
  42405. // fragments in the appropriate lists. Coplanar polygons go into either
  42406. // `coplanarFront` or `coplanarBack` depending on their orientation with
  42407. // respect to this plane. Polygons in front or in back of this plane go into
  42408. // either `front` or `back`.
  42409. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  42410. var COPLANAR = 0;
  42411. var FRONT = 1;
  42412. var BACK = 2;
  42413. var SPANNING = 3;
  42414. // Classify each point as well as the entire polygon into one of the above
  42415. // four classes.
  42416. var polygonType = 0;
  42417. var types = [];
  42418. var i;
  42419. var t;
  42420. for (i = 0; i < polygon.vertices.length; i++) {
  42421. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  42422. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  42423. polygonType |= type;
  42424. types.push(type);
  42425. }
  42426. // Put the polygon in the correct list, splitting it when necessary.
  42427. switch (polygonType) {
  42428. case COPLANAR:
  42429. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  42430. break;
  42431. case FRONT:
  42432. front.push(polygon);
  42433. break;
  42434. case BACK:
  42435. back.push(polygon);
  42436. break;
  42437. case SPANNING:
  42438. var f = [], b = [];
  42439. for (i = 0; i < polygon.vertices.length; i++) {
  42440. var j = (i + 1) % polygon.vertices.length;
  42441. var ti = types[i], tj = types[j];
  42442. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  42443. if (ti !== BACK)
  42444. f.push(vi);
  42445. if (ti !== FRONT)
  42446. b.push(ti !== BACK ? vi.clone() : vi);
  42447. if ((ti | tj) === SPANNING) {
  42448. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  42449. var v = vi.interpolate(vj, t);
  42450. f.push(v);
  42451. b.push(v.clone());
  42452. }
  42453. }
  42454. var poly;
  42455. if (f.length >= 3) {
  42456. poly = new Polygon(f, polygon.shared);
  42457. if (poly.plane)
  42458. front.push(poly);
  42459. }
  42460. if (b.length >= 3) {
  42461. poly = new Polygon(b, polygon.shared);
  42462. if (poly.plane)
  42463. back.push(poly);
  42464. }
  42465. break;
  42466. }
  42467. };
  42468. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  42469. // point is on the plane.
  42470. Plane.EPSILON = 1e-5;
  42471. return Plane;
  42472. })();
  42473. // # class Polygon
  42474. // Represents a convex polygon. The vertices used to initialize a polygon must
  42475. // be coplanar and form a convex loop.
  42476. //
  42477. // Each convex polygon has a `shared` property, which is shared between all
  42478. // polygons that are clones of each other or were split from the same polygon.
  42479. // This can be used to define per-polygon properties (such as surface color).
  42480. var Polygon = (function () {
  42481. function Polygon(vertices, shared) {
  42482. this.vertices = vertices;
  42483. this.shared = shared;
  42484. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  42485. }
  42486. Polygon.prototype.clone = function () {
  42487. var vertices = this.vertices.map(function (v) { return v.clone(); });
  42488. return new Polygon(vertices, this.shared);
  42489. };
  42490. Polygon.prototype.flip = function () {
  42491. this.vertices.reverse().map(function (v) { v.flip(); });
  42492. this.plane.flip();
  42493. };
  42494. return Polygon;
  42495. })();
  42496. // # class Node
  42497. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  42498. // by picking a polygon to split along. That polygon (and all other coplanar
  42499. // polygons) are added directly to that node and the other polygons are added to
  42500. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  42501. // no distinction between internal and leaf nodes.
  42502. var Node = (function () {
  42503. function Node(polygons) {
  42504. this.plane = null;
  42505. this.front = null;
  42506. this.back = null;
  42507. this.polygons = [];
  42508. if (polygons) {
  42509. this.build(polygons);
  42510. }
  42511. }
  42512. Node.prototype.clone = function () {
  42513. var node = new Node();
  42514. node.plane = this.plane && this.plane.clone();
  42515. node.front = this.front && this.front.clone();
  42516. node.back = this.back && this.back.clone();
  42517. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  42518. return node;
  42519. };
  42520. // Convert solid space to empty space and empty space to solid space.
  42521. Node.prototype.invert = function () {
  42522. for (var i = 0; i < this.polygons.length; i++) {
  42523. this.polygons[i].flip();
  42524. }
  42525. if (this.plane) {
  42526. this.plane.flip();
  42527. }
  42528. if (this.front) {
  42529. this.front.invert();
  42530. }
  42531. if (this.back) {
  42532. this.back.invert();
  42533. }
  42534. var temp = this.front;
  42535. this.front = this.back;
  42536. this.back = temp;
  42537. };
  42538. // Recursively remove all polygons in `polygons` that are inside this BSP
  42539. // tree.
  42540. Node.prototype.clipPolygons = function (polygons) {
  42541. if (!this.plane)
  42542. return polygons.slice();
  42543. var front = [], back = [];
  42544. for (var i = 0; i < polygons.length; i++) {
  42545. this.plane.splitPolygon(polygons[i], front, back, front, back);
  42546. }
  42547. if (this.front) {
  42548. front = this.front.clipPolygons(front);
  42549. }
  42550. if (this.back) {
  42551. back = this.back.clipPolygons(back);
  42552. }
  42553. else {
  42554. back = [];
  42555. }
  42556. return front.concat(back);
  42557. };
  42558. // Remove all polygons in this BSP tree that are inside the other BSP tree
  42559. // `bsp`.
  42560. Node.prototype.clipTo = function (bsp) {
  42561. this.polygons = bsp.clipPolygons(this.polygons);
  42562. if (this.front)
  42563. this.front.clipTo(bsp);
  42564. if (this.back)
  42565. this.back.clipTo(bsp);
  42566. };
  42567. // Return a list of all polygons in this BSP tree.
  42568. Node.prototype.allPolygons = function () {
  42569. var polygons = this.polygons.slice();
  42570. if (this.front)
  42571. polygons = polygons.concat(this.front.allPolygons());
  42572. if (this.back)
  42573. polygons = polygons.concat(this.back.allPolygons());
  42574. return polygons;
  42575. };
  42576. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  42577. // new polygons are filtered down to the bottom of the tree and become new
  42578. // nodes there. Each set of polygons is partitioned using the first polygon
  42579. // (no heuristic is used to pick a good split).
  42580. Node.prototype.build = function (polygons) {
  42581. if (!polygons.length)
  42582. return;
  42583. if (!this.plane)
  42584. this.plane = polygons[0].plane.clone();
  42585. var front = [], back = [];
  42586. for (var i = 0; i < polygons.length; i++) {
  42587. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  42588. }
  42589. if (front.length) {
  42590. if (!this.front)
  42591. this.front = new Node();
  42592. this.front.build(front);
  42593. }
  42594. if (back.length) {
  42595. if (!this.back)
  42596. this.back = new Node();
  42597. this.back.build(back);
  42598. }
  42599. };
  42600. return Node;
  42601. })();
  42602. var CSG = (function () {
  42603. function CSG() {
  42604. this.polygons = new Array();
  42605. }
  42606. // Convert BABYLON.Mesh to BABYLON.CSG
  42607. CSG.FromMesh = function (mesh) {
  42608. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  42609. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  42610. if (mesh instanceof BABYLON.Mesh) {
  42611. mesh.computeWorldMatrix(true);
  42612. matrix = mesh.getWorldMatrix();
  42613. meshPosition = mesh.position.clone();
  42614. meshRotation = mesh.rotation.clone();
  42615. if (mesh.rotationQuaternion) {
  42616. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  42617. }
  42618. meshScaling = mesh.scaling.clone();
  42619. }
  42620. else {
  42621. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  42622. }
  42623. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42624. var subMeshes = mesh.subMeshes;
  42625. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  42626. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  42627. vertices = [];
  42628. for (var j = 0; j < 3; j++) {
  42629. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  42630. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  42631. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  42632. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  42633. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  42634. vertex = new Vertex(position, normal, uv);
  42635. vertices.push(vertex);
  42636. }
  42637. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  42638. // To handle the case of degenerated triangle
  42639. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  42640. if (polygon.plane)
  42641. polygons.push(polygon);
  42642. }
  42643. }
  42644. var csg = CSG.FromPolygons(polygons);
  42645. csg.matrix = matrix;
  42646. csg.position = meshPosition;
  42647. csg.rotation = meshRotation;
  42648. csg.scaling = meshScaling;
  42649. csg.rotationQuaternion = meshRotationQuaternion;
  42650. currentCSGMeshId++;
  42651. return csg;
  42652. };
  42653. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  42654. CSG.FromPolygons = function (polygons) {
  42655. var csg = new CSG();
  42656. csg.polygons = polygons;
  42657. return csg;
  42658. };
  42659. CSG.prototype.clone = function () {
  42660. var csg = new CSG();
  42661. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  42662. csg.copyTransformAttributes(this);
  42663. return csg;
  42664. };
  42665. CSG.prototype.toPolygons = function () {
  42666. return this.polygons;
  42667. };
  42668. CSG.prototype.union = function (csg) {
  42669. var a = new Node(this.clone().polygons);
  42670. var b = new Node(csg.clone().polygons);
  42671. a.clipTo(b);
  42672. b.clipTo(a);
  42673. b.invert();
  42674. b.clipTo(a);
  42675. b.invert();
  42676. a.build(b.allPolygons());
  42677. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42678. };
  42679. CSG.prototype.unionInPlace = function (csg) {
  42680. var a = new Node(this.polygons);
  42681. var b = new Node(csg.polygons);
  42682. a.clipTo(b);
  42683. b.clipTo(a);
  42684. b.invert();
  42685. b.clipTo(a);
  42686. b.invert();
  42687. a.build(b.allPolygons());
  42688. this.polygons = a.allPolygons();
  42689. };
  42690. CSG.prototype.subtract = function (csg) {
  42691. var a = new Node(this.clone().polygons);
  42692. var b = new Node(csg.clone().polygons);
  42693. a.invert();
  42694. a.clipTo(b);
  42695. b.clipTo(a);
  42696. b.invert();
  42697. b.clipTo(a);
  42698. b.invert();
  42699. a.build(b.allPolygons());
  42700. a.invert();
  42701. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42702. };
  42703. CSG.prototype.subtractInPlace = function (csg) {
  42704. var a = new Node(this.polygons);
  42705. var b = new Node(csg.polygons);
  42706. a.invert();
  42707. a.clipTo(b);
  42708. b.clipTo(a);
  42709. b.invert();
  42710. b.clipTo(a);
  42711. b.invert();
  42712. a.build(b.allPolygons());
  42713. a.invert();
  42714. this.polygons = a.allPolygons();
  42715. };
  42716. CSG.prototype.intersect = function (csg) {
  42717. var a = new Node(this.clone().polygons);
  42718. var b = new Node(csg.clone().polygons);
  42719. a.invert();
  42720. b.clipTo(a);
  42721. b.invert();
  42722. a.clipTo(b);
  42723. b.clipTo(a);
  42724. a.build(b.allPolygons());
  42725. a.invert();
  42726. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42727. };
  42728. CSG.prototype.intersectInPlace = function (csg) {
  42729. var a = new Node(this.polygons);
  42730. var b = new Node(csg.polygons);
  42731. a.invert();
  42732. b.clipTo(a);
  42733. b.invert();
  42734. a.clipTo(b);
  42735. b.clipTo(a);
  42736. a.build(b.allPolygons());
  42737. a.invert();
  42738. this.polygons = a.allPolygons();
  42739. };
  42740. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  42741. // not modified.
  42742. CSG.prototype.inverse = function () {
  42743. var csg = this.clone();
  42744. csg.inverseInPlace();
  42745. return csg;
  42746. };
  42747. CSG.prototype.inverseInPlace = function () {
  42748. this.polygons.map(function (p) { p.flip(); });
  42749. };
  42750. // This is used to keep meshes transformations so they can be restored
  42751. // when we build back a Babylon Mesh
  42752. // NB : All CSG operations are performed in world coordinates
  42753. CSG.prototype.copyTransformAttributes = function (csg) {
  42754. this.matrix = csg.matrix;
  42755. this.position = csg.position;
  42756. this.rotation = csg.rotation;
  42757. this.scaling = csg.scaling;
  42758. this.rotationQuaternion = csg.rotationQuaternion;
  42759. return this;
  42760. };
  42761. // Build Raw mesh from CSG
  42762. // Coordinates here are in world space
  42763. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  42764. var matrix = this.matrix.clone();
  42765. matrix.invert();
  42766. 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;
  42767. if (keepSubMeshes) {
  42768. // Sort Polygons, since subMeshes are indices range
  42769. polygons.sort(function (a, b) {
  42770. if (a.shared.meshId === b.shared.meshId) {
  42771. return a.shared.subMeshId - b.shared.subMeshId;
  42772. }
  42773. else {
  42774. return a.shared.meshId - b.shared.meshId;
  42775. }
  42776. });
  42777. }
  42778. for (var i = 0, il = polygons.length; i < il; i++) {
  42779. polygon = polygons[i];
  42780. // Building SubMeshes
  42781. if (!subMesh_dict[polygon.shared.meshId]) {
  42782. subMesh_dict[polygon.shared.meshId] = {};
  42783. }
  42784. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  42785. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  42786. indexStart: +Infinity,
  42787. indexEnd: -Infinity,
  42788. materialIndex: polygon.shared.materialIndex
  42789. };
  42790. }
  42791. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  42792. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  42793. polygonIndices[0] = 0;
  42794. polygonIndices[1] = j - 1;
  42795. polygonIndices[2] = j;
  42796. for (var k = 0; k < 3; k++) {
  42797. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  42798. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  42799. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  42800. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  42801. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  42802. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  42803. // Check if 2 points can be merged
  42804. if (!(typeof vertex_idx !== 'undefined' &&
  42805. normals[vertex_idx * 3] === localNormal.x &&
  42806. normals[vertex_idx * 3 + 1] === localNormal.y &&
  42807. normals[vertex_idx * 3 + 2] === localNormal.z &&
  42808. uvs[vertex_idx * 2] === uv.x &&
  42809. uvs[vertex_idx * 2 + 1] === uv.y)) {
  42810. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  42811. uvs.push(uv.x, uv.y);
  42812. normals.push(normal.x, normal.y, normal.z);
  42813. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  42814. }
  42815. indices.push(vertex_idx);
  42816. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  42817. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  42818. currentIndex++;
  42819. }
  42820. }
  42821. }
  42822. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  42823. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  42824. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  42825. mesh.setIndices(indices);
  42826. if (keepSubMeshes) {
  42827. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  42828. var materialIndexOffset = 0, materialMaxIndex;
  42829. mesh.subMeshes = new Array();
  42830. for (var m in subMesh_dict) {
  42831. materialMaxIndex = -1;
  42832. for (var sm in subMesh_dict[m]) {
  42833. subMesh_obj = subMesh_dict[m][sm];
  42834. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  42835. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  42836. }
  42837. materialIndexOffset += ++materialMaxIndex;
  42838. }
  42839. }
  42840. return mesh;
  42841. };
  42842. // Build Mesh from CSG taking material and transforms into account
  42843. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  42844. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  42845. mesh.material = material;
  42846. mesh.position.copyFrom(this.position);
  42847. mesh.rotation.copyFrom(this.rotation);
  42848. if (this.rotationQuaternion) {
  42849. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  42850. }
  42851. mesh.scaling.copyFrom(this.scaling);
  42852. mesh.computeWorldMatrix(true);
  42853. return mesh;
  42854. };
  42855. return CSG;
  42856. })();
  42857. BABYLON.CSG = CSG;
  42858. })(BABYLON || (BABYLON = {}));
  42859. var BABYLON;
  42860. (function (BABYLON) {
  42861. var VRDistortionCorrectionPostProcess = (function (_super) {
  42862. __extends(VRDistortionCorrectionPostProcess, _super);
  42863. //ANY
  42864. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  42865. var _this = this;
  42866. _super.call(this, name, "vrDistortionCorrection", [
  42867. 'LensCenter',
  42868. 'Scale',
  42869. 'ScaleIn',
  42870. 'HmdWarpParam'
  42871. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  42872. this._isRightEye = isRightEye;
  42873. this._distortionFactors = vrMetrics.distortionK;
  42874. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  42875. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42876. this.onSizeChangedObservable.add(function () {
  42877. _this.aspectRatio = _this.width * .5 / _this.height;
  42878. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42879. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42880. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42881. });
  42882. this.onApplyObservable.add(function (effect) {
  42883. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42884. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42885. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42886. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42887. });
  42888. }
  42889. return VRDistortionCorrectionPostProcess;
  42890. })(BABYLON.PostProcess);
  42891. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42892. })(BABYLON || (BABYLON = {}));
  42893. // Mainly based on these 2 articles :
  42894. // 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
  42895. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42896. var BABYLON;
  42897. (function (BABYLON) {
  42898. (function (JoystickAxis) {
  42899. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42900. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42901. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42902. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42903. var JoystickAxis = BABYLON.JoystickAxis;
  42904. var VirtualJoystick = (function () {
  42905. function VirtualJoystick(leftJoystick) {
  42906. var _this = this;
  42907. if (leftJoystick) {
  42908. this._leftJoystick = true;
  42909. }
  42910. else {
  42911. this._leftJoystick = false;
  42912. }
  42913. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42914. VirtualJoystick._globalJoystickIndex++;
  42915. // By default left & right arrow keys are moving the X
  42916. // and up & down keys are moving the Y
  42917. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42918. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42919. this.reverseLeftRight = false;
  42920. this.reverseUpDown = false;
  42921. // collections of pointers
  42922. this._touches = new BABYLON.StringDictionary();
  42923. this.deltaPosition = BABYLON.Vector3.Zero();
  42924. this._joystickSensibility = 25;
  42925. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42926. this._rotationSpeed = 25;
  42927. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42928. this._rotateOnAxisRelativeToMesh = false;
  42929. this._onResize = function (evt) {
  42930. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42931. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42932. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42933. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42934. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42935. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42936. };
  42937. // injecting a canvas element on top of the canvas 3D game
  42938. if (!VirtualJoystick.vjCanvas) {
  42939. window.addEventListener("resize", this._onResize, false);
  42940. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42941. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42942. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42943. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42944. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42945. VirtualJoystick.vjCanvas.style.width = "100%";
  42946. VirtualJoystick.vjCanvas.style.height = "100%";
  42947. VirtualJoystick.vjCanvas.style.position = "absolute";
  42948. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42949. VirtualJoystick.vjCanvas.style.top = "0px";
  42950. VirtualJoystick.vjCanvas.style.left = "0px";
  42951. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42952. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42953. // Support for jQuery PEP polyfill
  42954. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42955. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42956. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42957. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42958. document.body.appendChild(VirtualJoystick.vjCanvas);
  42959. }
  42960. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42961. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42962. this.pressed = false;
  42963. // default joystick color
  42964. this._joystickColor = "cyan";
  42965. this._joystickPointerID = -1;
  42966. // current joystick position
  42967. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42968. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42969. // origin joystick position
  42970. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42971. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42972. this._onPointerDownHandlerRef = function (evt) {
  42973. _this._onPointerDown(evt);
  42974. };
  42975. this._onPointerMoveHandlerRef = function (evt) {
  42976. _this._onPointerMove(evt);
  42977. };
  42978. this._onPointerOutHandlerRef = function (evt) {
  42979. _this._onPointerUp(evt);
  42980. };
  42981. this._onPointerUpHandlerRef = function (evt) {
  42982. _this._onPointerUp(evt);
  42983. };
  42984. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42985. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42986. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42987. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42988. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42989. evt.preventDefault(); // Disables system menu
  42990. }, false);
  42991. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42992. }
  42993. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42994. this._joystickSensibility = newJoystickSensibility;
  42995. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42996. };
  42997. VirtualJoystick.prototype._onPointerDown = function (e) {
  42998. var positionOnScreenCondition;
  42999. e.preventDefault();
  43000. if (this._leftJoystick === true) {
  43001. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  43002. }
  43003. else {
  43004. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  43005. }
  43006. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  43007. // First contact will be dedicated to the virtual joystick
  43008. this._joystickPointerID = e.pointerId;
  43009. this._joystickPointerStartPos.x = e.clientX;
  43010. this._joystickPointerStartPos.y = e.clientY;
  43011. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  43012. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  43013. this._deltaJoystickVector.x = 0;
  43014. this._deltaJoystickVector.y = 0;
  43015. this.pressed = true;
  43016. this._touches.add(e.pointerId.toString(), e);
  43017. }
  43018. else {
  43019. // You can only trigger the action buttons with a joystick declared
  43020. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  43021. this._action();
  43022. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  43023. }
  43024. }
  43025. };
  43026. VirtualJoystick.prototype._onPointerMove = function (e) {
  43027. // If the current pointer is the one associated to the joystick (first touch contact)
  43028. if (this._joystickPointerID == e.pointerId) {
  43029. this._joystickPointerPos.x = e.clientX;
  43030. this._joystickPointerPos.y = e.clientY;
  43031. this._deltaJoystickVector = this._joystickPointerPos.clone();
  43032. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  43033. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  43034. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  43035. switch (this._axisTargetedByLeftAndRight) {
  43036. case JoystickAxis.X:
  43037. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  43038. break;
  43039. case JoystickAxis.Y:
  43040. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  43041. break;
  43042. case JoystickAxis.Z:
  43043. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  43044. break;
  43045. }
  43046. var directionUpDown = this.reverseUpDown ? 1 : -1;
  43047. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  43048. switch (this._axisTargetedByUpAndDown) {
  43049. case JoystickAxis.X:
  43050. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  43051. break;
  43052. case JoystickAxis.Y:
  43053. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  43054. break;
  43055. case JoystickAxis.Z:
  43056. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  43057. break;
  43058. }
  43059. }
  43060. else {
  43061. var data = this._touches.get(e.pointerId.toString());
  43062. if (data) {
  43063. data.x = e.clientX;
  43064. data.y = e.clientY;
  43065. }
  43066. }
  43067. };
  43068. VirtualJoystick.prototype._onPointerUp = function (e) {
  43069. if (this._joystickPointerID == e.pointerId) {
  43070. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  43071. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  43072. this._joystickPointerID = -1;
  43073. this.pressed = false;
  43074. }
  43075. else {
  43076. var touch = this._touches.get(e.pointerId.toString());
  43077. if (touch) {
  43078. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43079. }
  43080. }
  43081. this._deltaJoystickVector.x = 0;
  43082. this._deltaJoystickVector.y = 0;
  43083. this._touches.remove(e.pointerId.toString());
  43084. };
  43085. /**
  43086. * Change the color of the virtual joystick
  43087. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  43088. */
  43089. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  43090. this._joystickColor = newColor;
  43091. };
  43092. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  43093. this._action = action;
  43094. };
  43095. // Define which axis you'd like to control for left & right
  43096. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  43097. switch (axis) {
  43098. case JoystickAxis.X:
  43099. case JoystickAxis.Y:
  43100. case JoystickAxis.Z:
  43101. this._axisTargetedByLeftAndRight = axis;
  43102. break;
  43103. default:
  43104. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43105. break;
  43106. }
  43107. };
  43108. // Define which axis you'd like to control for up & down
  43109. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  43110. switch (axis) {
  43111. case JoystickAxis.X:
  43112. case JoystickAxis.Y:
  43113. case JoystickAxis.Z:
  43114. this._axisTargetedByUpAndDown = axis;
  43115. break;
  43116. default:
  43117. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43118. break;
  43119. }
  43120. };
  43121. VirtualJoystick.prototype._clearCanvas = function () {
  43122. if (this._leftJoystick) {
  43123. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  43124. }
  43125. else {
  43126. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  43127. }
  43128. };
  43129. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  43130. var _this = this;
  43131. if (this.pressed) {
  43132. this._touches.forEach(function (touch) {
  43133. if (touch.pointerId === _this._joystickPointerID) {
  43134. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  43135. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  43136. VirtualJoystick.vjCanvasContext.beginPath();
  43137. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43138. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43139. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  43140. VirtualJoystick.vjCanvasContext.stroke();
  43141. VirtualJoystick.vjCanvasContext.closePath();
  43142. VirtualJoystick.vjCanvasContext.beginPath();
  43143. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43144. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43145. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  43146. VirtualJoystick.vjCanvasContext.stroke();
  43147. VirtualJoystick.vjCanvasContext.closePath();
  43148. VirtualJoystick.vjCanvasContext.beginPath();
  43149. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43150. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  43151. VirtualJoystick.vjCanvasContext.stroke();
  43152. VirtualJoystick.vjCanvasContext.closePath();
  43153. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  43154. }
  43155. else {
  43156. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43157. VirtualJoystick.vjCanvasContext.beginPath();
  43158. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  43159. VirtualJoystick.vjCanvasContext.beginPath();
  43160. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  43161. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43162. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  43163. VirtualJoystick.vjCanvasContext.stroke();
  43164. VirtualJoystick.vjCanvasContext.closePath();
  43165. touch.prevX = touch.x;
  43166. touch.prevY = touch.y;
  43167. }
  43168. ;
  43169. });
  43170. }
  43171. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43172. };
  43173. VirtualJoystick.prototype.releaseCanvas = function () {
  43174. if (VirtualJoystick.vjCanvas) {
  43175. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  43176. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  43177. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  43178. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  43179. window.removeEventListener("resize", this._onResize);
  43180. document.body.removeChild(VirtualJoystick.vjCanvas);
  43181. VirtualJoystick.vjCanvas = null;
  43182. }
  43183. };
  43184. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  43185. VirtualJoystick._globalJoystickIndex = 0;
  43186. return VirtualJoystick;
  43187. })();
  43188. BABYLON.VirtualJoystick = VirtualJoystick;
  43189. })(BABYLON || (BABYLON = {}));
  43190. var BABYLON;
  43191. (function (BABYLON) {
  43192. // We're mainly based on the logic defined into the FreeCamera code
  43193. var VirtualJoysticksCamera = (function (_super) {
  43194. __extends(VirtualJoysticksCamera, _super);
  43195. function VirtualJoysticksCamera(name, position, scene) {
  43196. _super.call(this, name, position, scene);
  43197. this.inputs.addVirtualJoystick();
  43198. }
  43199. return VirtualJoysticksCamera;
  43200. })(BABYLON.FreeCamera);
  43201. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  43202. })(BABYLON || (BABYLON = {}));
  43203. var BABYLON;
  43204. (function (BABYLON) {
  43205. var FreeCameraVirtualJoystickInput = (function () {
  43206. function FreeCameraVirtualJoystickInput() {
  43207. }
  43208. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  43209. return this._leftjoystick;
  43210. };
  43211. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  43212. return this._rightjoystick;
  43213. };
  43214. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  43215. if (this._leftjoystick) {
  43216. var camera = this.camera;
  43217. var speed = camera._computeLocalCameraSpeed() * 50;
  43218. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  43219. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  43220. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  43221. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  43222. if (!this._leftjoystick.pressed) {
  43223. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  43224. }
  43225. if (!this._rightjoystick.pressed) {
  43226. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  43227. }
  43228. }
  43229. };
  43230. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  43231. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  43232. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  43233. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  43234. this._leftjoystick.setJoystickSensibility(0.15);
  43235. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  43236. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  43237. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  43238. this._rightjoystick.reverseUpDown = true;
  43239. this._rightjoystick.setJoystickSensibility(0.05);
  43240. this._rightjoystick.setJoystickColor("yellow");
  43241. };
  43242. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  43243. this._leftjoystick.releaseCanvas();
  43244. this._rightjoystick.releaseCanvas();
  43245. };
  43246. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  43247. return "FreeCameraVirtualJoystickInput";
  43248. };
  43249. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  43250. return "virtualJoystick";
  43251. };
  43252. return FreeCameraVirtualJoystickInput;
  43253. })();
  43254. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  43255. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  43256. })(BABYLON || (BABYLON = {}));
  43257. var BABYLON;
  43258. (function (BABYLON) {
  43259. var AnaglyphPostProcess = (function (_super) {
  43260. __extends(AnaglyphPostProcess, _super);
  43261. function AnaglyphPostProcess(name, ratio, rigCameras, samplingMode, engine, reusable) {
  43262. var _this = this;
  43263. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, rigCameras[1], samplingMode, engine, reusable);
  43264. this._passedProcess = rigCameras[0]._rigPostProcess;
  43265. this.onApplyObservable.add(function (effect) {
  43266. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  43267. });
  43268. }
  43269. return AnaglyphPostProcess;
  43270. })(BABYLON.PostProcess);
  43271. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  43272. })(BABYLON || (BABYLON = {}));
  43273. var BABYLON;
  43274. (function (BABYLON) {
  43275. var OutlineRenderer = (function () {
  43276. function OutlineRenderer(scene) {
  43277. this._scene = scene;
  43278. }
  43279. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  43280. var _this = this;
  43281. if (useOverlay === void 0) { useOverlay = false; }
  43282. var scene = this._scene;
  43283. var engine = this._scene.getEngine();
  43284. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43285. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  43286. return;
  43287. }
  43288. var mesh = subMesh.getRenderingMesh();
  43289. var material = subMesh.getMaterial();
  43290. engine.enableEffect(this._effect);
  43291. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  43292. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  43293. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  43294. // Bones
  43295. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43296. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43297. }
  43298. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  43299. // Alpha test
  43300. if (material && material.needAlphaTesting()) {
  43301. var alphaTexture = material.getAlphaTestTexture();
  43302. this._effect.setTexture("diffuseSampler", alphaTexture);
  43303. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43304. }
  43305. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  43306. };
  43307. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  43308. var defines = [];
  43309. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  43310. var mesh = subMesh.getMesh();
  43311. var material = subMesh.getMaterial();
  43312. // Alpha test
  43313. if (material && material.needAlphaTesting()) {
  43314. defines.push("#define ALPHATEST");
  43315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43316. attribs.push(BABYLON.VertexBuffer.UVKind);
  43317. defines.push("#define UV1");
  43318. }
  43319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43320. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43321. defines.push("#define UV2");
  43322. }
  43323. }
  43324. // Bones
  43325. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43326. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43327. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43328. if (mesh.numBoneInfluencers > 4) {
  43329. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43330. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43331. }
  43332. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43333. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43334. }
  43335. else {
  43336. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43337. }
  43338. // Instances
  43339. if (useInstances) {
  43340. defines.push("#define INSTANCES");
  43341. attribs.push("world0");
  43342. attribs.push("world1");
  43343. attribs.push("world2");
  43344. attribs.push("world3");
  43345. }
  43346. // Get correct effect
  43347. var join = defines.join("\n");
  43348. if (this._cachedDefines !== join) {
  43349. this._cachedDefines = join;
  43350. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  43351. }
  43352. return this._effect.isReady();
  43353. };
  43354. return OutlineRenderer;
  43355. })();
  43356. BABYLON.OutlineRenderer = OutlineRenderer;
  43357. })(BABYLON || (BABYLON = {}));
  43358. var BABYLON;
  43359. (function (BABYLON) {
  43360. var MeshAssetTask = (function () {
  43361. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  43362. this.name = name;
  43363. this.meshesNames = meshesNames;
  43364. this.rootUrl = rootUrl;
  43365. this.sceneFilename = sceneFilename;
  43366. this.isCompleted = false;
  43367. }
  43368. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43369. var _this = this;
  43370. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  43371. _this.loadedMeshes = meshes;
  43372. _this.loadedParticleSystems = particleSystems;
  43373. _this.loadedSkeletons = skeletons;
  43374. _this.isCompleted = true;
  43375. if (_this.onSuccess) {
  43376. _this.onSuccess(_this);
  43377. }
  43378. onSuccess();
  43379. }, null, function () {
  43380. if (_this.onError) {
  43381. _this.onError(_this);
  43382. }
  43383. onError();
  43384. });
  43385. };
  43386. return MeshAssetTask;
  43387. })();
  43388. BABYLON.MeshAssetTask = MeshAssetTask;
  43389. var TextFileAssetTask = (function () {
  43390. function TextFileAssetTask(name, url) {
  43391. this.name = name;
  43392. this.url = url;
  43393. this.isCompleted = false;
  43394. }
  43395. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43396. var _this = this;
  43397. BABYLON.Tools.LoadFile(this.url, function (data) {
  43398. _this.text = data;
  43399. _this.isCompleted = true;
  43400. if (_this.onSuccess) {
  43401. _this.onSuccess(_this);
  43402. }
  43403. onSuccess();
  43404. }, null, scene.database, false, function () {
  43405. if (_this.onError) {
  43406. _this.onError(_this);
  43407. }
  43408. onError();
  43409. });
  43410. };
  43411. return TextFileAssetTask;
  43412. })();
  43413. BABYLON.TextFileAssetTask = TextFileAssetTask;
  43414. var BinaryFileAssetTask = (function () {
  43415. function BinaryFileAssetTask(name, url) {
  43416. this.name = name;
  43417. this.url = url;
  43418. this.isCompleted = false;
  43419. }
  43420. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43421. var _this = this;
  43422. BABYLON.Tools.LoadFile(this.url, function (data) {
  43423. _this.data = data;
  43424. _this.isCompleted = true;
  43425. if (_this.onSuccess) {
  43426. _this.onSuccess(_this);
  43427. }
  43428. onSuccess();
  43429. }, null, scene.database, true, function () {
  43430. if (_this.onError) {
  43431. _this.onError(_this);
  43432. }
  43433. onError();
  43434. });
  43435. };
  43436. return BinaryFileAssetTask;
  43437. })();
  43438. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  43439. var ImageAssetTask = (function () {
  43440. function ImageAssetTask(name, url) {
  43441. this.name = name;
  43442. this.url = url;
  43443. this.isCompleted = false;
  43444. }
  43445. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43446. var _this = this;
  43447. var img = new Image();
  43448. img.onload = function () {
  43449. _this.image = img;
  43450. _this.isCompleted = true;
  43451. if (_this.onSuccess) {
  43452. _this.onSuccess(_this);
  43453. }
  43454. onSuccess();
  43455. };
  43456. img.onerror = function () {
  43457. if (_this.onError) {
  43458. _this.onError(_this);
  43459. }
  43460. onError();
  43461. };
  43462. img.src = this.url;
  43463. };
  43464. return ImageAssetTask;
  43465. })();
  43466. BABYLON.ImageAssetTask = ImageAssetTask;
  43467. var TextureAssetTask = (function () {
  43468. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  43469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43470. this.name = name;
  43471. this.url = url;
  43472. this.noMipmap = noMipmap;
  43473. this.invertY = invertY;
  43474. this.samplingMode = samplingMode;
  43475. this.isCompleted = false;
  43476. }
  43477. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43478. var _this = this;
  43479. var onload = function () {
  43480. _this.isCompleted = true;
  43481. if (_this.onSuccess) {
  43482. _this.onSuccess(_this);
  43483. }
  43484. onSuccess();
  43485. };
  43486. var onerror = function () {
  43487. if (_this.onError) {
  43488. _this.onError(_this);
  43489. }
  43490. onError();
  43491. };
  43492. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  43493. };
  43494. return TextureAssetTask;
  43495. })();
  43496. BABYLON.TextureAssetTask = TextureAssetTask;
  43497. var AssetsManager = (function () {
  43498. function AssetsManager(scene) {
  43499. this._tasks = new Array();
  43500. this._waitingTasksCount = 0;
  43501. this.useDefaultLoadingScreen = true;
  43502. this._scene = scene;
  43503. }
  43504. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  43505. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  43506. this._tasks.push(task);
  43507. return task;
  43508. };
  43509. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  43510. var task = new TextFileAssetTask(taskName, url);
  43511. this._tasks.push(task);
  43512. return task;
  43513. };
  43514. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  43515. var task = new BinaryFileAssetTask(taskName, url);
  43516. this._tasks.push(task);
  43517. return task;
  43518. };
  43519. AssetsManager.prototype.addImageTask = function (taskName, url) {
  43520. var task = new ImageAssetTask(taskName, url);
  43521. this._tasks.push(task);
  43522. return task;
  43523. };
  43524. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  43525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43526. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  43527. this._tasks.push(task);
  43528. return task;
  43529. };
  43530. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  43531. this._waitingTasksCount--;
  43532. if (this._waitingTasksCount === 0) {
  43533. if (this.onFinish) {
  43534. this.onFinish(this._tasks);
  43535. }
  43536. this._scene.getEngine().hideLoadingUI();
  43537. }
  43538. };
  43539. AssetsManager.prototype._runTask = function (task) {
  43540. var _this = this;
  43541. task.run(this._scene, function () {
  43542. if (_this.onTaskSuccess) {
  43543. _this.onTaskSuccess(task);
  43544. }
  43545. _this._decreaseWaitingTasksCount();
  43546. }, function () {
  43547. if (_this.onTaskError) {
  43548. _this.onTaskError(task);
  43549. }
  43550. _this._decreaseWaitingTasksCount();
  43551. });
  43552. };
  43553. AssetsManager.prototype.reset = function () {
  43554. this._tasks = new Array();
  43555. return this;
  43556. };
  43557. AssetsManager.prototype.load = function () {
  43558. this._waitingTasksCount = this._tasks.length;
  43559. if (this._waitingTasksCount === 0) {
  43560. if (this.onFinish) {
  43561. this.onFinish(this._tasks);
  43562. }
  43563. return this;
  43564. }
  43565. if (this.useDefaultLoadingScreen) {
  43566. this._scene.getEngine().displayLoadingUI();
  43567. }
  43568. for (var index = 0; index < this._tasks.length; index++) {
  43569. var task = this._tasks[index];
  43570. this._runTask(task);
  43571. }
  43572. return this;
  43573. };
  43574. return AssetsManager;
  43575. })();
  43576. BABYLON.AssetsManager = AssetsManager;
  43577. })(BABYLON || (BABYLON = {}));
  43578. var BABYLON;
  43579. (function (BABYLON) {
  43580. var VRCameraMetrics = (function () {
  43581. function VRCameraMetrics() {
  43582. this.compensateDistortion = true;
  43583. }
  43584. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  43585. get: function () {
  43586. return this.hResolution / (2 * this.vResolution);
  43587. },
  43588. enumerable: true,
  43589. configurable: true
  43590. });
  43591. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  43592. get: function () {
  43593. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  43594. },
  43595. enumerable: true,
  43596. configurable: true
  43597. });
  43598. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  43599. get: function () {
  43600. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43601. var h = (4 * meters) / this.hScreenSize;
  43602. return BABYLON.Matrix.Translation(h, 0, 0);
  43603. },
  43604. enumerable: true,
  43605. configurable: true
  43606. });
  43607. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  43608. get: function () {
  43609. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43610. var h = (4 * meters) / this.hScreenSize;
  43611. return BABYLON.Matrix.Translation(-h, 0, 0);
  43612. },
  43613. enumerable: true,
  43614. configurable: true
  43615. });
  43616. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  43617. get: function () {
  43618. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  43619. },
  43620. enumerable: true,
  43621. configurable: true
  43622. });
  43623. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  43624. get: function () {
  43625. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  43626. },
  43627. enumerable: true,
  43628. configurable: true
  43629. });
  43630. VRCameraMetrics.GetDefault = function () {
  43631. var result = new VRCameraMetrics();
  43632. result.hResolution = 1280;
  43633. result.vResolution = 800;
  43634. result.hScreenSize = 0.149759993;
  43635. result.vScreenSize = 0.0935999975;
  43636. result.vScreenCenter = 0.0467999987,
  43637. result.eyeToScreenDistance = 0.0410000011;
  43638. result.lensSeparationDistance = 0.0635000020;
  43639. result.interpupillaryDistance = 0.0640000030;
  43640. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  43641. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  43642. result.postProcessScaleFactor = 1.714605507808412;
  43643. result.lensCenterOffset = 0.151976421;
  43644. return result;
  43645. };
  43646. return VRCameraMetrics;
  43647. })();
  43648. BABYLON.VRCameraMetrics = VRCameraMetrics;
  43649. })(BABYLON || (BABYLON = {}));
  43650. var BABYLON;
  43651. (function (BABYLON) {
  43652. var VRDeviceOrientationFreeCamera = (function (_super) {
  43653. __extends(VRDeviceOrientationFreeCamera, _super);
  43654. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  43655. if (compensateDistortion === void 0) { compensateDistortion = true; }
  43656. _super.call(this, name, position, scene);
  43657. this.rotationQuaternion = new BABYLON.Quaternion();
  43658. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  43659. metrics.compensateDistortion = compensateDistortion;
  43660. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  43661. this.inputs.addDeviceOrientation();
  43662. }
  43663. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  43664. return "VRDeviceOrientationFreeCamera";
  43665. };
  43666. return VRDeviceOrientationFreeCamera;
  43667. })(BABYLON.FreeCamera);
  43668. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  43669. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  43670. __extends(VRDeviceOrientationArcRotateCamera, _super);
  43671. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  43672. if (compensateDistortion === void 0) { compensateDistortion = true; }
  43673. _super.call(this, name, alpha, beta, radius, target, scene);
  43674. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  43675. metrics.compensateDistortion = compensateDistortion;
  43676. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  43677. this.inputs.addVRDeviceOrientation();
  43678. }
  43679. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  43680. return "VRDeviceOrientationArcRotateCamera";
  43681. };
  43682. return VRDeviceOrientationArcRotateCamera;
  43683. })(BABYLON.ArcRotateCamera);
  43684. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  43685. })(BABYLON || (BABYLON = {}));
  43686. var BABYLON;
  43687. (function (BABYLON) {
  43688. var WebVRFreeCamera = (function (_super) {
  43689. __extends(WebVRFreeCamera, _super);
  43690. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  43691. if (compensateDistortion === void 0) { compensateDistortion = true; }
  43692. _super.call(this, name, position, scene);
  43693. this._hmdDevice = null;
  43694. this._sensorDevice = null;
  43695. this._cacheState = null;
  43696. this._cacheQuaternion = new BABYLON.Quaternion();
  43697. this._cacheRotation = BABYLON.Vector3.Zero();
  43698. this._vrEnabled = false;
  43699. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  43700. metrics.compensateDistortion = compensateDistortion;
  43701. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  43702. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  43703. }
  43704. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  43705. var size = devices.length;
  43706. var i = 0;
  43707. // Reset devices.
  43708. this._sensorDevice = null;
  43709. this._hmdDevice = null;
  43710. // Search for a HmdDevice.
  43711. while (i < size && this._hmdDevice === null) {
  43712. if (devices[i] instanceof HMDVRDevice) {
  43713. this._hmdDevice = devices[i];
  43714. }
  43715. i++;
  43716. }
  43717. i = 0;
  43718. while (i < size && this._sensorDevice === null) {
  43719. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  43720. this._sensorDevice = devices[i];
  43721. }
  43722. i++;
  43723. }
  43724. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  43725. };
  43726. WebVRFreeCamera.prototype._checkInputs = function () {
  43727. if (this._vrEnabled) {
  43728. this._cacheState = this._sensorDevice.getState();
  43729. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  43730. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  43731. this.rotation.x = -this._cacheRotation.x;
  43732. this.rotation.y = -this._cacheRotation.y;
  43733. this.rotation.z = this._cacheRotation.z;
  43734. }
  43735. _super.prototype._checkInputs.call(this);
  43736. };
  43737. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43738. _super.prototype.attachControl.call(this, element, noPreventDefault);
  43739. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43740. if (navigator.getVRDevices) {
  43741. navigator.getVRDevices().then(this._getWebVRDevices);
  43742. }
  43743. else if (navigator.mozGetVRDevices) {
  43744. navigator.mozGetVRDevices(this._getWebVRDevices);
  43745. }
  43746. };
  43747. WebVRFreeCamera.prototype.detachControl = function (element) {
  43748. _super.prototype.detachControl.call(this, element);
  43749. this._vrEnabled = false;
  43750. };
  43751. WebVRFreeCamera.prototype.getTypeName = function () {
  43752. return "WebVRFreeCamera";
  43753. };
  43754. return WebVRFreeCamera;
  43755. })(BABYLON.FreeCamera);
  43756. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  43757. })(BABYLON || (BABYLON = {}));
  43758. var BABYLON;
  43759. (function (BABYLON) {
  43760. // Standard optimizations
  43761. var SceneOptimization = (function () {
  43762. function SceneOptimization(priority) {
  43763. if (priority === void 0) { priority = 0; }
  43764. this.priority = priority;
  43765. this.apply = function (scene) {
  43766. return true; // Return true if everything that can be done was applied
  43767. };
  43768. }
  43769. return SceneOptimization;
  43770. })();
  43771. BABYLON.SceneOptimization = SceneOptimization;
  43772. var TextureOptimization = (function (_super) {
  43773. __extends(TextureOptimization, _super);
  43774. function TextureOptimization(priority, maximumSize) {
  43775. var _this = this;
  43776. if (priority === void 0) { priority = 0; }
  43777. if (maximumSize === void 0) { maximumSize = 1024; }
  43778. _super.call(this, priority);
  43779. this.priority = priority;
  43780. this.maximumSize = maximumSize;
  43781. this.apply = function (scene) {
  43782. var allDone = true;
  43783. for (var index = 0; index < scene.textures.length; index++) {
  43784. var texture = scene.textures[index];
  43785. if (!texture.canRescale) {
  43786. continue;
  43787. }
  43788. var currentSize = texture.getSize();
  43789. var maxDimension = Math.max(currentSize.width, currentSize.height);
  43790. if (maxDimension > _this.maximumSize) {
  43791. texture.scale(0.5);
  43792. allDone = false;
  43793. }
  43794. }
  43795. return allDone;
  43796. };
  43797. }
  43798. return TextureOptimization;
  43799. })(SceneOptimization);
  43800. BABYLON.TextureOptimization = TextureOptimization;
  43801. var HardwareScalingOptimization = (function (_super) {
  43802. __extends(HardwareScalingOptimization, _super);
  43803. function HardwareScalingOptimization(priority, maximumScale) {
  43804. var _this = this;
  43805. if (priority === void 0) { priority = 0; }
  43806. if (maximumScale === void 0) { maximumScale = 2; }
  43807. _super.call(this, priority);
  43808. this.priority = priority;
  43809. this.maximumScale = maximumScale;
  43810. this._currentScale = 1;
  43811. this.apply = function (scene) {
  43812. _this._currentScale++;
  43813. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  43814. return _this._currentScale >= _this.maximumScale;
  43815. };
  43816. }
  43817. return HardwareScalingOptimization;
  43818. })(SceneOptimization);
  43819. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  43820. var ShadowsOptimization = (function (_super) {
  43821. __extends(ShadowsOptimization, _super);
  43822. function ShadowsOptimization() {
  43823. _super.apply(this, arguments);
  43824. this.apply = function (scene) {
  43825. scene.shadowsEnabled = false;
  43826. return true;
  43827. };
  43828. }
  43829. return ShadowsOptimization;
  43830. })(SceneOptimization);
  43831. BABYLON.ShadowsOptimization = ShadowsOptimization;
  43832. var PostProcessesOptimization = (function (_super) {
  43833. __extends(PostProcessesOptimization, _super);
  43834. function PostProcessesOptimization() {
  43835. _super.apply(this, arguments);
  43836. this.apply = function (scene) {
  43837. scene.postProcessesEnabled = false;
  43838. return true;
  43839. };
  43840. }
  43841. return PostProcessesOptimization;
  43842. })(SceneOptimization);
  43843. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  43844. var LensFlaresOptimization = (function (_super) {
  43845. __extends(LensFlaresOptimization, _super);
  43846. function LensFlaresOptimization() {
  43847. _super.apply(this, arguments);
  43848. this.apply = function (scene) {
  43849. scene.lensFlaresEnabled = false;
  43850. return true;
  43851. };
  43852. }
  43853. return LensFlaresOptimization;
  43854. })(SceneOptimization);
  43855. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43856. var ParticlesOptimization = (function (_super) {
  43857. __extends(ParticlesOptimization, _super);
  43858. function ParticlesOptimization() {
  43859. _super.apply(this, arguments);
  43860. this.apply = function (scene) {
  43861. scene.particlesEnabled = false;
  43862. return true;
  43863. };
  43864. }
  43865. return ParticlesOptimization;
  43866. })(SceneOptimization);
  43867. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43868. var RenderTargetsOptimization = (function (_super) {
  43869. __extends(RenderTargetsOptimization, _super);
  43870. function RenderTargetsOptimization() {
  43871. _super.apply(this, arguments);
  43872. this.apply = function (scene) {
  43873. scene.renderTargetsEnabled = false;
  43874. return true;
  43875. };
  43876. }
  43877. return RenderTargetsOptimization;
  43878. })(SceneOptimization);
  43879. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43880. var MergeMeshesOptimization = (function (_super) {
  43881. __extends(MergeMeshesOptimization, _super);
  43882. function MergeMeshesOptimization() {
  43883. var _this = this;
  43884. _super.apply(this, arguments);
  43885. this._canBeMerged = function (abstractMesh) {
  43886. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43887. return false;
  43888. }
  43889. var mesh = abstractMesh;
  43890. if (!mesh.isVisible || !mesh.isEnabled()) {
  43891. return false;
  43892. }
  43893. if (mesh.instances.length > 0) {
  43894. return false;
  43895. }
  43896. if (mesh.skeleton || mesh.hasLODLevels) {
  43897. return false;
  43898. }
  43899. if (mesh.parent) {
  43900. return false;
  43901. }
  43902. return true;
  43903. };
  43904. this.apply = function (scene, updateSelectionTree) {
  43905. var globalPool = scene.meshes.slice(0);
  43906. var globalLength = globalPool.length;
  43907. for (var index = 0; index < globalLength; index++) {
  43908. var currentPool = new Array();
  43909. var current = globalPool[index];
  43910. // Checks
  43911. if (!_this._canBeMerged(current)) {
  43912. continue;
  43913. }
  43914. currentPool.push(current);
  43915. // Find compatible meshes
  43916. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43917. var otherMesh = globalPool[subIndex];
  43918. if (!_this._canBeMerged(otherMesh)) {
  43919. continue;
  43920. }
  43921. if (otherMesh.material !== current.material) {
  43922. continue;
  43923. }
  43924. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43925. continue;
  43926. }
  43927. currentPool.push(otherMesh);
  43928. globalLength--;
  43929. globalPool.splice(subIndex, 1);
  43930. subIndex--;
  43931. }
  43932. if (currentPool.length < 2) {
  43933. continue;
  43934. }
  43935. // Merge meshes
  43936. BABYLON.Mesh.MergeMeshes(currentPool);
  43937. }
  43938. if (updateSelectionTree != undefined) {
  43939. if (updateSelectionTree) {
  43940. scene.createOrUpdateSelectionOctree();
  43941. }
  43942. }
  43943. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43944. scene.createOrUpdateSelectionOctree();
  43945. }
  43946. return true;
  43947. };
  43948. }
  43949. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43950. get: function () {
  43951. return MergeMeshesOptimization._UpdateSelectionTree;
  43952. },
  43953. set: function (value) {
  43954. MergeMeshesOptimization._UpdateSelectionTree = value;
  43955. },
  43956. enumerable: true,
  43957. configurable: true
  43958. });
  43959. MergeMeshesOptimization._UpdateSelectionTree = false;
  43960. return MergeMeshesOptimization;
  43961. })(SceneOptimization);
  43962. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43963. // Options
  43964. var SceneOptimizerOptions = (function () {
  43965. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43966. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43967. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43968. this.targetFrameRate = targetFrameRate;
  43969. this.trackerDuration = trackerDuration;
  43970. this.optimizations = new Array();
  43971. }
  43972. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43973. var result = new SceneOptimizerOptions(targetFrameRate);
  43974. var priority = 0;
  43975. result.optimizations.push(new MergeMeshesOptimization(priority));
  43976. result.optimizations.push(new ShadowsOptimization(priority));
  43977. result.optimizations.push(new LensFlaresOptimization(priority));
  43978. // Next priority
  43979. priority++;
  43980. result.optimizations.push(new PostProcessesOptimization(priority));
  43981. result.optimizations.push(new ParticlesOptimization(priority));
  43982. // Next priority
  43983. priority++;
  43984. result.optimizations.push(new TextureOptimization(priority, 1024));
  43985. return result;
  43986. };
  43987. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43988. var result = new SceneOptimizerOptions(targetFrameRate);
  43989. var priority = 0;
  43990. result.optimizations.push(new MergeMeshesOptimization(priority));
  43991. result.optimizations.push(new ShadowsOptimization(priority));
  43992. result.optimizations.push(new LensFlaresOptimization(priority));
  43993. // Next priority
  43994. priority++;
  43995. result.optimizations.push(new PostProcessesOptimization(priority));
  43996. result.optimizations.push(new ParticlesOptimization(priority));
  43997. // Next priority
  43998. priority++;
  43999. result.optimizations.push(new TextureOptimization(priority, 512));
  44000. // Next priority
  44001. priority++;
  44002. result.optimizations.push(new RenderTargetsOptimization(priority));
  44003. // Next priority
  44004. priority++;
  44005. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  44006. return result;
  44007. };
  44008. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  44009. var result = new SceneOptimizerOptions(targetFrameRate);
  44010. var priority = 0;
  44011. result.optimizations.push(new MergeMeshesOptimization(priority));
  44012. result.optimizations.push(new ShadowsOptimization(priority));
  44013. result.optimizations.push(new LensFlaresOptimization(priority));
  44014. // Next priority
  44015. priority++;
  44016. result.optimizations.push(new PostProcessesOptimization(priority));
  44017. result.optimizations.push(new ParticlesOptimization(priority));
  44018. // Next priority
  44019. priority++;
  44020. result.optimizations.push(new TextureOptimization(priority, 256));
  44021. // Next priority
  44022. priority++;
  44023. result.optimizations.push(new RenderTargetsOptimization(priority));
  44024. // Next priority
  44025. priority++;
  44026. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  44027. return result;
  44028. };
  44029. return SceneOptimizerOptions;
  44030. })();
  44031. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  44032. // Scene optimizer tool
  44033. var SceneOptimizer = (function () {
  44034. function SceneOptimizer() {
  44035. }
  44036. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  44037. // TODO: add an epsilon
  44038. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  44039. if (onSuccess) {
  44040. onSuccess();
  44041. }
  44042. return;
  44043. }
  44044. // Apply current level of optimizations
  44045. var allDone = true;
  44046. var noOptimizationApplied = true;
  44047. for (var index = 0; index < options.optimizations.length; index++) {
  44048. var optimization = options.optimizations[index];
  44049. if (optimization.priority === currentPriorityLevel) {
  44050. noOptimizationApplied = false;
  44051. allDone = allDone && optimization.apply(scene);
  44052. }
  44053. }
  44054. // If no optimization was applied, this is a failure :(
  44055. if (noOptimizationApplied) {
  44056. if (onFailure) {
  44057. onFailure();
  44058. }
  44059. return;
  44060. }
  44061. // If all optimizations were done, move to next level
  44062. if (allDone) {
  44063. currentPriorityLevel++;
  44064. }
  44065. // Let's the system running for a specific amount of time before checking FPS
  44066. scene.executeWhenReady(function () {
  44067. setTimeout(function () {
  44068. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  44069. }, options.trackerDuration);
  44070. });
  44071. };
  44072. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  44073. if (!options) {
  44074. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  44075. }
  44076. // Let's the system running for a specific amount of time before checking FPS
  44077. scene.executeWhenReady(function () {
  44078. setTimeout(function () {
  44079. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  44080. }, options.trackerDuration);
  44081. });
  44082. };
  44083. return SceneOptimizer;
  44084. })();
  44085. BABYLON.SceneOptimizer = SceneOptimizer;
  44086. })(BABYLON || (BABYLON = {}));
  44087. var BABYLON;
  44088. (function (BABYLON) {
  44089. var Internals;
  44090. (function (Internals) {
  44091. var MeshLODLevel = (function () {
  44092. function MeshLODLevel(distance, mesh) {
  44093. this.distance = distance;
  44094. this.mesh = mesh;
  44095. }
  44096. return MeshLODLevel;
  44097. })();
  44098. Internals.MeshLODLevel = MeshLODLevel;
  44099. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44100. })(BABYLON || (BABYLON = {}));
  44101. var BABYLON;
  44102. (function (BABYLON) {
  44103. var RawTexture = (function (_super) {
  44104. __extends(RawTexture, _super);
  44105. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44106. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44107. if (invertY === void 0) { invertY = false; }
  44108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44109. _super.call(this, null, scene, !generateMipMaps, invertY);
  44110. this.format = format;
  44111. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44112. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44113. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44114. }
  44115. RawTexture.prototype.update = function (data) {
  44116. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44117. };
  44118. // Statics
  44119. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44120. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44121. if (invertY === void 0) { invertY = false; }
  44122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44123. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44124. };
  44125. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44126. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44127. if (invertY === void 0) { invertY = false; }
  44128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44129. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44130. };
  44131. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44132. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44133. if (invertY === void 0) { invertY = false; }
  44134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44135. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44136. };
  44137. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44138. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44139. if (invertY === void 0) { invertY = false; }
  44140. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44141. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44142. };
  44143. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44144. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44145. if (invertY === void 0) { invertY = false; }
  44146. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44147. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44148. };
  44149. return RawTexture;
  44150. })(BABYLON.Texture);
  44151. BABYLON.RawTexture = RawTexture;
  44152. })(BABYLON || (BABYLON = {}));
  44153. var BABYLON;
  44154. (function (BABYLON) {
  44155. var IndexedVector2 = (function (_super) {
  44156. __extends(IndexedVector2, _super);
  44157. function IndexedVector2(original, index) {
  44158. _super.call(this, original.x, original.y);
  44159. this.index = index;
  44160. }
  44161. return IndexedVector2;
  44162. })(BABYLON.Vector2);
  44163. var PolygonPoints = (function () {
  44164. function PolygonPoints() {
  44165. this.elements = new Array();
  44166. }
  44167. PolygonPoints.prototype.add = function (originalPoints) {
  44168. var _this = this;
  44169. var result = new Array();
  44170. originalPoints.forEach(function (point) {
  44171. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  44172. var newPoint = new IndexedVector2(point, _this.elements.length);
  44173. result.push(newPoint);
  44174. _this.elements.push(newPoint);
  44175. }
  44176. });
  44177. return result;
  44178. };
  44179. PolygonPoints.prototype.computeBounds = function () {
  44180. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44181. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44182. this.elements.forEach(function (point) {
  44183. // x
  44184. if (point.x < lmin.x) {
  44185. lmin.x = point.x;
  44186. }
  44187. else if (point.x > lmax.x) {
  44188. lmax.x = point.x;
  44189. }
  44190. // y
  44191. if (point.y < lmin.y) {
  44192. lmin.y = point.y;
  44193. }
  44194. else if (point.y > lmax.y) {
  44195. lmax.y = point.y;
  44196. }
  44197. });
  44198. return {
  44199. min: lmin,
  44200. max: lmax,
  44201. width: lmax.x - lmin.x,
  44202. height: lmax.y - lmin.y
  44203. };
  44204. };
  44205. return PolygonPoints;
  44206. })();
  44207. var Polygon = (function () {
  44208. function Polygon() {
  44209. }
  44210. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  44211. return [
  44212. new BABYLON.Vector2(xmin, ymin),
  44213. new BABYLON.Vector2(xmax, ymin),
  44214. new BABYLON.Vector2(xmax, ymax),
  44215. new BABYLON.Vector2(xmin, ymax)
  44216. ];
  44217. };
  44218. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  44219. if (cx === void 0) { cx = 0; }
  44220. if (cy === void 0) { cy = 0; }
  44221. if (numberOfSides === void 0) { numberOfSides = 32; }
  44222. var result = new Array();
  44223. var angle = 0;
  44224. var increment = (Math.PI * 2) / numberOfSides;
  44225. for (var i = 0; i < numberOfSides; i++) {
  44226. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  44227. angle -= increment;
  44228. }
  44229. return result;
  44230. };
  44231. Polygon.Parse = function (input) {
  44232. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  44233. var i, result = [];
  44234. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  44235. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  44236. }
  44237. return result;
  44238. };
  44239. Polygon.StartingAt = function (x, y) {
  44240. return BABYLON.Path2.StartingAt(x, y);
  44241. };
  44242. return Polygon;
  44243. })();
  44244. BABYLON.Polygon = Polygon;
  44245. var PolygonMeshBuilder = (function () {
  44246. function PolygonMeshBuilder(name, contours, scene) {
  44247. this._points = new PolygonPoints();
  44248. this._outlinepoints = new PolygonPoints();
  44249. this._holes = [];
  44250. if (!("poly2tri" in window)) {
  44251. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  44252. }
  44253. this._name = name;
  44254. this._scene = scene;
  44255. var points;
  44256. if (contours instanceof BABYLON.Path2) {
  44257. points = contours.getPoints();
  44258. }
  44259. else {
  44260. points = contours;
  44261. }
  44262. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  44263. this._outlinepoints.add(points);
  44264. }
  44265. PolygonMeshBuilder.prototype.addHole = function (hole) {
  44266. this._swctx.addHole(this._points.add(hole));
  44267. var holepoints = new PolygonPoints();
  44268. holepoints.add(hole);
  44269. this._holes.push(holepoints);
  44270. return this;
  44271. };
  44272. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  44273. var _this = this;
  44274. if (updatable === void 0) { updatable = false; }
  44275. var result = new BABYLON.Mesh(this._name, this._scene);
  44276. var normals = [];
  44277. var positions = [];
  44278. var uvs = [];
  44279. var bounds = this._points.computeBounds();
  44280. this._points.elements.forEach(function (p) {
  44281. normals.push(0, 1.0, 0);
  44282. positions.push(p.x, 0, p.y);
  44283. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  44284. });
  44285. var indices = [];
  44286. this._swctx.triangulate();
  44287. this._swctx.getTriangles().forEach(function (triangle) {
  44288. triangle.getPoints().forEach(function (point) {
  44289. indices.push(point.index);
  44290. });
  44291. });
  44292. if (depth > 0) {
  44293. var positionscount = (positions.length / 3); //get the current pointcount
  44294. this._points.elements.forEach(function (p) {
  44295. normals.push(0, -1.0, 0);
  44296. positions.push(p.x, -depth, p.y);
  44297. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  44298. });
  44299. var p1; //we need to change order of point so the triangles are made in the rigth way.
  44300. var p2;
  44301. var poscounter = 0;
  44302. this._swctx.getTriangles().forEach(function (triangle) {
  44303. triangle.getPoints().forEach(function (point) {
  44304. switch (poscounter) {
  44305. case 0:
  44306. p1 = point;
  44307. break;
  44308. case 1:
  44309. p2 = point;
  44310. break;
  44311. case 2:
  44312. indices.push(point.index + positionscount);
  44313. indices.push(p2.index + positionscount);
  44314. indices.push(p1.index + positionscount);
  44315. poscounter = -1;
  44316. break;
  44317. }
  44318. poscounter++;
  44319. //indices.push((<IndexedVector2>point).index + positionscount);
  44320. });
  44321. });
  44322. //Add the sides
  44323. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  44324. this._holes.forEach(function (hole) {
  44325. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  44326. });
  44327. }
  44328. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  44329. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  44330. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  44331. result.setIndices(indices);
  44332. return result;
  44333. };
  44334. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  44335. var StartIndex = positions.length / 3;
  44336. var ulength = 0;
  44337. for (var i = 0; i < points.elements.length; i++) {
  44338. var p = points.elements[i];
  44339. var p1;
  44340. if ((i + 1) > points.elements.length - 1) {
  44341. p1 = points.elements[0];
  44342. }
  44343. else {
  44344. p1 = points.elements[i + 1];
  44345. }
  44346. positions.push(p.x, 0, p.y);
  44347. positions.push(p.x, -depth, p.y);
  44348. positions.push(p1.x, 0, p1.y);
  44349. positions.push(p1.x, -depth, p1.y);
  44350. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  44351. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  44352. var v3 = v2.subtract(v1);
  44353. var v4 = new BABYLON.Vector3(0, 1, 0);
  44354. var vn = BABYLON.Vector3.Cross(v3, v4);
  44355. vn = vn.normalize();
  44356. uvs.push(ulength / bounds.width, 0);
  44357. uvs.push(ulength / bounds.width, 1);
  44358. ulength += v3.length();
  44359. uvs.push((ulength / bounds.width), 0);
  44360. uvs.push((ulength / bounds.width), 1);
  44361. if (!flip) {
  44362. normals.push(-vn.x, -vn.y, -vn.z);
  44363. normals.push(-vn.x, -vn.y, -vn.z);
  44364. normals.push(-vn.x, -vn.y, -vn.z);
  44365. normals.push(-vn.x, -vn.y, -vn.z);
  44366. indices.push(StartIndex);
  44367. indices.push(StartIndex + 1);
  44368. indices.push(StartIndex + 2);
  44369. indices.push(StartIndex + 1);
  44370. indices.push(StartIndex + 3);
  44371. indices.push(StartIndex + 2);
  44372. }
  44373. else {
  44374. normals.push(vn.x, vn.y, vn.z);
  44375. normals.push(vn.x, vn.y, vn.z);
  44376. normals.push(vn.x, vn.y, vn.z);
  44377. normals.push(vn.x, vn.y, vn.z);
  44378. indices.push(StartIndex);
  44379. indices.push(StartIndex + 2);
  44380. indices.push(StartIndex + 1);
  44381. indices.push(StartIndex + 1);
  44382. indices.push(StartIndex + 2);
  44383. indices.push(StartIndex + 3);
  44384. }
  44385. StartIndex += 4;
  44386. }
  44387. ;
  44388. };
  44389. return PolygonMeshBuilder;
  44390. })();
  44391. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  44392. })(BABYLON || (BABYLON = {}));
  44393. var BABYLON;
  44394. (function (BABYLON) {
  44395. var Octree = (function () {
  44396. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  44397. if (maxDepth === void 0) { maxDepth = 2; }
  44398. this.maxDepth = maxDepth;
  44399. this.dynamicContent = new Array();
  44400. this._maxBlockCapacity = maxBlockCapacity || 64;
  44401. this._selectionContent = new BABYLON.SmartArray(1024);
  44402. this._creationFunc = creationFunc;
  44403. }
  44404. // Methods
  44405. Octree.prototype.update = function (worldMin, worldMax, entries) {
  44406. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  44407. };
  44408. Octree.prototype.addMesh = function (entry) {
  44409. for (var index = 0; index < this.blocks.length; index++) {
  44410. var block = this.blocks[index];
  44411. block.addEntry(entry);
  44412. }
  44413. };
  44414. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  44415. this._selectionContent.reset();
  44416. for (var index = 0; index < this.blocks.length; index++) {
  44417. var block = this.blocks[index];
  44418. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  44419. }
  44420. if (allowDuplicate) {
  44421. this._selectionContent.concat(this.dynamicContent);
  44422. }
  44423. else {
  44424. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44425. }
  44426. return this._selectionContent;
  44427. };
  44428. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  44429. this._selectionContent.reset();
  44430. for (var index = 0; index < this.blocks.length; index++) {
  44431. var block = this.blocks[index];
  44432. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  44433. }
  44434. if (allowDuplicate) {
  44435. this._selectionContent.concat(this.dynamicContent);
  44436. }
  44437. else {
  44438. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44439. }
  44440. return this._selectionContent;
  44441. };
  44442. Octree.prototype.intersectsRay = function (ray) {
  44443. this._selectionContent.reset();
  44444. for (var index = 0; index < this.blocks.length; index++) {
  44445. var block = this.blocks[index];
  44446. block.intersectsRay(ray, this._selectionContent);
  44447. }
  44448. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44449. return this._selectionContent;
  44450. };
  44451. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  44452. target.blocks = new Array();
  44453. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  44454. // Segmenting space
  44455. for (var x = 0; x < 2; x++) {
  44456. for (var y = 0; y < 2; y++) {
  44457. for (var z = 0; z < 2; z++) {
  44458. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  44459. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  44460. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  44461. block.addEntries(entries);
  44462. target.blocks.push(block);
  44463. }
  44464. }
  44465. }
  44466. };
  44467. Octree.CreationFuncForMeshes = function (entry, block) {
  44468. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44469. block.entries.push(entry);
  44470. }
  44471. };
  44472. Octree.CreationFuncForSubMeshes = function (entry, block) {
  44473. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44474. block.entries.push(entry);
  44475. }
  44476. };
  44477. return Octree;
  44478. })();
  44479. BABYLON.Octree = Octree;
  44480. })(BABYLON || (BABYLON = {}));
  44481. var BABYLON;
  44482. (function (BABYLON) {
  44483. var OctreeBlock = (function () {
  44484. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  44485. this.entries = new Array();
  44486. this._boundingVectors = new Array();
  44487. this._capacity = capacity;
  44488. this._depth = depth;
  44489. this._maxDepth = maxDepth;
  44490. this._creationFunc = creationFunc;
  44491. this._minPoint = minPoint;
  44492. this._maxPoint = maxPoint;
  44493. this._boundingVectors.push(minPoint.clone());
  44494. this._boundingVectors.push(maxPoint.clone());
  44495. this._boundingVectors.push(minPoint.clone());
  44496. this._boundingVectors[2].x = maxPoint.x;
  44497. this._boundingVectors.push(minPoint.clone());
  44498. this._boundingVectors[3].y = maxPoint.y;
  44499. this._boundingVectors.push(minPoint.clone());
  44500. this._boundingVectors[4].z = maxPoint.z;
  44501. this._boundingVectors.push(maxPoint.clone());
  44502. this._boundingVectors[5].z = minPoint.z;
  44503. this._boundingVectors.push(maxPoint.clone());
  44504. this._boundingVectors[6].x = minPoint.x;
  44505. this._boundingVectors.push(maxPoint.clone());
  44506. this._boundingVectors[7].y = minPoint.y;
  44507. }
  44508. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  44509. // Property
  44510. get: function () {
  44511. return this._capacity;
  44512. },
  44513. enumerable: true,
  44514. configurable: true
  44515. });
  44516. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  44517. get: function () {
  44518. return this._minPoint;
  44519. },
  44520. enumerable: true,
  44521. configurable: true
  44522. });
  44523. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  44524. get: function () {
  44525. return this._maxPoint;
  44526. },
  44527. enumerable: true,
  44528. configurable: true
  44529. });
  44530. // Methods
  44531. OctreeBlock.prototype.addEntry = function (entry) {
  44532. if (this.blocks) {
  44533. for (var index = 0; index < this.blocks.length; index++) {
  44534. var block = this.blocks[index];
  44535. block.addEntry(entry);
  44536. }
  44537. return;
  44538. }
  44539. this._creationFunc(entry, this);
  44540. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  44541. this.createInnerBlocks();
  44542. }
  44543. };
  44544. OctreeBlock.prototype.addEntries = function (entries) {
  44545. for (var index = 0; index < entries.length; index++) {
  44546. var mesh = entries[index];
  44547. this.addEntry(mesh);
  44548. }
  44549. };
  44550. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  44551. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  44552. if (this.blocks) {
  44553. for (var index = 0; index < this.blocks.length; index++) {
  44554. var block = this.blocks[index];
  44555. block.select(frustumPlanes, selection, allowDuplicate);
  44556. }
  44557. return;
  44558. }
  44559. if (allowDuplicate) {
  44560. selection.concat(this.entries);
  44561. }
  44562. else {
  44563. selection.concatWithNoDuplicate(this.entries);
  44564. }
  44565. }
  44566. };
  44567. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  44568. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  44569. if (this.blocks) {
  44570. for (var index = 0; index < this.blocks.length; index++) {
  44571. var block = this.blocks[index];
  44572. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  44573. }
  44574. return;
  44575. }
  44576. if (allowDuplicate) {
  44577. selection.concat(this.entries);
  44578. }
  44579. else {
  44580. selection.concatWithNoDuplicate(this.entries);
  44581. }
  44582. }
  44583. };
  44584. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  44585. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  44586. if (this.blocks) {
  44587. for (var index = 0; index < this.blocks.length; index++) {
  44588. var block = this.blocks[index];
  44589. block.intersectsRay(ray, selection);
  44590. }
  44591. return;
  44592. }
  44593. selection.concatWithNoDuplicate(this.entries);
  44594. }
  44595. };
  44596. OctreeBlock.prototype.createInnerBlocks = function () {
  44597. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  44598. };
  44599. return OctreeBlock;
  44600. })();
  44601. BABYLON.OctreeBlock = OctreeBlock;
  44602. })(BABYLON || (BABYLON = {}));
  44603. var BABYLON;
  44604. (function (BABYLON) {
  44605. var BlurPostProcess = (function (_super) {
  44606. __extends(BlurPostProcess, _super);
  44607. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  44608. var _this = this;
  44609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44610. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  44611. this.direction = direction;
  44612. this.blurWidth = blurWidth;
  44613. this.onApplyObservable.add(function (effect) {
  44614. effect.setFloat2("screenSize", _this.width, _this.height);
  44615. effect.setVector2("direction", _this.direction);
  44616. effect.setFloat("blurWidth", _this.blurWidth);
  44617. });
  44618. }
  44619. return BlurPostProcess;
  44620. })(BABYLON.PostProcess);
  44621. BABYLON.BlurPostProcess = BlurPostProcess;
  44622. })(BABYLON || (BABYLON = {}));
  44623. var BABYLON;
  44624. (function (BABYLON) {
  44625. var RefractionPostProcess = (function (_super) {
  44626. __extends(RefractionPostProcess, _super);
  44627. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  44628. var _this = this;
  44629. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  44630. this.color = color;
  44631. this.depth = depth;
  44632. this.colorLevel = colorLevel;
  44633. this.onActivateObservable.add(function (cam) {
  44634. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  44635. });
  44636. this.onApplyObservable.add(function (effect) {
  44637. effect.setColor3("baseColor", _this.color);
  44638. effect.setFloat("depth", _this.depth);
  44639. effect.setFloat("colorLevel", _this.colorLevel);
  44640. effect.setTexture("refractionSampler", _this._refRexture);
  44641. });
  44642. }
  44643. // Methods
  44644. RefractionPostProcess.prototype.dispose = function (camera) {
  44645. if (this._refRexture) {
  44646. this._refRexture.dispose();
  44647. }
  44648. _super.prototype.dispose.call(this, camera);
  44649. };
  44650. return RefractionPostProcess;
  44651. })(BABYLON.PostProcess);
  44652. BABYLON.RefractionPostProcess = RefractionPostProcess;
  44653. })(BABYLON || (BABYLON = {}));
  44654. var BABYLON;
  44655. (function (BABYLON) {
  44656. var BlackAndWhitePostProcess = (function (_super) {
  44657. __extends(BlackAndWhitePostProcess, _super);
  44658. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  44659. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  44660. }
  44661. return BlackAndWhitePostProcess;
  44662. })(BABYLON.PostProcess);
  44663. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  44664. })(BABYLON || (BABYLON = {}));
  44665. var BABYLON;
  44666. (function (BABYLON) {
  44667. var ConvolutionPostProcess = (function (_super) {
  44668. __extends(ConvolutionPostProcess, _super);
  44669. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  44670. var _this = this;
  44671. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  44672. this.kernel = kernel;
  44673. this.onApply = function (effect) {
  44674. effect.setFloat2("screenSize", _this.width, _this.height);
  44675. effect.setArray("kernel", _this.kernel);
  44676. };
  44677. }
  44678. // Statics
  44679. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  44680. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  44681. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  44682. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  44683. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  44684. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  44685. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  44686. return ConvolutionPostProcess;
  44687. })(BABYLON.PostProcess);
  44688. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  44689. })(BABYLON || (BABYLON = {}));
  44690. var BABYLON;
  44691. (function (BABYLON) {
  44692. var FilterPostProcess = (function (_super) {
  44693. __extends(FilterPostProcess, _super);
  44694. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  44695. var _this = this;
  44696. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  44697. this.kernelMatrix = kernelMatrix;
  44698. this.onApply = function (effect) {
  44699. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  44700. };
  44701. }
  44702. return FilterPostProcess;
  44703. })(BABYLON.PostProcess);
  44704. BABYLON.FilterPostProcess = FilterPostProcess;
  44705. })(BABYLON || (BABYLON = {}));
  44706. var BABYLON;
  44707. (function (BABYLON) {
  44708. var FxaaPostProcess = (function (_super) {
  44709. __extends(FxaaPostProcess, _super);
  44710. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  44711. var _this = this;
  44712. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  44713. this.onSizeChangedObservable.add(function () {
  44714. _this.texelWidth = 1.0 / _this.width;
  44715. _this.texelHeight = 1.0 / _this.height;
  44716. });
  44717. this.onApplyObservable.add(function (effect) {
  44718. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  44719. });
  44720. }
  44721. return FxaaPostProcess;
  44722. })(BABYLON.PostProcess);
  44723. BABYLON.FxaaPostProcess = FxaaPostProcess;
  44724. })(BABYLON || (BABYLON = {}));
  44725. var BABYLON;
  44726. (function (BABYLON) {
  44727. var StereoscopicInterlacePostProcess = (function (_super) {
  44728. __extends(StereoscopicInterlacePostProcess, _super);
  44729. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  44730. var _this = this;
  44731. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  44732. this._passedProcess = rigCameras[0]._rigPostProcess;
  44733. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  44734. this.onSizeChangedObservable.add(function () {
  44735. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  44736. });
  44737. this.onApplyObservable.add(function (effect) {
  44738. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  44739. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  44740. });
  44741. }
  44742. return StereoscopicInterlacePostProcess;
  44743. })(BABYLON.PostProcess);
  44744. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  44745. })(BABYLON || (BABYLON = {}));
  44746. var BABYLON;
  44747. (function (BABYLON) {
  44748. var LensFlare = (function () {
  44749. function LensFlare(size, position, color, imgUrl, system) {
  44750. this.size = size;
  44751. this.position = position;
  44752. this.dispose = function () {
  44753. if (this.texture) {
  44754. this.texture.dispose();
  44755. }
  44756. // Remove from scene
  44757. var index = this._system.lensFlares.indexOf(this);
  44758. this._system.lensFlares.splice(index, 1);
  44759. };
  44760. this.color = color || new BABYLON.Color3(1, 1, 1);
  44761. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  44762. this._system = system;
  44763. system.lensFlares.push(this);
  44764. }
  44765. return LensFlare;
  44766. })();
  44767. BABYLON.LensFlare = LensFlare;
  44768. })(BABYLON || (BABYLON = {}));
  44769. var BABYLON;
  44770. (function (BABYLON) {
  44771. var LensFlareSystem = (function () {
  44772. function LensFlareSystem(name, emitter, scene) {
  44773. this.name = name;
  44774. this.lensFlares = new Array();
  44775. this.borderLimit = 300;
  44776. this.layerMask = 0x0FFFFFFF;
  44777. this._vertexDeclaration = [2];
  44778. this._vertexStrideSize = 2 * 4;
  44779. this._isEnabled = true;
  44780. this._scene = scene;
  44781. this._emitter = emitter;
  44782. this.id = name;
  44783. scene.lensFlareSystems.push(this);
  44784. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  44785. // VBO
  44786. var vertices = [];
  44787. vertices.push(1, 1);
  44788. vertices.push(-1, 1);
  44789. vertices.push(-1, -1);
  44790. vertices.push(1, -1);
  44791. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  44792. // Indices
  44793. var indices = [];
  44794. indices.push(0);
  44795. indices.push(1);
  44796. indices.push(2);
  44797. indices.push(0);
  44798. indices.push(2);
  44799. indices.push(3);
  44800. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44801. // Effects
  44802. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  44803. }
  44804. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  44805. get: function () {
  44806. return this._isEnabled;
  44807. },
  44808. set: function (value) {
  44809. this._isEnabled = value;
  44810. },
  44811. enumerable: true,
  44812. configurable: true
  44813. });
  44814. LensFlareSystem.prototype.getScene = function () {
  44815. return this._scene;
  44816. };
  44817. LensFlareSystem.prototype.getEmitter = function () {
  44818. return this._emitter;
  44819. };
  44820. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  44821. this._emitter = newEmitter;
  44822. };
  44823. LensFlareSystem.prototype.getEmitterPosition = function () {
  44824. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  44825. };
  44826. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  44827. var position = this.getEmitterPosition();
  44828. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  44829. this._positionX = position.x;
  44830. this._positionY = position.y;
  44831. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  44832. if (position.z > 0) {
  44833. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  44834. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  44835. return true;
  44836. }
  44837. }
  44838. return false;
  44839. };
  44840. LensFlareSystem.prototype._isVisible = function () {
  44841. if (!this._isEnabled) {
  44842. return false;
  44843. }
  44844. var emitterPosition = this.getEmitterPosition();
  44845. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  44846. var distance = direction.length();
  44847. direction.normalize();
  44848. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  44849. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44850. return !pickInfo.hit || pickInfo.distance > distance;
  44851. };
  44852. LensFlareSystem.prototype.render = function () {
  44853. if (!this._effect.isReady())
  44854. return false;
  44855. var engine = this._scene.getEngine();
  44856. var viewport = this._scene.activeCamera.viewport;
  44857. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44858. // Position
  44859. if (!this.computeEffectivePosition(globalViewport)) {
  44860. return false;
  44861. }
  44862. // Visibility
  44863. if (!this._isVisible()) {
  44864. return false;
  44865. }
  44866. // Intensity
  44867. var awayX;
  44868. var awayY;
  44869. if (this._positionX < this.borderLimit + globalViewport.x) {
  44870. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44871. }
  44872. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44873. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44874. }
  44875. else {
  44876. awayX = 0;
  44877. }
  44878. if (this._positionY < this.borderLimit + globalViewport.y) {
  44879. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44880. }
  44881. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44882. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44883. }
  44884. else {
  44885. awayY = 0;
  44886. }
  44887. var away = (awayX > awayY) ? awayX : awayY;
  44888. if (away > this.borderLimit) {
  44889. away = this.borderLimit;
  44890. }
  44891. var intensity = 1.0 - (away / this.borderLimit);
  44892. if (intensity < 0) {
  44893. return false;
  44894. }
  44895. if (intensity > 1.0) {
  44896. intensity = 1.0;
  44897. }
  44898. // Position
  44899. var centerX = globalViewport.x + globalViewport.width / 2;
  44900. var centerY = globalViewport.y + globalViewport.height / 2;
  44901. var distX = centerX - this._positionX;
  44902. var distY = centerY - this._positionY;
  44903. // Effects
  44904. engine.enableEffect(this._effect);
  44905. engine.setState(false);
  44906. engine.setDepthBuffer(false);
  44907. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44908. // VBOs
  44909. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  44910. // Flares
  44911. for (var index = 0; index < this.lensFlares.length; index++) {
  44912. var flare = this.lensFlares[index];
  44913. var x = centerX - (distX * flare.position);
  44914. var y = centerY - (distY * flare.position);
  44915. var cw = flare.size;
  44916. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44917. var cx = 2 * (x / globalViewport.width) - 1.0;
  44918. var cy = 1.0 - 2 * (y / globalViewport.height);
  44919. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44920. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44921. // Texture
  44922. this._effect.setTexture("textureSampler", flare.texture);
  44923. // Color
  44924. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44925. // Draw order
  44926. engine.draw(true, 0, 6);
  44927. }
  44928. engine.setDepthBuffer(true);
  44929. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44930. return true;
  44931. };
  44932. LensFlareSystem.prototype.dispose = function () {
  44933. if (this._vertexBuffer) {
  44934. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  44935. this._vertexBuffer = null;
  44936. }
  44937. if (this._indexBuffer) {
  44938. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44939. this._indexBuffer = null;
  44940. }
  44941. while (this.lensFlares.length) {
  44942. this.lensFlares[0].dispose();
  44943. }
  44944. // Remove from scene
  44945. var index = this._scene.lensFlareSystems.indexOf(this);
  44946. this._scene.lensFlareSystems.splice(index, 1);
  44947. };
  44948. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44949. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44950. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44951. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44952. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44953. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44954. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44955. var parsedFlare = parsedLensFlareSystem.flares[index];
  44956. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44957. }
  44958. return lensFlareSystem;
  44959. };
  44960. LensFlareSystem.prototype.serialize = function () {
  44961. var serializationObject = {};
  44962. serializationObject.id = this.id;
  44963. serializationObject.name = this.name;
  44964. serializationObject.emitterId = this.getEmitter().id;
  44965. serializationObject.borderLimit = this.borderLimit;
  44966. serializationObject.flares = [];
  44967. for (var index = 0; index < this.lensFlares.length; index++) {
  44968. var flare = this.lensFlares[index];
  44969. serializationObject.flares.push({
  44970. size: flare.size,
  44971. position: flare.position,
  44972. color: flare.color.asArray(),
  44973. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44974. });
  44975. }
  44976. return serializationObject;
  44977. };
  44978. return LensFlareSystem;
  44979. })();
  44980. BABYLON.LensFlareSystem = LensFlareSystem;
  44981. })(BABYLON || (BABYLON = {}));
  44982. var BABYLON;
  44983. (function (BABYLON) {
  44984. // We're mainly based on the logic defined into the FreeCamera code
  44985. var DeviceOrientationCamera = (function (_super) {
  44986. __extends(DeviceOrientationCamera, _super);
  44987. //-- end properties for backward compatibility for inputs
  44988. function DeviceOrientationCamera(name, position, scene) {
  44989. _super.call(this, name, position, scene);
  44990. this.inputs.addDeviceOrientation();
  44991. }
  44992. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  44993. //-- Begin properties for backward compatibility for inputs
  44994. get: function () {
  44995. return 0;
  44996. },
  44997. set: function (value) {
  44998. },
  44999. enumerable: true,
  45000. configurable: true
  45001. });
  45002. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  45003. get: function () {
  45004. return 0;
  45005. },
  45006. set: function (value) {
  45007. },
  45008. enumerable: true,
  45009. configurable: true
  45010. });
  45011. DeviceOrientationCamera.prototype.getTypeName = function () {
  45012. return "DeviceOrientationCamera";
  45013. };
  45014. return DeviceOrientationCamera;
  45015. })(BABYLON.FreeCamera);
  45016. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  45017. })(BABYLON || (BABYLON = {}));
  45018. var BABYLON;
  45019. (function (BABYLON) {
  45020. // We're mainly based on the logic defined into the FreeCamera code
  45021. var UniversalCamera = (function (_super) {
  45022. __extends(UniversalCamera, _super);
  45023. //-- end properties for backward compatibility for inputs
  45024. function UniversalCamera(name, position, scene) {
  45025. _super.call(this, name, position, scene);
  45026. this.inputs.addGamepad();
  45027. }
  45028. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  45029. //-- Begin properties for backward compatibility for inputs
  45030. get: function () {
  45031. var gamepad = this.inputs.attached["gamepad"];
  45032. if (gamepad)
  45033. return gamepad.gamepadAngularSensibility;
  45034. },
  45035. set: function (value) {
  45036. var gamepad = this.inputs.attached["gamepad"];
  45037. if (gamepad)
  45038. gamepad.gamepadAngularSensibility = value;
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  45044. get: function () {
  45045. var gamepad = this.inputs.attached["gamepad"];
  45046. if (gamepad)
  45047. return gamepad.gamepadMoveSensibility;
  45048. },
  45049. set: function (value) {
  45050. var gamepad = this.inputs.attached["gamepad"];
  45051. if (gamepad)
  45052. gamepad.gamepadMoveSensibility = value;
  45053. },
  45054. enumerable: true,
  45055. configurable: true
  45056. });
  45057. UniversalCamera.prototype.getTypeName = function () {
  45058. return "UniversalCamera";
  45059. };
  45060. return UniversalCamera;
  45061. })(BABYLON.TouchCamera);
  45062. BABYLON.UniversalCamera = UniversalCamera;
  45063. })(BABYLON || (BABYLON = {}));
  45064. var BABYLON;
  45065. (function (BABYLON) {
  45066. var Gamepads = (function () {
  45067. function Gamepads(ongamedpadconnected) {
  45068. var _this = this;
  45069. this.babylonGamepads = [];
  45070. this.oneGamepadConnected = false;
  45071. this.isMonitoring = false;
  45072. this.gamepadEventSupported = 'GamepadEvent' in window;
  45073. this.gamepadSupportAvailable = (navigator.getGamepads ||
  45074. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  45075. this._callbackGamepadConnected = ongamedpadconnected;
  45076. if (this.gamepadSupportAvailable) {
  45077. // Checking if the gamepad connected event is supported (like in Firefox)
  45078. if (this.gamepadEventSupported) {
  45079. this._onGamepadConnectedEvent = function (evt) {
  45080. _this._onGamepadConnected(evt);
  45081. };
  45082. this._onGamepadDisonnectedEvent = function (evt) {
  45083. _this._onGamepadDisconnected(evt);
  45084. };
  45085. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45086. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45087. }
  45088. else {
  45089. this._startMonitoringGamepads();
  45090. }
  45091. }
  45092. }
  45093. Gamepads.prototype.dispose = function () {
  45094. if (Gamepads.gamepadDOMInfo) {
  45095. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45096. }
  45097. if (this._onGamepadConnectedEvent) {
  45098. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45099. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45100. this._onGamepadConnectedEvent = null;
  45101. this._onGamepadDisonnectedEvent = null;
  45102. }
  45103. };
  45104. Gamepads.prototype._onGamepadConnected = function (evt) {
  45105. var newGamepad = this._addNewGamepad(evt.gamepad);
  45106. if (this._callbackGamepadConnected)
  45107. this._callbackGamepadConnected(newGamepad);
  45108. this._startMonitoringGamepads();
  45109. };
  45110. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45111. if (!this.oneGamepadConnected) {
  45112. this.oneGamepadConnected = true;
  45113. if (Gamepads.gamepadDOMInfo) {
  45114. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45115. Gamepads.gamepadDOMInfo = null;
  45116. }
  45117. }
  45118. var newGamepad;
  45119. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45120. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  45121. }
  45122. else {
  45123. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45124. }
  45125. this.babylonGamepads.push(newGamepad);
  45126. return newGamepad;
  45127. };
  45128. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45129. // Remove the gamepad from the list of gamepads to monitor.
  45130. for (var i in this.babylonGamepads) {
  45131. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45132. this.babylonGamepads.splice(+i, 1);
  45133. break;
  45134. }
  45135. }
  45136. // If no gamepads are left, stop the polling loop.
  45137. if (this.babylonGamepads.length == 0) {
  45138. this._stopMonitoringGamepads();
  45139. }
  45140. };
  45141. Gamepads.prototype._startMonitoringGamepads = function () {
  45142. if (!this.isMonitoring) {
  45143. this.isMonitoring = true;
  45144. this._checkGamepadsStatus();
  45145. }
  45146. };
  45147. Gamepads.prototype._stopMonitoringGamepads = function () {
  45148. this.isMonitoring = false;
  45149. };
  45150. Gamepads.prototype._checkGamepadsStatus = function () {
  45151. var _this = this;
  45152. // updating gamepad objects
  45153. this._updateGamepadObjects();
  45154. for (var i in this.babylonGamepads) {
  45155. this.babylonGamepads[i].update();
  45156. }
  45157. if (this.isMonitoring) {
  45158. if (window.requestAnimationFrame) {
  45159. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45160. }
  45161. else if (window.mozRequestAnimationFrame) {
  45162. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45163. }
  45164. else if (window.webkitRequestAnimationFrame) {
  45165. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45166. }
  45167. }
  45168. };
  45169. // This function is called only on Chrome, which does not yet support
  45170. // connection/disconnection events, but requires you to monitor
  45171. // an array for changes.
  45172. Gamepads.prototype._updateGamepadObjects = function () {
  45173. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45174. for (var i = 0; i < gamepads.length; i++) {
  45175. if (gamepads[i]) {
  45176. if (!(gamepads[i].index in this.babylonGamepads)) {
  45177. var newGamepad = this._addNewGamepad(gamepads[i]);
  45178. if (this._callbackGamepadConnected) {
  45179. this._callbackGamepadConnected(newGamepad);
  45180. }
  45181. }
  45182. else {
  45183. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45184. }
  45185. }
  45186. }
  45187. };
  45188. return Gamepads;
  45189. })();
  45190. BABYLON.Gamepads = Gamepads;
  45191. var StickValues = (function () {
  45192. function StickValues(x, y) {
  45193. this.x = x;
  45194. this.y = y;
  45195. }
  45196. return StickValues;
  45197. })();
  45198. BABYLON.StickValues = StickValues;
  45199. var Gamepad = (function () {
  45200. function Gamepad(id, index, browserGamepad) {
  45201. this.id = id;
  45202. this.index = index;
  45203. this.browserGamepad = browserGamepad;
  45204. if (this.browserGamepad.axes.length >= 2) {
  45205. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45206. }
  45207. if (this.browserGamepad.axes.length >= 4) {
  45208. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45209. }
  45210. }
  45211. Gamepad.prototype.onleftstickchanged = function (callback) {
  45212. this._onleftstickchanged = callback;
  45213. };
  45214. Gamepad.prototype.onrightstickchanged = function (callback) {
  45215. this._onrightstickchanged = callback;
  45216. };
  45217. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45218. get: function () {
  45219. return this._leftStick;
  45220. },
  45221. set: function (newValues) {
  45222. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45223. this._onleftstickchanged(newValues);
  45224. }
  45225. this._leftStick = newValues;
  45226. },
  45227. enumerable: true,
  45228. configurable: true
  45229. });
  45230. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45231. get: function () {
  45232. return this._rightStick;
  45233. },
  45234. set: function (newValues) {
  45235. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45236. this._onrightstickchanged(newValues);
  45237. }
  45238. this._rightStick = newValues;
  45239. },
  45240. enumerable: true,
  45241. configurable: true
  45242. });
  45243. Gamepad.prototype.update = function () {
  45244. if (this._leftStick) {
  45245. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45246. }
  45247. if (this._rightStick) {
  45248. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45249. }
  45250. };
  45251. return Gamepad;
  45252. })();
  45253. BABYLON.Gamepad = Gamepad;
  45254. var GenericPad = (function (_super) {
  45255. __extends(GenericPad, _super);
  45256. function GenericPad(id, index, gamepad) {
  45257. _super.call(this, id, index, gamepad);
  45258. this.id = id;
  45259. this.index = index;
  45260. this.gamepad = gamepad;
  45261. this._buttons = new Array(gamepad.buttons.length);
  45262. }
  45263. GenericPad.prototype.onbuttondown = function (callback) {
  45264. this._onbuttondown = callback;
  45265. };
  45266. GenericPad.prototype.onbuttonup = function (callback) {
  45267. this._onbuttonup = callback;
  45268. };
  45269. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45270. if (newValue !== currentValue) {
  45271. if (this._onbuttondown && newValue === 1) {
  45272. this._onbuttondown(buttonIndex);
  45273. }
  45274. if (this._onbuttonup && newValue === 0) {
  45275. this._onbuttonup(buttonIndex);
  45276. }
  45277. }
  45278. return newValue;
  45279. };
  45280. GenericPad.prototype.update = function () {
  45281. _super.prototype.update.call(this);
  45282. for (var index = 0; index < this._buttons.length; index++) {
  45283. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45284. }
  45285. };
  45286. return GenericPad;
  45287. })(Gamepad);
  45288. BABYLON.GenericPad = GenericPad;
  45289. (function (Xbox360Button) {
  45290. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45291. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45292. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45293. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45294. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45295. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45296. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45297. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45298. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45299. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45300. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45301. var Xbox360Button = BABYLON.Xbox360Button;
  45302. (function (Xbox360Dpad) {
  45303. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45304. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45305. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45306. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45307. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45308. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  45309. var Xbox360Pad = (function (_super) {
  45310. __extends(Xbox360Pad, _super);
  45311. function Xbox360Pad() {
  45312. _super.apply(this, arguments);
  45313. this._leftTrigger = 0;
  45314. this._rightTrigger = 0;
  45315. this._buttonA = 0;
  45316. this._buttonB = 0;
  45317. this._buttonX = 0;
  45318. this._buttonY = 0;
  45319. this._buttonBack = 0;
  45320. this._buttonStart = 0;
  45321. this._buttonLB = 0;
  45322. this._buttonRB = 0;
  45323. this._buttonLeftStick = 0;
  45324. this._buttonRightStick = 0;
  45325. this._dPadUp = 0;
  45326. this._dPadDown = 0;
  45327. this._dPadLeft = 0;
  45328. this._dPadRight = 0;
  45329. }
  45330. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45331. this._onlefttriggerchanged = callback;
  45332. };
  45333. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45334. this._onrighttriggerchanged = callback;
  45335. };
  45336. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45337. get: function () {
  45338. return this._leftTrigger;
  45339. },
  45340. set: function (newValue) {
  45341. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45342. this._onlefttriggerchanged(newValue);
  45343. }
  45344. this._leftTrigger = newValue;
  45345. },
  45346. enumerable: true,
  45347. configurable: true
  45348. });
  45349. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45350. get: function () {
  45351. return this._rightTrigger;
  45352. },
  45353. set: function (newValue) {
  45354. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45355. this._onrighttriggerchanged(newValue);
  45356. }
  45357. this._rightTrigger = newValue;
  45358. },
  45359. enumerable: true,
  45360. configurable: true
  45361. });
  45362. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45363. this._onbuttondown = callback;
  45364. };
  45365. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45366. this._onbuttonup = callback;
  45367. };
  45368. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45369. this._ondpaddown = callback;
  45370. };
  45371. Xbox360Pad.prototype.ondpadup = function (callback) {
  45372. this._ondpadup = callback;
  45373. };
  45374. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45375. if (newValue !== currentValue) {
  45376. if (this._onbuttondown && newValue === 1) {
  45377. this._onbuttondown(buttonType);
  45378. }
  45379. if (this._onbuttonup && newValue === 0) {
  45380. this._onbuttonup(buttonType);
  45381. }
  45382. }
  45383. return newValue;
  45384. };
  45385. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45386. if (newValue !== currentValue) {
  45387. if (this._ondpaddown && newValue === 1) {
  45388. this._ondpaddown(buttonType);
  45389. }
  45390. if (this._ondpadup && newValue === 0) {
  45391. this._ondpadup(buttonType);
  45392. }
  45393. }
  45394. return newValue;
  45395. };
  45396. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45397. get: function () {
  45398. return this._buttonA;
  45399. },
  45400. set: function (value) {
  45401. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45402. },
  45403. enumerable: true,
  45404. configurable: true
  45405. });
  45406. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45407. get: function () {
  45408. return this._buttonB;
  45409. },
  45410. set: function (value) {
  45411. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45412. },
  45413. enumerable: true,
  45414. configurable: true
  45415. });
  45416. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45417. get: function () {
  45418. return this._buttonX;
  45419. },
  45420. set: function (value) {
  45421. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45427. get: function () {
  45428. return this._buttonY;
  45429. },
  45430. set: function (value) {
  45431. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45432. },
  45433. enumerable: true,
  45434. configurable: true
  45435. });
  45436. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45437. get: function () {
  45438. return this._buttonStart;
  45439. },
  45440. set: function (value) {
  45441. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45442. },
  45443. enumerable: true,
  45444. configurable: true
  45445. });
  45446. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45447. get: function () {
  45448. return this._buttonBack;
  45449. },
  45450. set: function (value) {
  45451. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45452. },
  45453. enumerable: true,
  45454. configurable: true
  45455. });
  45456. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45457. get: function () {
  45458. return this._buttonLB;
  45459. },
  45460. set: function (value) {
  45461. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45462. },
  45463. enumerable: true,
  45464. configurable: true
  45465. });
  45466. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45467. get: function () {
  45468. return this._buttonRB;
  45469. },
  45470. set: function (value) {
  45471. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45472. },
  45473. enumerable: true,
  45474. configurable: true
  45475. });
  45476. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45477. get: function () {
  45478. return this._buttonLeftStick;
  45479. },
  45480. set: function (value) {
  45481. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45482. },
  45483. enumerable: true,
  45484. configurable: true
  45485. });
  45486. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45487. get: function () {
  45488. return this._buttonRightStick;
  45489. },
  45490. set: function (value) {
  45491. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45492. },
  45493. enumerable: true,
  45494. configurable: true
  45495. });
  45496. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45497. get: function () {
  45498. return this._dPadUp;
  45499. },
  45500. set: function (value) {
  45501. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45502. },
  45503. enumerable: true,
  45504. configurable: true
  45505. });
  45506. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45507. get: function () {
  45508. return this._dPadDown;
  45509. },
  45510. set: function (value) {
  45511. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45512. },
  45513. enumerable: true,
  45514. configurable: true
  45515. });
  45516. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45517. get: function () {
  45518. return this._dPadLeft;
  45519. },
  45520. set: function (value) {
  45521. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45522. },
  45523. enumerable: true,
  45524. configurable: true
  45525. });
  45526. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45527. get: function () {
  45528. return this._dPadRight;
  45529. },
  45530. set: function (value) {
  45531. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45532. },
  45533. enumerable: true,
  45534. configurable: true
  45535. });
  45536. Xbox360Pad.prototype.update = function () {
  45537. _super.prototype.update.call(this);
  45538. this.buttonA = this.browserGamepad.buttons[0].value;
  45539. this.buttonB = this.browserGamepad.buttons[1].value;
  45540. this.buttonX = this.browserGamepad.buttons[2].value;
  45541. this.buttonY = this.browserGamepad.buttons[3].value;
  45542. this.buttonLB = this.browserGamepad.buttons[4].value;
  45543. this.buttonRB = this.browserGamepad.buttons[5].value;
  45544. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45545. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45546. this.buttonBack = this.browserGamepad.buttons[8].value;
  45547. this.buttonStart = this.browserGamepad.buttons[9].value;
  45548. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45549. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45550. this.dPadUp = this.browserGamepad.buttons[12].value;
  45551. this.dPadDown = this.browserGamepad.buttons[13].value;
  45552. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45553. this.dPadRight = this.browserGamepad.buttons[15].value;
  45554. };
  45555. return Xbox360Pad;
  45556. })(Gamepad);
  45557. BABYLON.Xbox360Pad = Xbox360Pad;
  45558. })(BABYLON || (BABYLON = {}));
  45559. var BABYLON;
  45560. (function (BABYLON) {
  45561. // We're mainly based on the logic defined into the FreeCamera code
  45562. var GamepadCamera = (function (_super) {
  45563. __extends(GamepadCamera, _super);
  45564. //-- end properties for backward compatibility for inputs
  45565. function GamepadCamera(name, position, scene) {
  45566. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  45567. _super.call(this, name, position, scene);
  45568. }
  45569. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45570. //-- Begin properties for backward compatibility for inputs
  45571. get: function () {
  45572. var gamepad = this.inputs.attached["gamepad"];
  45573. if (gamepad)
  45574. return gamepad.gamepadAngularSensibility;
  45575. },
  45576. set: function (value) {
  45577. var gamepad = this.inputs.attached["gamepad"];
  45578. if (gamepad)
  45579. gamepad.gamepadAngularSensibility = value;
  45580. },
  45581. enumerable: true,
  45582. configurable: true
  45583. });
  45584. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45585. get: function () {
  45586. var gamepad = this.inputs.attached["gamepad"];
  45587. if (gamepad)
  45588. return gamepad.gamepadMoveSensibility;
  45589. },
  45590. set: function (value) {
  45591. var gamepad = this.inputs.attached["gamepad"];
  45592. if (gamepad)
  45593. gamepad.gamepadMoveSensibility = value;
  45594. },
  45595. enumerable: true,
  45596. configurable: true
  45597. });
  45598. GamepadCamera.prototype.getTypeName = function () {
  45599. return "GamepadCamera";
  45600. };
  45601. return GamepadCamera;
  45602. })(BABYLON.UniversalCamera);
  45603. BABYLON.GamepadCamera = GamepadCamera;
  45604. })(BABYLON || (BABYLON = {}));
  45605. var BABYLON;
  45606. (function (BABYLON) {
  45607. var Analyser = (function () {
  45608. function Analyser(scene) {
  45609. this.SMOOTHING = 0.75;
  45610. this.FFT_SIZE = 512;
  45611. this.BARGRAPHAMPLITUDE = 256;
  45612. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45613. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45614. this._scene = scene;
  45615. this._audioEngine = BABYLON.Engine.audioEngine;
  45616. if (this._audioEngine.canUseWebAudio) {
  45617. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45618. this._webAudioAnalyser.minDecibels = -140;
  45619. this._webAudioAnalyser.maxDecibels = 0;
  45620. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45621. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45622. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45623. }
  45624. }
  45625. Analyser.prototype.getFrequencyBinCount = function () {
  45626. if (this._audioEngine.canUseWebAudio) {
  45627. return this._webAudioAnalyser.frequencyBinCount;
  45628. }
  45629. else {
  45630. return 0;
  45631. }
  45632. };
  45633. Analyser.prototype.getByteFrequencyData = function () {
  45634. if (this._audioEngine.canUseWebAudio) {
  45635. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45636. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45637. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45638. }
  45639. return this._byteFreqs;
  45640. };
  45641. Analyser.prototype.getByteTimeDomainData = function () {
  45642. if (this._audioEngine.canUseWebAudio) {
  45643. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45644. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45645. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45646. }
  45647. return this._byteTime;
  45648. };
  45649. Analyser.prototype.getFloatFrequencyData = function () {
  45650. if (this._audioEngine.canUseWebAudio) {
  45651. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45652. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45653. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45654. }
  45655. return this._floatFreqs;
  45656. };
  45657. Analyser.prototype.drawDebugCanvas = function () {
  45658. var _this = this;
  45659. if (this._audioEngine.canUseWebAudio) {
  45660. if (!this._debugCanvas) {
  45661. this._debugCanvas = document.createElement("canvas");
  45662. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45663. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45664. this._debugCanvas.style.position = "absolute";
  45665. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45666. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45667. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45668. document.body.appendChild(this._debugCanvas);
  45669. this._registerFunc = function () {
  45670. _this.drawDebugCanvas();
  45671. };
  45672. this._scene.registerBeforeRender(this._registerFunc);
  45673. }
  45674. if (this._registerFunc) {
  45675. var workingArray = this.getByteFrequencyData();
  45676. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45677. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45678. // Draw the frequency domain chart.
  45679. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45680. var value = workingArray[i];
  45681. var percent = value / this.BARGRAPHAMPLITUDE;
  45682. var height = this.DEBUGCANVASSIZE.height * percent;
  45683. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45684. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45685. var hue = i / this.getFrequencyBinCount() * 360;
  45686. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45687. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45688. }
  45689. }
  45690. }
  45691. };
  45692. Analyser.prototype.stopDebugCanvas = function () {
  45693. if (this._debugCanvas) {
  45694. this._scene.unregisterBeforeRender(this._registerFunc);
  45695. this._registerFunc = null;
  45696. document.body.removeChild(this._debugCanvas);
  45697. this._debugCanvas = null;
  45698. this._debugCanvasContext = null;
  45699. }
  45700. };
  45701. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45702. if (this._audioEngine.canUseWebAudio) {
  45703. inputAudioNode.connect(this._webAudioAnalyser);
  45704. this._webAudioAnalyser.connect(outputAudioNode);
  45705. }
  45706. };
  45707. Analyser.prototype.dispose = function () {
  45708. if (this._audioEngine.canUseWebAudio) {
  45709. this._webAudioAnalyser.disconnect();
  45710. }
  45711. };
  45712. return Analyser;
  45713. })();
  45714. BABYLON.Analyser = Analyser;
  45715. })(BABYLON || (BABYLON = {}));
  45716. var BABYLON;
  45717. (function (BABYLON) {
  45718. var DepthRenderer = (function () {
  45719. function DepthRenderer(scene, type) {
  45720. var _this = this;
  45721. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45722. this._viewMatrix = BABYLON.Matrix.Zero();
  45723. this._projectionMatrix = BABYLON.Matrix.Zero();
  45724. this._transformMatrix = BABYLON.Matrix.Zero();
  45725. this._worldViewProjection = BABYLON.Matrix.Zero();
  45726. this._scene = scene;
  45727. var engine = scene.getEngine();
  45728. // Render target
  45729. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45730. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45731. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45732. this._depthMap.refreshRate = 1;
  45733. this._depthMap.renderParticles = false;
  45734. this._depthMap.renderList = null;
  45735. // set default depth value to 1.0 (far away)
  45736. this._depthMap.onClearObservable.add(function (engine) {
  45737. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  45738. });
  45739. // Custom render function
  45740. var renderSubMesh = function (subMesh) {
  45741. var mesh = subMesh.getRenderingMesh();
  45742. var scene = _this._scene;
  45743. var engine = scene.getEngine();
  45744. // Culling
  45745. engine.setState(subMesh.getMaterial().backFaceCulling);
  45746. // Managing instances
  45747. var batch = mesh._getInstancesRenderList(subMesh._id);
  45748. if (batch.mustReturn) {
  45749. return;
  45750. }
  45751. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45752. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45753. engine.enableEffect(_this._effect);
  45754. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45755. var material = subMesh.getMaterial();
  45756. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45757. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45758. // Alpha test
  45759. if (material && material.needAlphaTesting()) {
  45760. var alphaTexture = material.getAlphaTestTexture();
  45761. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45762. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45763. }
  45764. // Bones
  45765. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45766. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45767. }
  45768. // Draw
  45769. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45770. }
  45771. };
  45772. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45773. var index;
  45774. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45775. renderSubMesh(opaqueSubMeshes.data[index]);
  45776. }
  45777. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45778. renderSubMesh(alphaTestSubMeshes.data[index]);
  45779. }
  45780. };
  45781. }
  45782. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45783. var material = subMesh.getMaterial();
  45784. if (material.disableDepthWrite) {
  45785. return false;
  45786. }
  45787. var defines = [];
  45788. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45789. var mesh = subMesh.getMesh();
  45790. var scene = mesh.getScene();
  45791. // Alpha test
  45792. if (material && material.needAlphaTesting()) {
  45793. defines.push("#define ALPHATEST");
  45794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45795. attribs.push(BABYLON.VertexBuffer.UVKind);
  45796. defines.push("#define UV1");
  45797. }
  45798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45799. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45800. defines.push("#define UV2");
  45801. }
  45802. }
  45803. // Bones
  45804. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45805. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45806. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45807. if (mesh.numBoneInfluencers > 4) {
  45808. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45809. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45810. }
  45811. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45812. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45813. }
  45814. else {
  45815. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45816. }
  45817. // Instances
  45818. if (useInstances) {
  45819. defines.push("#define INSTANCES");
  45820. attribs.push("world0");
  45821. attribs.push("world1");
  45822. attribs.push("world2");
  45823. attribs.push("world3");
  45824. }
  45825. // Get correct effect
  45826. var join = defines.join("\n");
  45827. if (this._cachedDefines !== join) {
  45828. this._cachedDefines = join;
  45829. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45830. }
  45831. return this._effect.isReady();
  45832. };
  45833. DepthRenderer.prototype.getDepthMap = function () {
  45834. return this._depthMap;
  45835. };
  45836. // Methods
  45837. DepthRenderer.prototype.dispose = function () {
  45838. this._depthMap.dispose();
  45839. };
  45840. return DepthRenderer;
  45841. })();
  45842. BABYLON.DepthRenderer = DepthRenderer;
  45843. })(BABYLON || (BABYLON = {}));
  45844. var BABYLON;
  45845. (function (BABYLON) {
  45846. var SSAORenderingPipeline = (function (_super) {
  45847. __extends(SSAORenderingPipeline, _super);
  45848. /**
  45849. * @constructor
  45850. * @param {string} name - The rendering pipeline name
  45851. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45852. * @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 }
  45853. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45854. */
  45855. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45856. var _this = this;
  45857. _super.call(this, scene.getEngine(), name);
  45858. // Members
  45859. /**
  45860. * The PassPostProcess id in the pipeline that contains the original scene color
  45861. * @type {string}
  45862. */
  45863. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45864. /**
  45865. * The SSAO PostProcess id in the pipeline
  45866. * @type {string}
  45867. */
  45868. this.SSAORenderEffect = "SSAORenderEffect";
  45869. /**
  45870. * The horizontal blur PostProcess id in the pipeline
  45871. * @type {string}
  45872. */
  45873. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45874. /**
  45875. * The vertical blur PostProcess id in the pipeline
  45876. * @type {string}
  45877. */
  45878. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45879. /**
  45880. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45881. * @type {string}
  45882. */
  45883. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45884. /**
  45885. * The output strength of the SSAO post-process. Default value is 1.0.
  45886. * @type {number}
  45887. */
  45888. this.totalStrength = 1.0;
  45889. /**
  45890. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45891. * @type {number}
  45892. */
  45893. this.radius = 0.0001;
  45894. /**
  45895. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45896. * Must not be equal to fallOff and superior to fallOff.
  45897. * Default value is 0.975
  45898. * @type {number}
  45899. */
  45900. this.area = 0.0075;
  45901. /**
  45902. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45903. * Must not be equal to area and inferior to area.
  45904. * Default value is 0.0
  45905. * @type {number}
  45906. */
  45907. this.fallOff = 0.000001;
  45908. /**
  45909. * The base color of the SSAO post-process
  45910. * The final result is "base + ssao" between [0, 1]
  45911. * @type {number}
  45912. */
  45913. this.base = 0.5;
  45914. this._firstUpdate = true;
  45915. this._scene = scene;
  45916. // Set up assets
  45917. this._createRandomTexture();
  45918. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45919. var ssaoRatio = ratio.ssaoRatio || ratio;
  45920. var combineRatio = ratio.combineRatio || ratio;
  45921. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45922. this._createSSAOPostProcess(ssaoRatio);
  45923. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45924. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45925. this._createSSAOCombinePostProcess(combineRatio);
  45926. // Set up pipeline
  45927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45930. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45931. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45932. // Finish
  45933. scene.postProcessRenderPipelineManager.addPipeline(this);
  45934. if (cameras)
  45935. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45936. }
  45937. // Public Methods
  45938. /**
  45939. * Returns the horizontal blur PostProcess
  45940. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45941. */
  45942. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45943. return this._blurHPostProcess;
  45944. };
  45945. /**
  45946. * Returns the vertical blur PostProcess
  45947. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45948. */
  45949. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45950. return this._blurVPostProcess;
  45951. };
  45952. /**
  45953. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45954. */
  45955. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45956. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45957. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45958. this._originalColorPostProcess = undefined;
  45959. this._ssaoPostProcess = undefined;
  45960. this._blurHPostProcess = undefined;
  45961. this._blurVPostProcess = undefined;
  45962. this._ssaoCombinePostProcess = undefined;
  45963. this._randomTexture.dispose();
  45964. if (disableDepthRender)
  45965. this._scene.disableDepthRenderer();
  45966. };
  45967. // Private Methods
  45968. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  45969. var _this = this;
  45970. var numSamples = 16;
  45971. var sampleSphere = [
  45972. 0.5381, 0.1856, -0.4319,
  45973. 0.1379, 0.2486, 0.4430,
  45974. 0.3371, 0.5679, -0.0057,
  45975. -0.6999, -0.0451, -0.0019,
  45976. 0.0689, -0.1598, -0.8547,
  45977. 0.0560, 0.0069, -0.1843,
  45978. -0.0146, 0.1402, 0.0762,
  45979. 0.0100, -0.1924, -0.0344,
  45980. -0.3577, -0.5301, -0.4358,
  45981. -0.3169, 0.1063, 0.0158,
  45982. 0.0103, -0.5869, 0.0046,
  45983. -0.0897, -0.4940, 0.3287,
  45984. 0.7119, -0.0154, -0.0918,
  45985. -0.0533, 0.0596, -0.5411,
  45986. 0.0352, -0.0631, 0.5460,
  45987. -0.4776, 0.2847, -0.0271
  45988. ];
  45989. var samplesFactor = 1.0 / numSamples;
  45990. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  45991. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  45992. "area", "fallOff", "base"
  45993. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  45994. this._ssaoPostProcess.onApply = function (effect) {
  45995. if (_this._firstUpdate) {
  45996. effect.setArray3("sampleSphere", sampleSphere);
  45997. effect.setFloat("samplesFactor", samplesFactor);
  45998. effect.setFloat("randTextureTiles", 4.0);
  45999. _this._firstUpdate = false;
  46000. }
  46001. effect.setFloat("totalStrength", _this.totalStrength);
  46002. effect.setFloat("radius", _this.radius);
  46003. effect.setFloat("area", _this.area);
  46004. effect.setFloat("fallOff", _this.fallOff);
  46005. effect.setFloat("base", _this.base);
  46006. effect.setTexture("textureSampler", _this._depthTexture);
  46007. effect.setTexture("randomSampler", _this._randomTexture);
  46008. };
  46009. };
  46010. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46011. var _this = this;
  46012. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46013. this._ssaoCombinePostProcess.onApply = function (effect) {
  46014. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46015. };
  46016. };
  46017. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46018. var size = 512;
  46019. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46020. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46021. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46022. var context = this._randomTexture.getContext();
  46023. var rand = function (min, max) {
  46024. return Math.random() * (max - min) + min;
  46025. };
  46026. var randVector = BABYLON.Vector3.Zero();
  46027. for (var x = 0; x < size; x++) {
  46028. for (var y = 0; y < size; y++) {
  46029. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46030. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46031. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46032. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46033. context.fillRect(x, y, 1, 1);
  46034. }
  46035. }
  46036. this._randomTexture.update(false);
  46037. };
  46038. return SSAORenderingPipeline;
  46039. })(BABYLON.PostProcessRenderPipeline);
  46040. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46041. })(BABYLON || (BABYLON = {}));
  46042. var BABYLON;
  46043. (function (BABYLON) {
  46044. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  46045. var VolumetricLightScatteringPostProcess = (function (_super) {
  46046. __extends(VolumetricLightScatteringPostProcess, _super);
  46047. /**
  46048. * @constructor
  46049. * @param {string} name - The post-process name
  46050. * @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)
  46051. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  46052. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  46053. * @param {number} samples - The post-process quality, default 100
  46054. * @param {number} samplingMode - The post-process filtering mode
  46055. * @param {BABYLON.Engine} engine - The babylon engine
  46056. * @param {boolean} reusable - If the post-process is reusable
  46057. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  46058. */
  46059. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  46060. var _this = this;
  46061. if (samples === void 0) { samples = 100; }
  46062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46063. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  46064. this._screenCoordinates = BABYLON.Vector2.Zero();
  46065. /**
  46066. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  46067. * @type {Vector3}
  46068. */
  46069. this.customMeshPosition = BABYLON.Vector3.Zero();
  46070. /**
  46071. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  46072. * @type {boolean}
  46073. */
  46074. this.useCustomMeshPosition = false;
  46075. /**
  46076. * If the post-process should inverse the light scattering direction
  46077. * @type {boolean}
  46078. */
  46079. this.invert = true;
  46080. /**
  46081. * Array containing the excluded meshes not rendered in the internal pass
  46082. */
  46083. this.excludedMeshes = new Array();
  46084. /**
  46085. * Controls the overall intensity of the post-process
  46086. * @type {number}
  46087. */
  46088. this.exposure = 0.3;
  46089. /**
  46090. * Dissipates each sample's contribution in range [0, 1]
  46091. * @type {number}
  46092. */
  46093. this.decay = 0.96815;
  46094. /**
  46095. * Controls the overall intensity of each sample
  46096. * @type {number}
  46097. */
  46098. this.weight = 0.58767;
  46099. /**
  46100. * Controls the density of each sample
  46101. * @type {number}
  46102. */
  46103. this.density = 0.926;
  46104. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  46105. var engine = scene.getEngine();
  46106. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46107. // Configure mesh
  46108. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  46109. // Configure
  46110. this._createPass(scene, ratio.passRatio || ratio);
  46111. this.onActivate = function (camera) {
  46112. if (!_this.isSupported) {
  46113. _this.dispose(camera);
  46114. }
  46115. _this.onActivate = null;
  46116. };
  46117. this.onApplyObservable.add(function (effect) {
  46118. _this._updateMeshScreenCoordinates(scene);
  46119. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  46120. effect.setFloat("exposure", _this.exposure);
  46121. effect.setFloat("decay", _this.decay);
  46122. effect.setFloat("weight", _this.weight);
  46123. effect.setFloat("density", _this.density);
  46124. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  46125. });
  46126. }
  46127. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  46128. get: function () {
  46129. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46130. return false;
  46131. },
  46132. set: function (useDiffuseColor) {
  46133. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46134. },
  46135. enumerable: true,
  46136. configurable: true
  46137. });
  46138. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  46139. var mesh = subMesh.getMesh();
  46140. // Render this.mesh as default
  46141. if (mesh === this.mesh) {
  46142. return mesh.material.isReady(mesh);
  46143. }
  46144. var defines = [];
  46145. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46146. var material = subMesh.getMaterial();
  46147. var needUV = false;
  46148. // Alpha test
  46149. if (material) {
  46150. if (material.needAlphaTesting()) {
  46151. defines.push("#define ALPHATEST");
  46152. }
  46153. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46154. attribs.push(BABYLON.VertexBuffer.UVKind);
  46155. defines.push("#define UV1");
  46156. }
  46157. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46158. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46159. defines.push("#define UV2");
  46160. }
  46161. }
  46162. // Bones
  46163. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46164. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46165. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46166. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46167. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46168. }
  46169. else {
  46170. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46171. }
  46172. // Instances
  46173. if (useInstances) {
  46174. defines.push("#define INSTANCES");
  46175. attribs.push("world0");
  46176. attribs.push("world1");
  46177. attribs.push("world2");
  46178. attribs.push("world3");
  46179. }
  46180. // Get correct effect
  46181. var join = defines.join("\n");
  46182. if (this._cachedDefines !== join) {
  46183. this._cachedDefines = join;
  46184. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  46185. }
  46186. return this._volumetricLightScatteringPass.isReady();
  46187. };
  46188. /**
  46189. * Sets the new light position for light scattering effect
  46190. * @param {BABYLON.Vector3} The new custom light position
  46191. */
  46192. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  46193. this.customMeshPosition = position;
  46194. };
  46195. /**
  46196. * Returns the light position for light scattering effect
  46197. * @return {BABYLON.Vector3} The custom light position
  46198. */
  46199. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  46200. return this.customMeshPosition;
  46201. };
  46202. /**
  46203. * Disposes the internal assets and detaches the post-process from the camera
  46204. */
  46205. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  46206. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  46207. if (rttIndex !== -1) {
  46208. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  46209. }
  46210. this._volumetricLightScatteringRTT.dispose();
  46211. _super.prototype.dispose.call(this, camera);
  46212. };
  46213. /**
  46214. * Returns the render target texture used by the post-process
  46215. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  46216. */
  46217. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  46218. return this._volumetricLightScatteringRTT;
  46219. };
  46220. // Private methods
  46221. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  46222. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  46223. return true;
  46224. }
  46225. return false;
  46226. };
  46227. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  46228. var _this = this;
  46229. var engine = scene.getEngine();
  46230. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  46231. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46232. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46233. this._volumetricLightScatteringRTT.renderList = null;
  46234. this._volumetricLightScatteringRTT.renderParticles = false;
  46235. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  46236. // Custom render function for submeshes
  46237. var renderSubMesh = function (subMesh) {
  46238. var mesh = subMesh.getRenderingMesh();
  46239. if (_this._meshExcluded(mesh)) {
  46240. return;
  46241. }
  46242. var scene = mesh.getScene();
  46243. var engine = scene.getEngine();
  46244. // Culling
  46245. engine.setState(subMesh.getMaterial().backFaceCulling);
  46246. // Managing instances
  46247. var batch = mesh._getInstancesRenderList(subMesh._id);
  46248. if (batch.mustReturn) {
  46249. return;
  46250. }
  46251. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46252. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46253. var effect = _this._volumetricLightScatteringPass;
  46254. if (mesh === _this.mesh) {
  46255. effect = subMesh.getMaterial().getEffect();
  46256. }
  46257. engine.enableEffect(effect);
  46258. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  46259. if (mesh === _this.mesh) {
  46260. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  46261. }
  46262. else {
  46263. var material = subMesh.getMaterial();
  46264. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  46265. // Alpha test
  46266. if (material && material.needAlphaTesting()) {
  46267. var alphaTexture = material.getAlphaTestTexture();
  46268. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  46269. if (alphaTexture) {
  46270. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46271. }
  46272. }
  46273. // Bones
  46274. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46275. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46276. }
  46277. }
  46278. // Draw
  46279. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  46280. }
  46281. };
  46282. // Render target texture callbacks
  46283. var savedSceneClearColor;
  46284. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  46285. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  46286. savedSceneClearColor = scene.clearColor;
  46287. scene.clearColor = sceneClearColor;
  46288. });
  46289. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  46290. scene.clearColor = savedSceneClearColor;
  46291. });
  46292. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46293. var engine = scene.getEngine();
  46294. var index;
  46295. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46296. renderSubMesh(opaqueSubMeshes.data[index]);
  46297. }
  46298. engine.setAlphaTesting(true);
  46299. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46300. renderSubMesh(alphaTestSubMeshes.data[index]);
  46301. }
  46302. engine.setAlphaTesting(false);
  46303. if (transparentSubMeshes.length) {
  46304. // Sort sub meshes
  46305. for (index = 0; index < transparentSubMeshes.length; index++) {
  46306. var submesh = transparentSubMeshes.data[index];
  46307. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  46308. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  46309. }
  46310. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  46311. sortedArray.sort(function (a, b) {
  46312. // Alpha index first
  46313. if (a._alphaIndex > b._alphaIndex) {
  46314. return 1;
  46315. }
  46316. if (a._alphaIndex < b._alphaIndex) {
  46317. return -1;
  46318. }
  46319. // Then distance to camera
  46320. if (a._distanceToCamera < b._distanceToCamera) {
  46321. return 1;
  46322. }
  46323. if (a._distanceToCamera > b._distanceToCamera) {
  46324. return -1;
  46325. }
  46326. return 0;
  46327. });
  46328. // Render sub meshes
  46329. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46330. for (index = 0; index < sortedArray.length; index++) {
  46331. renderSubMesh(sortedArray[index]);
  46332. }
  46333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46334. }
  46335. };
  46336. };
  46337. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  46338. var transform = scene.getTransformMatrix();
  46339. var meshPosition;
  46340. if (this.useCustomMeshPosition) {
  46341. meshPosition = this.customMeshPosition;
  46342. }
  46343. else if (this.attachedNode) {
  46344. meshPosition = this.attachedNode.position;
  46345. }
  46346. else {
  46347. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  46348. }
  46349. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  46350. this._screenCoordinates.x = pos.x / this._viewPort.width;
  46351. this._screenCoordinates.y = pos.y / this._viewPort.height;
  46352. if (this.invert)
  46353. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  46354. };
  46355. // Static methods
  46356. /**
  46357. * Creates a default mesh for the Volumeric Light Scattering post-process
  46358. * @param {string} The mesh name
  46359. * @param {BABYLON.Scene} The scene where to create the mesh
  46360. * @return {BABYLON.Mesh} the default mesh
  46361. */
  46362. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  46363. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  46364. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  46365. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  46366. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  46367. mesh.material = material;
  46368. return mesh;
  46369. };
  46370. __decorate([
  46371. BABYLON.serializeAsVector3()
  46372. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  46373. __decorate([
  46374. BABYLON.serialize()
  46375. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  46376. __decorate([
  46377. BABYLON.serialize()
  46378. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  46379. __decorate([
  46380. BABYLON.serializeAsMeshReference()
  46381. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  46382. __decorate([
  46383. BABYLON.serialize()
  46384. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  46385. __decorate([
  46386. BABYLON.serialize()
  46387. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  46388. __decorate([
  46389. BABYLON.serialize()
  46390. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  46391. __decorate([
  46392. BABYLON.serialize()
  46393. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  46394. __decorate([
  46395. BABYLON.serialize()
  46396. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  46397. return VolumetricLightScatteringPostProcess;
  46398. })(BABYLON.PostProcess);
  46399. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  46400. })(BABYLON || (BABYLON = {}));
  46401. // BABYLON.JS Chromatic Aberration GLSL Shader
  46402. // Author: Olivier Guyot
  46403. // Separates very slightly R, G and B colors on the edges of the screen
  46404. // Inspired by Francois Tarlier & Martins Upitis
  46405. var BABYLON;
  46406. (function (BABYLON) {
  46407. var LensRenderingPipeline = (function (_super) {
  46408. __extends(LensRenderingPipeline, _super);
  46409. /**
  46410. * @constructor
  46411. *
  46412. * Effect parameters are as follow:
  46413. * {
  46414. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46415. * edge_blur: number; // from 0 to x (1 for realism)
  46416. * distortion: number; // from 0 to x (1 for realism)
  46417. * grain_amount: number; // from 0 to 1
  46418. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46419. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46420. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46421. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46422. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46423. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46424. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46425. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46426. * }
  46427. * Note: if an effect parameter is unset, effect is disabled
  46428. *
  46429. * @param {string} name - The rendering pipeline name
  46430. * @param {object} parameters - An object containing all parameters (see above)
  46431. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46432. * @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)
  46433. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46434. */
  46435. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46436. var _this = this;
  46437. if (ratio === void 0) { ratio = 1.0; }
  46438. _super.call(this, scene.getEngine(), name);
  46439. // Lens effects can be of the following:
  46440. // - chromatic aberration (slight shift of RGB colors)
  46441. // - blur on the edge of the lens
  46442. // - lens distortion
  46443. // - depth-of-field blur & highlights enhancing
  46444. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46445. // - grain effect (noise or custom texture)
  46446. // Two additional texture samplers are needed:
  46447. // - depth map (for depth-of-field)
  46448. // - grain texture
  46449. /**
  46450. * The chromatic aberration PostProcess id in the pipeline
  46451. * @type {string}
  46452. */
  46453. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46454. /**
  46455. * The highlights enhancing PostProcess id in the pipeline
  46456. * @type {string}
  46457. */
  46458. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46459. /**
  46460. * The depth-of-field PostProcess id in the pipeline
  46461. * @type {string}
  46462. */
  46463. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46464. this._scene = scene;
  46465. // Fetch texture samplers
  46466. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46467. if (parameters.grain_texture) {
  46468. this._grainTexture = parameters.grain_texture;
  46469. }
  46470. else {
  46471. this._createGrainTexture();
  46472. }
  46473. // save parameters
  46474. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46475. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46476. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46477. this._distortion = parameters.distortion ? parameters.distortion : 0;
  46478. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46479. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46480. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46481. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46482. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46483. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46484. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46485. // Create effects
  46486. this._createChromaticAberrationPostProcess(ratio);
  46487. this._createHighlightsPostProcess(ratio);
  46488. this._createDepthOfFieldPostProcess(ratio / 4);
  46489. // Set up pipeline
  46490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46493. if (this._highlightsGain === -1) {
  46494. this._disableEffect(this.HighlightsEnhancingEffect, null);
  46495. }
  46496. // Finish
  46497. scene.postProcessRenderPipelineManager.addPipeline(this);
  46498. if (cameras) {
  46499. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46500. }
  46501. }
  46502. // public methods (self explanatory)
  46503. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46504. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46505. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46506. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46507. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46508. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46509. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46510. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46511. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46512. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46513. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46514. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46515. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46516. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46517. };
  46518. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46519. this._highlightsPostProcess.updateEffect();
  46520. };
  46521. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46522. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46523. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46524. this._highlightsGain = amount;
  46525. };
  46526. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46527. if (this._highlightsGain === -1) {
  46528. this._highlightsGain = 1.0;
  46529. }
  46530. this._highlightsThreshold = amount;
  46531. };
  46532. LensRenderingPipeline.prototype.disableHighlights = function () {
  46533. this._highlightsGain = -1;
  46534. };
  46535. /**
  46536. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46537. */
  46538. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46539. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46540. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46541. this._chromaticAberrationPostProcess = undefined;
  46542. this._highlightsPostProcess = undefined;
  46543. this._depthOfFieldPostProcess = undefined;
  46544. this._grainTexture.dispose();
  46545. if (disableDepthRender)
  46546. this._scene.disableDepthRenderer();
  46547. };
  46548. // colors shifting and distortion
  46549. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46550. var _this = this;
  46551. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46552. [], // samplers
  46553. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46554. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46555. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46556. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46557. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46558. };
  46559. };
  46560. // highlights enhancing
  46561. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46562. var _this = this;
  46563. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46564. [], // samplers
  46565. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46566. this._highlightsPostProcess.onApply = function (effect) {
  46567. effect.setFloat('gain', _this._highlightsGain);
  46568. effect.setFloat('threshold', _this._highlightsThreshold);
  46569. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46570. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46571. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46572. };
  46573. };
  46574. // colors shifting and distortion
  46575. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46576. var _this = this;
  46577. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46578. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46579. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46580. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46581. this._depthOfFieldPostProcess.onApply = function (effect) {
  46582. effect.setTexture("depthSampler", _this._depthTexture);
  46583. effect.setTexture("grainSampler", _this._grainTexture);
  46584. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46585. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46586. effect.setFloat('grain_amount', _this._grainAmount);
  46587. effect.setBool('blur_noise', _this._blurNoise);
  46588. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46589. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46590. effect.setFloat('distortion', _this._distortion);
  46591. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46592. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46593. effect.setFloat('aperture', _this._dofAperture);
  46594. effect.setFloat('darken', _this._dofDarken);
  46595. effect.setFloat('edge_blur', _this._edgeBlur);
  46596. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46597. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46598. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46599. };
  46600. };
  46601. // creates a black and white random noise texture, 512x512
  46602. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46603. var size = 512;
  46604. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46605. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46606. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46607. var context = this._grainTexture.getContext();
  46608. var rand = function (min, max) {
  46609. return Math.random() * (max - min) + min;
  46610. };
  46611. var value;
  46612. for (var x = 0; x < size; x++) {
  46613. for (var y = 0; y < size; y++) {
  46614. value = Math.floor(rand(0.42, 0.58) * 255);
  46615. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46616. context.fillRect(x, y, 1, 1);
  46617. }
  46618. }
  46619. this._grainTexture.update(false);
  46620. };
  46621. return LensRenderingPipeline;
  46622. })(BABYLON.PostProcessRenderPipeline);
  46623. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46624. })(BABYLON || (BABYLON = {}));
  46625. //
  46626. // This post-process allows the modification of rendered colors by using
  46627. // a 'look-up table' (LUT). This effect is also called Color Grading.
  46628. //
  46629. // The object needs to be provided an url to a texture containing the color
  46630. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  46631. // Use an image editing software to tweak the LUT to match your needs.
  46632. //
  46633. // For an example of a color LUT, see here:
  46634. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  46635. // For explanations on color grading, see here:
  46636. // http://udn.epicgames.com/Three/ColorGrading.html
  46637. //
  46638. var BABYLON;
  46639. (function (BABYLON) {
  46640. var ColorCorrectionPostProcess = (function (_super) {
  46641. __extends(ColorCorrectionPostProcess, _super);
  46642. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  46643. var _this = this;
  46644. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  46645. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46646. this._colorTableTexture.anisotropicFilteringLevel = 1;
  46647. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46648. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46649. this.onApply = function (effect) {
  46650. effect.setTexture("colorTable", _this._colorTableTexture);
  46651. };
  46652. }
  46653. return ColorCorrectionPostProcess;
  46654. })(BABYLON.PostProcess);
  46655. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  46656. })(BABYLON || (BABYLON = {}));
  46657. var BABYLON;
  46658. (function (BABYLON) {
  46659. var AnaglyphFreeCamera = (function (_super) {
  46660. __extends(AnaglyphFreeCamera, _super);
  46661. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  46662. _super.call(this, name, position, scene);
  46663. this.interaxialDistance = interaxialDistance;
  46664. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46665. }
  46666. AnaglyphFreeCamera.prototype.getTypeName = function () {
  46667. return "AnaglyphFreeCamera";
  46668. };
  46669. return AnaglyphFreeCamera;
  46670. })(BABYLON.FreeCamera);
  46671. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  46672. var AnaglyphArcRotateCamera = (function (_super) {
  46673. __extends(AnaglyphArcRotateCamera, _super);
  46674. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  46675. _super.call(this, name, alpha, beta, radius, target, scene);
  46676. this.interaxialDistance = interaxialDistance;
  46677. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46678. }
  46679. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  46680. return "AnaglyphArcRotateCamera";
  46681. };
  46682. return AnaglyphArcRotateCamera;
  46683. })(BABYLON.ArcRotateCamera);
  46684. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  46685. var AnaglyphGamepadCamera = (function (_super) {
  46686. __extends(AnaglyphGamepadCamera, _super);
  46687. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  46688. _super.call(this, name, position, scene);
  46689. this.interaxialDistance = interaxialDistance;
  46690. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46691. }
  46692. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  46693. return "AnaglyphGamepadCamera";
  46694. };
  46695. return AnaglyphGamepadCamera;
  46696. })(BABYLON.GamepadCamera);
  46697. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  46698. var AnaglyphUniversalCamera = (function (_super) {
  46699. __extends(AnaglyphUniversalCamera, _super);
  46700. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  46701. _super.call(this, name, position, scene);
  46702. this.interaxialDistance = interaxialDistance;
  46703. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46704. }
  46705. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  46706. return "AnaglyphUniversalCamera";
  46707. };
  46708. return AnaglyphUniversalCamera;
  46709. })(BABYLON.UniversalCamera);
  46710. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  46711. var StereoscopicFreeCamera = (function (_super) {
  46712. __extends(StereoscopicFreeCamera, _super);
  46713. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46714. _super.call(this, name, position, scene);
  46715. this.interaxialDistance = interaxialDistance;
  46716. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46717. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46718. }
  46719. StereoscopicFreeCamera.prototype.getTypeName = function () {
  46720. return "StereoscopicFreeCamera";
  46721. };
  46722. return StereoscopicFreeCamera;
  46723. })(BABYLON.FreeCamera);
  46724. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  46725. var StereoscopicArcRotateCamera = (function (_super) {
  46726. __extends(StereoscopicArcRotateCamera, _super);
  46727. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  46728. _super.call(this, name, alpha, beta, radius, target, scene);
  46729. this.interaxialDistance = interaxialDistance;
  46730. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46731. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46732. }
  46733. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  46734. return "StereoscopicArcRotateCamera";
  46735. };
  46736. return StereoscopicArcRotateCamera;
  46737. })(BABYLON.ArcRotateCamera);
  46738. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46739. var StereoscopicGamepadCamera = (function (_super) {
  46740. __extends(StereoscopicGamepadCamera, _super);
  46741. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46742. _super.call(this, name, position, scene);
  46743. this.interaxialDistance = interaxialDistance;
  46744. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46745. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46746. }
  46747. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46748. return "StereoscopicGamepadCamera";
  46749. };
  46750. return StereoscopicGamepadCamera;
  46751. })(BABYLON.GamepadCamera);
  46752. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46753. var StereoscopicUniversalCamera = (function (_super) {
  46754. __extends(StereoscopicUniversalCamera, _super);
  46755. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46756. _super.call(this, name, position, scene);
  46757. this.interaxialDistance = interaxialDistance;
  46758. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46759. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46760. }
  46761. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46762. return "StereoscopicUniversalCamera";
  46763. };
  46764. return StereoscopicUniversalCamera;
  46765. })(BABYLON.UniversalCamera);
  46766. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46767. })(BABYLON || (BABYLON = {}));
  46768. var BABYLON;
  46769. (function (BABYLON) {
  46770. var HDRRenderingPipeline = (function (_super) {
  46771. __extends(HDRRenderingPipeline, _super);
  46772. /**
  46773. * @constructor
  46774. * @param {string} name - The rendering pipeline name
  46775. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46776. * @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)
  46777. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46778. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46779. */
  46780. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46781. var _this = this;
  46782. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46783. _super.call(this, scene.getEngine(), name);
  46784. /**
  46785. * Public members
  46786. */
  46787. // Gaussian Blur
  46788. /**
  46789. * Gaussian blur coefficient
  46790. * @type {number}
  46791. */
  46792. this.gaussCoeff = 0.3;
  46793. /**
  46794. * Gaussian blur mean
  46795. * @type {number}
  46796. */
  46797. this.gaussMean = 1.0;
  46798. /**
  46799. * Gaussian blur standard deviation
  46800. * @type {number}
  46801. */
  46802. this.gaussStandDev = 0.8;
  46803. /**
  46804. * Gaussian blur multiplier. Multiplies the blur effect
  46805. * @type {number}
  46806. */
  46807. this.gaussMultiplier = 4.0;
  46808. // HDR
  46809. /**
  46810. * Exposure, controls the overall intensity of the pipeline
  46811. * @type {number}
  46812. */
  46813. this.exposure = 1.0;
  46814. /**
  46815. * Minimum luminance that the post-process can output. Luminance is >= 0
  46816. * @type {number}
  46817. */
  46818. this.minimumLuminance = 1.0;
  46819. /**
  46820. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46821. * @type {number}
  46822. */
  46823. this.maximumLuminance = 1e20;
  46824. /**
  46825. * Increase rate for luminance: eye adaptation speed to dark
  46826. * @type {number}
  46827. */
  46828. this.luminanceIncreaserate = 0.5;
  46829. /**
  46830. * Decrease rate for luminance: eye adaptation speed to bright
  46831. * @type {number}
  46832. */
  46833. this.luminanceDecreaseRate = 0.5;
  46834. // Bright pass
  46835. /**
  46836. * Minimum luminance needed to compute HDR
  46837. * @type {number}
  46838. */
  46839. this.brightThreshold = 0.8;
  46840. this._needUpdate = true;
  46841. this._scene = scene;
  46842. // Bright pass
  46843. this._createBrightPassPostProcess(scene, ratio);
  46844. // Down sample X4
  46845. this._createDownSampleX4PostProcess(scene, ratio);
  46846. // Create gaussian blur post-processes
  46847. this._createGaussianBlurPostProcess(scene, ratio);
  46848. // Texture adder
  46849. this._createTextureAdderPostProcess(scene, ratio);
  46850. // Luminance generator
  46851. this._createLuminanceGeneratorPostProcess(scene);
  46852. // HDR
  46853. this._createHDRPostProcess(scene, ratio);
  46854. // Pass postprocess
  46855. if (originalPostProcess === null) {
  46856. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46857. }
  46858. else {
  46859. this._originalPostProcess = originalPostProcess;
  46860. }
  46861. // Configure pipeline
  46862. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46863. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46864. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46865. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46868. var addDownSamplerPostProcess = function (id) {
  46869. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46870. };
  46871. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46872. addDownSamplerPostProcess(i);
  46873. }
  46874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46875. // Finish
  46876. scene.postProcessRenderPipelineManager.addPipeline(this);
  46877. if (cameras !== null) {
  46878. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46879. }
  46880. this.update();
  46881. }
  46882. /**
  46883. * Tells the pipeline to update its post-processes
  46884. */
  46885. HDRRenderingPipeline.prototype.update = function () {
  46886. this._needUpdate = true;
  46887. };
  46888. /**
  46889. * Returns the current calculated luminance
  46890. */
  46891. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46892. return this._hdrCurrentLuminance;
  46893. };
  46894. /**
  46895. * Returns the currently drawn luminance
  46896. */
  46897. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46898. return this._hdrOutputLuminance;
  46899. };
  46900. /**
  46901. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46902. */
  46903. HDRRenderingPipeline.prototype.dispose = function () {
  46904. this._originalPostProcess = undefined;
  46905. this._brightPassPostProcess = undefined;
  46906. this._downSampleX4PostProcess = undefined;
  46907. this._guassianBlurHPostProcess = undefined;
  46908. this._guassianBlurVPostProcess = undefined;
  46909. this._textureAdderPostProcess = undefined;
  46910. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46911. this._downSamplePostProcesses[i] = undefined;
  46912. }
  46913. this._hdrPostProcess = undefined;
  46914. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46915. };
  46916. /**
  46917. * Creates the HDR post-process and computes the luminance adaptation
  46918. */
  46919. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46920. var _this = this;
  46921. var hdrLastLuminance = 0.0;
  46922. this._hdrOutputLuminance = -1.0;
  46923. this._hdrCurrentLuminance = 1.0;
  46924. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46925. this._hdrPostProcess.onApply = function (effect) {
  46926. if (_this._hdrOutputLuminance < 0.0) {
  46927. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46928. }
  46929. else {
  46930. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46931. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46932. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46933. }
  46934. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46935. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46936. }
  46937. else {
  46938. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46939. }
  46940. }
  46941. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46942. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46943. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46944. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46945. effect.setFloat("exposure", _this.exposure);
  46946. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46947. _this._needUpdate = false;
  46948. };
  46949. };
  46950. /**
  46951. * Texture Adder post-process
  46952. */
  46953. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46954. var _this = this;
  46955. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46956. this._textureAdderPostProcess.onApply = function (effect) {
  46957. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46958. };
  46959. };
  46960. /**
  46961. * Down sample X4 post-process
  46962. */
  46963. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46964. var _this = this;
  46965. var downSampleX4Offsets = new Array(32);
  46966. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46967. this._downSampleX4PostProcess.onApply = function (effect) {
  46968. if (_this._needUpdate) {
  46969. var id = 0;
  46970. for (var i = -2; i < 2; i++) {
  46971. for (var j = -2; j < 2; j++) {
  46972. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46973. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46974. id += 2;
  46975. }
  46976. }
  46977. }
  46978. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46979. };
  46980. };
  46981. /**
  46982. * Bright pass post-process
  46983. */
  46984. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46985. var _this = this;
  46986. var brightOffsets = new Array(8);
  46987. var brightPassCallback = function (effect) {
  46988. if (_this._needUpdate) {
  46989. var sU = (1.0 / _this._brightPassPostProcess.width);
  46990. var sV = (1.0 / _this._brightPassPostProcess.height);
  46991. brightOffsets[0] = -0.5 * sU;
  46992. brightOffsets[1] = 0.5 * sV;
  46993. brightOffsets[2] = 0.5 * sU;
  46994. brightOffsets[3] = 0.5 * sV;
  46995. brightOffsets[4] = -0.5 * sU;
  46996. brightOffsets[5] = -0.5 * sV;
  46997. brightOffsets[6] = 0.5 * sU;
  46998. brightOffsets[7] = -0.5 * sV;
  46999. }
  47000. effect.setArray2("dsOffsets", brightOffsets);
  47001. effect.setFloat("brightThreshold", _this.brightThreshold);
  47002. };
  47003. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47004. this._brightPassPostProcess.onApply = brightPassCallback;
  47005. };
  47006. /**
  47007. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47008. */
  47009. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47010. var _this = this;
  47011. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47012. var luminanceOffsets = new Array(8);
  47013. var downSampleOffsets = new Array(18);
  47014. var halfDestPixelSize;
  47015. this._downSamplePostProcesses = new Array(lumSteps);
  47016. // Utils for luminance
  47017. var luminanceUpdateSourceOffsets = function (width, height) {
  47018. var sU = (1.0 / width);
  47019. var sV = (1.0 / height);
  47020. luminanceOffsets[0] = -0.5 * sU;
  47021. luminanceOffsets[1] = 0.5 * sV;
  47022. luminanceOffsets[2] = 0.5 * sU;
  47023. luminanceOffsets[3] = 0.5 * sV;
  47024. luminanceOffsets[4] = -0.5 * sU;
  47025. luminanceOffsets[5] = -0.5 * sV;
  47026. luminanceOffsets[6] = 0.5 * sU;
  47027. luminanceOffsets[7] = -0.5 * sV;
  47028. };
  47029. var luminanceUpdateDestOffsets = function (width, height) {
  47030. var id = 0;
  47031. for (var x = -1; x < 2; x++) {
  47032. for (var y = -1; y < 2; y++) {
  47033. downSampleOffsets[id] = (x) / width;
  47034. downSampleOffsets[id + 1] = (y) / height;
  47035. id += 2;
  47036. }
  47037. }
  47038. };
  47039. // Luminance callback
  47040. var luminanceCallback = function (effect) {
  47041. if (_this._needUpdate) {
  47042. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47043. }
  47044. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47045. effect.setArray2("lumOffsets", luminanceOffsets);
  47046. };
  47047. // Down sample callbacks
  47048. var downSampleCallback = function (indice) {
  47049. var i = indice;
  47050. return function (effect) {
  47051. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47052. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47053. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47054. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47055. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47056. effect.setArray2("dsOffsets", downSampleOffsets);
  47057. };
  47058. };
  47059. var downSampleAfterRenderCallback = function (effect) {
  47060. // Unpack result
  47061. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47062. 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);
  47063. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47064. };
  47065. // Create luminance post-process
  47066. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47067. 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);
  47068. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47069. // Create down sample post-processes
  47070. for (var i = lumSteps - 2; i >= 0; i--) {
  47071. var length = Math.pow(3, i);
  47072. ratio = { width: length, height: length };
  47073. var defines = "#define DOWN_SAMPLE\n";
  47074. if (i === 0) {
  47075. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47076. }
  47077. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47078. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47079. if (i === 0) {
  47080. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47081. }
  47082. }
  47083. };
  47084. /**
  47085. * Gaussian blur post-processes. Horizontal and Vertical
  47086. */
  47087. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47088. var _this = this;
  47089. var blurOffsetsW = new Array(9);
  47090. var blurOffsetsH = new Array(9);
  47091. var blurWeights = new Array(9);
  47092. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47093. // Utils for gaussian blur
  47094. var calculateBlurOffsets = function (height) {
  47095. var lastOutputDimensions = {
  47096. width: scene.getEngine().getRenderWidth(),
  47097. height: scene.getEngine().getRenderHeight()
  47098. };
  47099. for (var i = 0; i < 9; i++) {
  47100. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47101. if (height) {
  47102. blurOffsetsH[i] = value;
  47103. }
  47104. else {
  47105. blurOffsetsW[i] = value;
  47106. }
  47107. }
  47108. };
  47109. var calculateWeights = function () {
  47110. var x = 0.0;
  47111. for (var i = 0; i < 9; i++) {
  47112. x = (i - 4.0) / 4.0;
  47113. 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));
  47114. }
  47115. };
  47116. // Callback
  47117. var gaussianBlurCallback = function (height) {
  47118. return function (effect) {
  47119. if (_this._needUpdate) {
  47120. calculateWeights();
  47121. calculateBlurOffsets(height);
  47122. }
  47123. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47124. effect.setArray("blurWeights", blurWeights);
  47125. effect.setFloat("multiplier", _this.gaussMultiplier);
  47126. };
  47127. };
  47128. // Create horizontal gaussian blur post-processes
  47129. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47130. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47131. // Create vertical gaussian blur post-process
  47132. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47133. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47134. };
  47135. // Luminance generator
  47136. HDRRenderingPipeline.LUM_STEPS = 6;
  47137. return HDRRenderingPipeline;
  47138. })(BABYLON.PostProcessRenderPipeline);
  47139. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47140. })(BABYLON || (BABYLON = {}));
  47141. var BABYLON;
  47142. (function (BABYLON) {
  47143. var FaceAdjacencies = (function () {
  47144. function FaceAdjacencies() {
  47145. this.edges = new Array();
  47146. this.edgesConnectedCount = 0;
  47147. }
  47148. return FaceAdjacencies;
  47149. })();
  47150. var EdgesRenderer = (function () {
  47151. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  47152. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  47153. if (epsilon === void 0) { epsilon = 0.95; }
  47154. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  47155. this.edgesWidthScalerForOrthographic = 1000.0;
  47156. this.edgesWidthScalerForPerspective = 50.0;
  47157. this._linesPositions = new Array();
  47158. this._linesNormals = new Array();
  47159. this._linesIndices = new Array();
  47160. this._buffers = new Array();
  47161. this._checkVerticesInsteadOfIndices = false;
  47162. this._source = source;
  47163. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  47164. this._epsilon = epsilon;
  47165. this._prepareRessources();
  47166. this._generateEdgesLines();
  47167. }
  47168. EdgesRenderer.prototype._prepareRessources = function () {
  47169. if (this._lineShader) {
  47170. return;
  47171. }
  47172. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  47173. attributes: ["position", "normal"],
  47174. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  47175. });
  47176. this._lineShader.disableDepthWrite = true;
  47177. this._lineShader.backFaceCulling = false;
  47178. };
  47179. EdgesRenderer.prototype.dispose = function () {
  47180. this._vb0.dispose();
  47181. this._vb1.dispose();
  47182. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  47183. this._lineShader.dispose();
  47184. };
  47185. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  47186. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  47187. return 0;
  47188. }
  47189. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  47190. return 1;
  47191. }
  47192. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  47193. return 2;
  47194. }
  47195. return -1;
  47196. };
  47197. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  47198. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  47199. return 0;
  47200. }
  47201. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  47202. return 1;
  47203. }
  47204. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  47205. return 2;
  47206. }
  47207. return -1;
  47208. };
  47209. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  47210. var needToCreateLine;
  47211. if (edge === undefined) {
  47212. needToCreateLine = true;
  47213. }
  47214. else {
  47215. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  47216. needToCreateLine = dotProduct < this._epsilon;
  47217. }
  47218. if (needToCreateLine) {
  47219. var offset = this._linesPositions.length / 3;
  47220. var normal = p0.subtract(p1);
  47221. normal.normalize();
  47222. // Positions
  47223. this._linesPositions.push(p0.x);
  47224. this._linesPositions.push(p0.y);
  47225. this._linesPositions.push(p0.z);
  47226. this._linesPositions.push(p0.x);
  47227. this._linesPositions.push(p0.y);
  47228. this._linesPositions.push(p0.z);
  47229. this._linesPositions.push(p1.x);
  47230. this._linesPositions.push(p1.y);
  47231. this._linesPositions.push(p1.z);
  47232. this._linesPositions.push(p1.x);
  47233. this._linesPositions.push(p1.y);
  47234. this._linesPositions.push(p1.z);
  47235. // Normals
  47236. this._linesNormals.push(p1.x);
  47237. this._linesNormals.push(p1.y);
  47238. this._linesNormals.push(p1.z);
  47239. this._linesNormals.push(-1);
  47240. this._linesNormals.push(p1.x);
  47241. this._linesNormals.push(p1.y);
  47242. this._linesNormals.push(p1.z);
  47243. this._linesNormals.push(1);
  47244. this._linesNormals.push(p0.x);
  47245. this._linesNormals.push(p0.y);
  47246. this._linesNormals.push(p0.z);
  47247. this._linesNormals.push(-1);
  47248. this._linesNormals.push(p0.x);
  47249. this._linesNormals.push(p0.y);
  47250. this._linesNormals.push(p0.z);
  47251. this._linesNormals.push(1);
  47252. // Indices
  47253. this._linesIndices.push(offset);
  47254. this._linesIndices.push(offset + 1);
  47255. this._linesIndices.push(offset + 2);
  47256. this._linesIndices.push(offset);
  47257. this._linesIndices.push(offset + 2);
  47258. this._linesIndices.push(offset + 3);
  47259. }
  47260. };
  47261. EdgesRenderer.prototype._generateEdgesLines = function () {
  47262. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47263. var indices = this._source.getIndices();
  47264. // First let's find adjacencies
  47265. var adjacencies = new Array();
  47266. var faceNormals = new Array();
  47267. var index;
  47268. var faceAdjacencies;
  47269. // Prepare faces
  47270. for (index = 0; index < indices.length; index += 3) {
  47271. faceAdjacencies = new FaceAdjacencies();
  47272. var p0Index = indices[index];
  47273. var p1Index = indices[index + 1];
  47274. var p2Index = indices[index + 2];
  47275. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  47276. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  47277. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  47278. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  47279. faceNormal.normalize();
  47280. faceNormals.push(faceNormal);
  47281. adjacencies.push(faceAdjacencies);
  47282. }
  47283. // Scan
  47284. for (index = 0; index < adjacencies.length; index++) {
  47285. faceAdjacencies = adjacencies[index];
  47286. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  47287. var otherFaceAdjacencies = adjacencies[otherIndex];
  47288. if (faceAdjacencies.edgesConnectedCount === 3) {
  47289. break;
  47290. }
  47291. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  47292. continue;
  47293. }
  47294. var otherP0 = indices[otherIndex * 3];
  47295. var otherP1 = indices[otherIndex * 3 + 1];
  47296. var otherP2 = indices[otherIndex * 3 + 2];
  47297. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  47298. var otherEdgeIndex;
  47299. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  47300. continue;
  47301. }
  47302. switch (edgeIndex) {
  47303. case 0:
  47304. if (this._checkVerticesInsteadOfIndices) {
  47305. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47306. }
  47307. else {
  47308. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  47309. }
  47310. break;
  47311. case 1:
  47312. if (this._checkVerticesInsteadOfIndices) {
  47313. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47314. }
  47315. else {
  47316. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  47317. }
  47318. break;
  47319. case 2:
  47320. if (this._checkVerticesInsteadOfIndices) {
  47321. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47322. }
  47323. else {
  47324. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  47325. }
  47326. break;
  47327. }
  47328. if (otherEdgeIndex === -1) {
  47329. continue;
  47330. }
  47331. faceAdjacencies.edges[edgeIndex] = otherIndex;
  47332. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  47333. faceAdjacencies.edgesConnectedCount++;
  47334. otherFaceAdjacencies.edgesConnectedCount++;
  47335. if (faceAdjacencies.edgesConnectedCount === 3) {
  47336. break;
  47337. }
  47338. }
  47339. }
  47340. }
  47341. // Create lines
  47342. for (index = 0; index < adjacencies.length; index++) {
  47343. // 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
  47344. var current = adjacencies[index];
  47345. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  47346. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  47347. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  47348. }
  47349. // Merge into a single mesh
  47350. var engine = this._source.getScene().getEngine();
  47351. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  47352. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  47353. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  47354. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  47355. this._ib = engine.createIndexBuffer(this._linesIndices);
  47356. this._indicesCount = this._linesIndices.length;
  47357. };
  47358. EdgesRenderer.prototype.render = function () {
  47359. if (!this._lineShader.isReady()) {
  47360. return;
  47361. }
  47362. var scene = this._source.getScene();
  47363. var engine = scene.getEngine();
  47364. this._lineShader._preBind();
  47365. // VBOs
  47366. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  47367. scene.resetCachedMaterial();
  47368. this._lineShader.setColor4("color", this._source.edgesColor);
  47369. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  47370. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  47371. }
  47372. else {
  47373. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  47374. }
  47375. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  47376. this._lineShader.bind(this._source.getWorldMatrix());
  47377. // Draw order
  47378. engine.draw(true, 0, this._indicesCount);
  47379. this._lineShader.unbind();
  47380. engine.setDepthWrite(true);
  47381. };
  47382. return EdgesRenderer;
  47383. })();
  47384. BABYLON.EdgesRenderer = EdgesRenderer;
  47385. })(BABYLON || (BABYLON = {}));
  47386. var BABYLON;
  47387. (function (BABYLON) {
  47388. (function (TonemappingOperator) {
  47389. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47390. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47391. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47392. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47393. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47394. var TonemappingOperator = BABYLON.TonemappingOperator;
  47395. ;
  47396. var TonemapPostProcess = (function (_super) {
  47397. __extends(TonemapPostProcess, _super);
  47398. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47399. var _this = this;
  47400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47401. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47402. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  47403. this._operator = _operator;
  47404. this.exposureAdjustment = exposureAdjustment;
  47405. var defines = "#define ";
  47406. if (this._operator === TonemappingOperator.Hable)
  47407. defines += "HABLE_TONEMAPPING";
  47408. else if (this._operator === TonemappingOperator.Reinhard)
  47409. defines += "REINHARD_TONEMAPPING";
  47410. else if (this._operator === TonemappingOperator.HejiDawson)
  47411. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47412. else if (this._operator === TonemappingOperator.Photographic)
  47413. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47414. //sadly a second call to create the effect.
  47415. this.updateEffect(defines);
  47416. this.onApply = function (effect) {
  47417. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47418. };
  47419. }
  47420. return TonemapPostProcess;
  47421. })(BABYLON.PostProcess);
  47422. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47423. })(BABYLON || (BABYLON = {}));
  47424. var BABYLON;
  47425. (function (BABYLON) {
  47426. var ReflectionProbe = (function () {
  47427. function ReflectionProbe(name, size, scene, generateMipMaps) {
  47428. var _this = this;
  47429. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47430. this.name = name;
  47431. this._viewMatrix = BABYLON.Matrix.Identity();
  47432. this._target = BABYLON.Vector3.Zero();
  47433. this._add = BABYLON.Vector3.Zero();
  47434. this.invertYAxis = false;
  47435. this.position = BABYLON.Vector3.Zero();
  47436. this._scene = scene;
  47437. this._scene.reflectionProbes.push(this);
  47438. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  47439. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  47440. switch (faceIndex) {
  47441. case 0:
  47442. _this._add.copyFromFloats(1, 0, 0);
  47443. break;
  47444. case 1:
  47445. _this._add.copyFromFloats(-1, 0, 0);
  47446. break;
  47447. case 2:
  47448. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  47449. break;
  47450. case 3:
  47451. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  47452. break;
  47453. case 4:
  47454. _this._add.copyFromFloats(0, 0, 1);
  47455. break;
  47456. case 5:
  47457. _this._add.copyFromFloats(0, 0, -1);
  47458. break;
  47459. }
  47460. if (_this._attachedMesh) {
  47461. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  47462. }
  47463. _this.position.addToRef(_this._add, _this._target);
  47464. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  47465. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  47466. });
  47467. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  47468. scene.updateTransformMatrix(true);
  47469. });
  47470. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  47471. }
  47472. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  47473. get: function () {
  47474. return this._renderTargetTexture.refreshRate;
  47475. },
  47476. set: function (value) {
  47477. this._renderTargetTexture.refreshRate = value;
  47478. },
  47479. enumerable: true,
  47480. configurable: true
  47481. });
  47482. ReflectionProbe.prototype.getScene = function () {
  47483. return this._scene;
  47484. };
  47485. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  47486. get: function () {
  47487. return this._renderTargetTexture;
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  47493. get: function () {
  47494. return this._renderTargetTexture.renderList;
  47495. },
  47496. enumerable: true,
  47497. configurable: true
  47498. });
  47499. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  47500. this._attachedMesh = mesh;
  47501. };
  47502. ReflectionProbe.prototype.dispose = function () {
  47503. var index = this._scene.reflectionProbes.indexOf(this);
  47504. if (index !== -1) {
  47505. // Remove from the scene if found
  47506. this._scene.reflectionProbes.splice(index, 1);
  47507. }
  47508. if (this._renderTargetTexture) {
  47509. this._renderTargetTexture.dispose();
  47510. this._renderTargetTexture = null;
  47511. }
  47512. };
  47513. return ReflectionProbe;
  47514. })();
  47515. BABYLON.ReflectionProbe = ReflectionProbe;
  47516. })(BABYLON || (BABYLON = {}));
  47517. var BABYLON;
  47518. (function (BABYLON) {
  47519. var SolidParticle = (function () {
  47520. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  47521. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  47522. this.position = BABYLON.Vector3.Zero(); // position
  47523. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47524. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  47525. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  47526. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47527. this.alive = true; // alive
  47528. this.isVisible = true; // visibility
  47529. this.idx = particleIndex;
  47530. this._pos = positionIndex;
  47531. this._model = model;
  47532. this.shapeId = shapeId;
  47533. this.idxInShape = idxInShape;
  47534. }
  47535. Object.defineProperty(SolidParticle.prototype, "scale", {
  47536. //legacy support, changed scale to scaling
  47537. get: function () {
  47538. return this.scaling;
  47539. },
  47540. set: function (scale) {
  47541. this.scaling = scale;
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47547. //legacy support, changed quaternion to rotationQuaternion
  47548. get: function () {
  47549. return this.rotationQuaternion;
  47550. },
  47551. set: function (q) {
  47552. this.rotationQuaternion = q;
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. return SolidParticle;
  47558. })();
  47559. BABYLON.SolidParticle = SolidParticle;
  47560. var ModelShape = (function () {
  47561. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  47562. this.shapeID = id;
  47563. this._shape = shape;
  47564. this._shapeUV = shapeUV;
  47565. this._positionFunction = posFunction;
  47566. this._vertexFunction = vtxFunction;
  47567. }
  47568. return ModelShape;
  47569. })();
  47570. BABYLON.ModelShape = ModelShape;
  47571. })(BABYLON || (BABYLON = {}));
  47572. var BABYLON;
  47573. (function (BABYLON) {
  47574. /**
  47575. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47576. */
  47577. var SolidParticleSystem = (function () {
  47578. /**
  47579. * Creates a SPS (Solid Particle System) object.
  47580. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47581. * `scene` (Scene) is the scene in which the SPS is added.
  47582. * `updatableè (default true) : if the SPS must be updatable or immutable.
  47583. * `isPickable` (default false) : if the solid particles must be pickable.
  47584. */
  47585. function SolidParticleSystem(name, scene, options) {
  47586. // public members
  47587. /**
  47588. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47589. * Example : var p = SPS.particles[i];
  47590. */
  47591. this.particles = new Array();
  47592. /**
  47593. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47594. */
  47595. this.nbParticles = 0;
  47596. /**
  47597. * If the particles must ever face the camera (default false). Useful for planar particles.
  47598. */
  47599. this.billboard = false;
  47600. /**
  47601. * This a counter ofr your own usage. It's not set by any SPS functions.
  47602. */
  47603. this.counter = 0;
  47604. /**
  47605. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47606. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47607. */
  47608. this.vars = {};
  47609. this._positions = new Array();
  47610. this._indices = new Array();
  47611. this._normals = new Array();
  47612. this._colors = new Array();
  47613. this._uvs = new Array();
  47614. this._index = 0; // indices index
  47615. this._updatable = true;
  47616. this._pickable = false;
  47617. this._isVisibilityBoxLocked = false;
  47618. this._alwaysVisible = false;
  47619. this._shapeCounter = 0;
  47620. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  47621. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47622. this._computeParticleColor = true;
  47623. this._computeParticleTexture = true;
  47624. this._computeParticleRotation = true;
  47625. this._computeParticleVertex = false;
  47626. this._computeBoundingBox = false;
  47627. this._cam_axisZ = BABYLON.Vector3.Zero();
  47628. this._cam_axisY = BABYLON.Vector3.Zero();
  47629. this._cam_axisX = BABYLON.Vector3.Zero();
  47630. this._axisX = BABYLON.Axis.X;
  47631. this._axisY = BABYLON.Axis.Y;
  47632. this._axisZ = BABYLON.Axis.Z;
  47633. this._fakeCamPos = BABYLON.Vector3.Zero();
  47634. this._rotMatrix = new BABYLON.Matrix();
  47635. this._invertMatrix = new BABYLON.Matrix();
  47636. this._rotated = BABYLON.Vector3.Zero();
  47637. this._quaternion = new BABYLON.Quaternion();
  47638. this._vertex = BABYLON.Vector3.Zero();
  47639. this._normal = BABYLON.Vector3.Zero();
  47640. this._yaw = 0.0;
  47641. this._pitch = 0.0;
  47642. this._roll = 0.0;
  47643. this._halfroll = 0.0;
  47644. this._halfpitch = 0.0;
  47645. this._halfyaw = 0.0;
  47646. this._sinRoll = 0.0;
  47647. this._cosRoll = 0.0;
  47648. this._sinPitch = 0.0;
  47649. this._cosPitch = 0.0;
  47650. this._sinYaw = 0.0;
  47651. this._cosYaw = 0.0;
  47652. this._w = 0.0;
  47653. this._minimum = BABYLON.Tmp.Vector3[0];
  47654. this._maximum = BABYLON.Tmp.Vector3[1];
  47655. this.name = name;
  47656. this._scene = scene;
  47657. this._camera = scene.activeCamera;
  47658. this._pickable = options ? options.isPickable : false;
  47659. if (options && options.updatable) {
  47660. this._updatable = options.updatable;
  47661. }
  47662. else {
  47663. this._updatable = true;
  47664. }
  47665. if (this._pickable) {
  47666. this.pickedParticles = [];
  47667. }
  47668. }
  47669. /**
  47670. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47671. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47672. */
  47673. SolidParticleSystem.prototype.buildMesh = function () {
  47674. if (this.nbParticles === 0) {
  47675. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47676. this.addShape(triangle, 1);
  47677. triangle.dispose();
  47678. }
  47679. this._positions32 = new Float32Array(this._positions);
  47680. this._uvs32 = new Float32Array(this._uvs);
  47681. this._colors32 = new Float32Array(this._colors);
  47682. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  47683. this._normals32 = new Float32Array(this._normals);
  47684. this._fixedNormal32 = new Float32Array(this._normals);
  47685. var vertexData = new BABYLON.VertexData();
  47686. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47687. vertexData.indices = this._indices;
  47688. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47689. if (this._uvs32) {
  47690. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47691. ;
  47692. }
  47693. if (this._colors32) {
  47694. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47695. }
  47696. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47697. vertexData.applyToMesh(mesh, this._updatable);
  47698. this.mesh = mesh;
  47699. this.mesh.isPickable = this._pickable;
  47700. // free memory
  47701. this._positions = null;
  47702. this._normals = null;
  47703. this._uvs = null;
  47704. this._colors = null;
  47705. if (!this._updatable) {
  47706. this.particles.length = 0;
  47707. }
  47708. return mesh;
  47709. };
  47710. /**
  47711. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47712. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47713. * Thus the particles generated from `digest()` have their property `position` set yet.
  47714. * `mesh` (`Mesh`) is the mesh to be digested
  47715. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47716. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47717. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47718. */
  47719. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47720. var size = (options && options.facetNb) || 1;
  47721. var number = (options && options.number);
  47722. var delta = (options && options.delta) || 0;
  47723. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47724. var meshInd = mesh.getIndices();
  47725. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47726. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47727. var f = 0; // facet counter
  47728. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47729. // compute size from number
  47730. if (number) {
  47731. number = (number > totalFacets) ? totalFacets : number;
  47732. size = Math.round(totalFacets / number);
  47733. delta = 0;
  47734. }
  47735. else {
  47736. size = (size > totalFacets) ? totalFacets : size;
  47737. }
  47738. var facetPos = []; // submesh positions
  47739. var facetInd = []; // submesh indices
  47740. var facetUV = []; // submesh UV
  47741. var facetCol = []; // submesh colors
  47742. var barycenter = BABYLON.Tmp.Vector3[0];
  47743. var rand;
  47744. var sizeO = size;
  47745. while (f < totalFacets) {
  47746. size = sizeO + Math.floor((1 + delta) * Math.random());
  47747. if (f > totalFacets - size) {
  47748. size = totalFacets - f;
  47749. }
  47750. // reset temp arrays
  47751. facetPos.length = 0;
  47752. facetInd.length = 0;
  47753. facetUV.length = 0;
  47754. facetCol.length = 0;
  47755. // iterate over "size" facets
  47756. var fi = 0;
  47757. for (var j = f * 3; j < (f + size) * 3; j++) {
  47758. facetInd.push(fi);
  47759. var i = meshInd[j];
  47760. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47761. if (meshUV) {
  47762. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47763. }
  47764. if (meshCol) {
  47765. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47766. }
  47767. fi++;
  47768. }
  47769. // create a model shape for each single particle
  47770. var idx = this.nbParticles;
  47771. var shape = this._posToShape(facetPos);
  47772. var shapeUV = this._uvsToShapeUV(facetUV);
  47773. // compute the barycenter of the shape
  47774. var v;
  47775. for (v = 0; v < shape.length; v++) {
  47776. barycenter.addInPlace(shape[v]);
  47777. }
  47778. barycenter.scaleInPlace(1 / shape.length);
  47779. // shift the shape from its barycenter to the origin
  47780. for (v = 0; v < shape.length; v++) {
  47781. shape[v].subtractInPlace(barycenter);
  47782. }
  47783. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  47784. // add the particle in the SPS
  47785. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  47786. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  47787. // initialize the particle position
  47788. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47789. this._index += shape.length;
  47790. idx++;
  47791. this.nbParticles++;
  47792. this._shapeCounter++;
  47793. f += size;
  47794. }
  47795. return this;
  47796. };
  47797. //reset copy
  47798. SolidParticleSystem.prototype._resetCopy = function () {
  47799. this._copy.position.x = 0;
  47800. this._copy.position.y = 0;
  47801. this._copy.position.z = 0;
  47802. this._copy.rotation.x = 0;
  47803. this._copy.rotation.y = 0;
  47804. this._copy.rotation.z = 0;
  47805. this._copy.rotationQuaternion = null;
  47806. this._copy.scaling.x = 1;
  47807. this._copy.scaling.y = 1;
  47808. this._copy.scaling.z = 1;
  47809. this._copy.uvs.x = 0;
  47810. this._copy.uvs.y = 0;
  47811. this._copy.uvs.z = 1;
  47812. this._copy.uvs.w = 1;
  47813. this._copy.color = null;
  47814. };
  47815. // _meshBuilder : inserts the shape model in the global SPS mesh
  47816. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  47817. var i;
  47818. var u = 0;
  47819. var c = 0;
  47820. this._resetCopy();
  47821. if (options && options.positionFunction) {
  47822. options.positionFunction(this._copy, idx, idxInShape);
  47823. }
  47824. if (this._copy.rotationQuaternion) {
  47825. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47826. }
  47827. else {
  47828. this._yaw = this._copy.rotation.y;
  47829. this._pitch = this._copy.rotation.x;
  47830. this._roll = this._copy.rotation.z;
  47831. this._quaternionRotationYPR();
  47832. }
  47833. this._quaternionToRotationMatrix();
  47834. for (i = 0; i < shape.length; i++) {
  47835. this._vertex.x = shape[i].x;
  47836. this._vertex.y = shape[i].y;
  47837. this._vertex.z = shape[i].z;
  47838. if (options && options.vertexFunction) {
  47839. options.vertexFunction(this._copy, this._vertex, i);
  47840. }
  47841. this._vertex.x *= this._copy.scaling.x;
  47842. this._vertex.y *= this._copy.scaling.y;
  47843. this._vertex.z *= this._copy.scaling.z;
  47844. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47845. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47846. if (meshUV) {
  47847. 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);
  47848. u += 2;
  47849. }
  47850. if (this._copy.color) {
  47851. this._color = this._copy.color;
  47852. }
  47853. else if (meshCol && meshCol[c]) {
  47854. this._color.r = meshCol[c];
  47855. this._color.g = meshCol[c + 1];
  47856. this._color.b = meshCol[c + 2];
  47857. this._color.a = meshCol[c + 3];
  47858. }
  47859. else {
  47860. this._color.r = 1;
  47861. this._color.g = 1;
  47862. this._color.b = 1;
  47863. this._color.a = 1;
  47864. }
  47865. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47866. c += 4;
  47867. }
  47868. for (i = 0; i < meshInd.length; i++) {
  47869. indices.push(p + meshInd[i]);
  47870. }
  47871. if (this._pickable) {
  47872. var nbfaces = meshInd.length / 3;
  47873. for (i = 0; i < nbfaces; i++) {
  47874. this.pickedParticles.push({ idx: idx, faceId: i });
  47875. }
  47876. }
  47877. };
  47878. // returns a shape array from positions array
  47879. SolidParticleSystem.prototype._posToShape = function (positions) {
  47880. var shape = [];
  47881. for (var i = 0; i < positions.length; i += 3) {
  47882. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47883. }
  47884. return shape;
  47885. };
  47886. // returns a shapeUV array from a Vector4 uvs
  47887. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47888. var shapeUV = [];
  47889. if (uvs) {
  47890. for (var i = 0; i < uvs.length; i++)
  47891. shapeUV.push(uvs[i]);
  47892. }
  47893. return shapeUV;
  47894. };
  47895. // adds a new particle object in the particles array
  47896. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  47897. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  47898. };
  47899. /**
  47900. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47901. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47902. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  47903. * `nb` (positive integer) the number of particles to be created from this model
  47904. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47905. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47906. */
  47907. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47908. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47909. var meshInd = mesh.getIndices();
  47910. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47911. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47912. var shape = this._posToShape(meshPos);
  47913. var shapeUV = this._uvsToShapeUV(meshUV);
  47914. var posfunc = options ? options.positionFunction : null;
  47915. var vtxfunc = options ? options.vertexFunction : null;
  47916. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  47917. // particles
  47918. var idx = this.nbParticles;
  47919. for (var i = 0; i < nb; i++) {
  47920. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  47921. if (this._updatable) {
  47922. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  47923. }
  47924. this._index += shape.length;
  47925. idx++;
  47926. }
  47927. this.nbParticles += nb;
  47928. this._shapeCounter++;
  47929. return this._shapeCounter - 1;
  47930. };
  47931. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47932. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47933. this._resetCopy();
  47934. if (particle._model._positionFunction) {
  47935. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47936. }
  47937. if (this._copy.rotationQuaternion) {
  47938. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47939. }
  47940. else {
  47941. this._yaw = this._copy.rotation.y;
  47942. this._pitch = this._copy.rotation.x;
  47943. this._roll = this._copy.rotation.z;
  47944. this._quaternionRotationYPR();
  47945. }
  47946. this._quaternionToRotationMatrix();
  47947. this._shape = particle._model._shape;
  47948. for (var pt = 0; pt < this._shape.length; pt++) {
  47949. this._vertex.x = this._shape[pt].x;
  47950. this._vertex.y = this._shape[pt].y;
  47951. this._vertex.z = this._shape[pt].z;
  47952. if (particle._model._vertexFunction) {
  47953. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47954. }
  47955. this._vertex.x *= this._copy.scaling.x;
  47956. this._vertex.y *= this._copy.scaling.y;
  47957. this._vertex.z *= this._copy.scaling.z;
  47958. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47959. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47960. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47961. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47962. }
  47963. particle.position.x = 0;
  47964. particle.position.y = 0;
  47965. particle.position.z = 0;
  47966. particle.rotation.x = 0;
  47967. particle.rotation.y = 0;
  47968. particle.rotation.z = 0;
  47969. particle.rotationQuaternion = null;
  47970. particle.scaling.x = 1;
  47971. particle.scaling.y = 1;
  47972. particle.scaling.z = 1;
  47973. };
  47974. /**
  47975. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47976. */
  47977. SolidParticleSystem.prototype.rebuildMesh = function () {
  47978. for (var p = 0; p < this.particles.length; p++) {
  47979. this._rebuildParticle(this.particles[p]);
  47980. }
  47981. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47982. };
  47983. /**
  47984. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47985. * This method calls `updateParticle()` for each particle of the SPS.
  47986. * For an animated SPS, it is usually called within the render loop.
  47987. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  47988. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  47989. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  47990. */
  47991. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47992. if (start === void 0) { start = 0; }
  47993. if (end === void 0) { end = this.nbParticles - 1; }
  47994. if (update === void 0) { update = true; }
  47995. if (!this._updatable) {
  47996. return;
  47997. }
  47998. // custom beforeUpdate
  47999. this.beforeUpdateParticles(start, end, update);
  48000. this._cam_axisX.x = 1;
  48001. this._cam_axisX.y = 0;
  48002. this._cam_axisX.z = 0;
  48003. this._cam_axisY.x = 0;
  48004. this._cam_axisY.y = 1;
  48005. this._cam_axisY.z = 0;
  48006. this._cam_axisZ.x = 0;
  48007. this._cam_axisZ.y = 0;
  48008. this._cam_axisZ.z = 1;
  48009. // if the particles will always face the camera
  48010. if (this.billboard) {
  48011. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  48012. this._yaw = this.mesh.rotation.y;
  48013. this._pitch = this.mesh.rotation.x;
  48014. this._roll = this.mesh.rotation.z;
  48015. this._quaternionRotationYPR();
  48016. this._quaternionToRotationMatrix();
  48017. this._rotMatrix.invertToRef(this._invertMatrix);
  48018. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  48019. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  48020. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  48021. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  48022. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  48023. this._cam_axisY.normalize();
  48024. this._cam_axisX.normalize();
  48025. this._cam_axisZ.normalize();
  48026. }
  48027. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  48028. var idx = 0;
  48029. var index = 0;
  48030. var colidx = 0;
  48031. var colorIndex = 0;
  48032. var uvidx = 0;
  48033. var uvIndex = 0;
  48034. var pt = 0;
  48035. if (this._computeBoundingBox) {
  48036. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  48037. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  48038. }
  48039. // particle loop
  48040. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  48041. for (var p = start; p <= end; p++) {
  48042. this._particle = this.particles[p];
  48043. this._shape = this._particle._model._shape;
  48044. this._shapeUV = this._particle._model._shapeUV;
  48045. // call to custom user function to update the particle properties
  48046. this.updateParticle(this._particle);
  48047. if (this._particle.isVisible) {
  48048. // particle rotation matrix
  48049. if (this.billboard) {
  48050. this._particle.rotation.x = 0.0;
  48051. this._particle.rotation.y = 0.0;
  48052. }
  48053. if (this._computeParticleRotation) {
  48054. if (this._particle.rotationQuaternion) {
  48055. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48056. }
  48057. else {
  48058. this._yaw = this._particle.rotation.y;
  48059. this._pitch = this._particle.rotation.x;
  48060. this._roll = this._particle.rotation.z;
  48061. this._quaternionRotationYPR();
  48062. }
  48063. this._quaternionToRotationMatrix();
  48064. }
  48065. // particle vertex loop
  48066. for (pt = 0; pt < this._shape.length; pt++) {
  48067. idx = index + pt * 3;
  48068. colidx = colorIndex + pt * 4;
  48069. uvidx = uvIndex + pt * 2;
  48070. this._vertex.x = this._shape[pt].x;
  48071. this._vertex.y = this._shape[pt].y;
  48072. this._vertex.z = this._shape[pt].z;
  48073. if (this._computeParticleVertex) {
  48074. this.updateParticleVertex(this._particle, this._vertex, pt);
  48075. }
  48076. // positions
  48077. this._vertex.x *= this._particle.scaling.x;
  48078. this._vertex.y *= this._particle.scaling.y;
  48079. this._vertex.z *= this._particle.scaling.z;
  48080. 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];
  48081. 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;
  48082. 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;
  48083. 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;
  48084. 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;
  48085. 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;
  48086. 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;
  48087. if (this._computeBoundingBox) {
  48088. if (this._positions32[idx] < this._minimum.x) {
  48089. this._minimum.x = this._positions32[idx];
  48090. }
  48091. if (this._positions32[idx] > this._maximum.x) {
  48092. this._maximum.x = this._positions32[idx];
  48093. }
  48094. if (this._positions32[idx + 1] < this._minimum.y) {
  48095. this._minimum.y = this._positions32[idx + 1];
  48096. }
  48097. if (this._positions32[idx + 1] > this._maximum.y) {
  48098. this._maximum.y = this._positions32[idx + 1];
  48099. }
  48100. if (this._positions32[idx + 2] < this._minimum.z) {
  48101. this._minimum.z = this._positions32[idx + 2];
  48102. }
  48103. if (this._positions32[idx + 2] > this._maximum.z) {
  48104. this._maximum.z = this._positions32[idx + 2];
  48105. }
  48106. }
  48107. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  48108. if (!this._computeParticleVertex && !this.billboard) {
  48109. this._normal.x = this._fixedNormal32[idx];
  48110. this._normal.y = this._fixedNormal32[idx + 1];
  48111. this._normal.z = this._fixedNormal32[idx + 2];
  48112. 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];
  48113. 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;
  48114. 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;
  48115. 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;
  48116. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  48117. 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;
  48118. 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;
  48119. }
  48120. if (this._computeParticleColor) {
  48121. this._colors32[colidx] = this._particle.color.r;
  48122. this._colors32[colidx + 1] = this._particle.color.g;
  48123. this._colors32[colidx + 2] = this._particle.color.b;
  48124. this._colors32[colidx + 3] = this._particle.color.a;
  48125. }
  48126. if (this._computeParticleTexture) {
  48127. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48128. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48129. }
  48130. }
  48131. }
  48132. else {
  48133. for (pt = 0; pt < this._shape.length; pt++) {
  48134. idx = index + pt * 3;
  48135. colidx = colorIndex + pt * 4;
  48136. uvidx = uvIndex + pt * 2;
  48137. this._positions32[idx] = this._camera.position.x;
  48138. this._positions32[idx + 1] = this._camera.position.y;
  48139. this._positions32[idx + 2] = this._camera.position.z;
  48140. this._normals32[idx] = 0.0;
  48141. this._normals32[idx + 1] = 0.0;
  48142. this._normals32[idx + 2] = 0.0;
  48143. if (this._computeParticleColor) {
  48144. this._colors32[colidx] = this._particle.color.r;
  48145. this._colors32[colidx + 1] = this._particle.color.g;
  48146. this._colors32[colidx + 2] = this._particle.color.b;
  48147. this._colors32[colidx + 3] = this._particle.color.a;
  48148. }
  48149. if (this._computeParticleTexture) {
  48150. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48151. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48152. }
  48153. }
  48154. }
  48155. // increment indexes for the next particle
  48156. index = idx + 3;
  48157. colorIndex = colidx + 4;
  48158. uvIndex = uvidx + 2;
  48159. }
  48160. // if the VBO must be updated
  48161. if (update) {
  48162. if (this._computeParticleColor) {
  48163. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  48164. }
  48165. if (this._computeParticleTexture) {
  48166. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  48167. }
  48168. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48169. if (!this.mesh.areNormalsFrozen) {
  48170. if (this._computeParticleVertex || this.billboard) {
  48171. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  48172. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  48173. for (var i = 0; i < this._normals32.length; i++) {
  48174. this._fixedNormal32[i] = this._normals32[i];
  48175. }
  48176. }
  48177. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  48178. }
  48179. }
  48180. if (this._computeBoundingBox) {
  48181. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  48182. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  48183. }
  48184. this.afterUpdateParticles(start, end, update);
  48185. };
  48186. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  48187. this._halfroll = this._roll * 0.5;
  48188. this._halfpitch = this._pitch * 0.5;
  48189. this._halfyaw = this._yaw * 0.5;
  48190. this._sinRoll = Math.sin(this._halfroll);
  48191. this._cosRoll = Math.cos(this._halfroll);
  48192. this._sinPitch = Math.sin(this._halfpitch);
  48193. this._cosPitch = Math.cos(this._halfpitch);
  48194. this._sinYaw = Math.sin(this._halfyaw);
  48195. this._cosYaw = Math.cos(this._halfyaw);
  48196. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  48197. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  48198. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  48199. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  48200. };
  48201. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  48202. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  48203. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  48204. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  48205. this._rotMatrix.m[3] = 0;
  48206. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  48207. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  48208. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  48209. this._rotMatrix.m[7] = 0;
  48210. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  48211. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  48212. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  48213. this._rotMatrix.m[11] = 0;
  48214. this._rotMatrix.m[12] = 0;
  48215. this._rotMatrix.m[13] = 0;
  48216. this._rotMatrix.m[14] = 0;
  48217. this._rotMatrix.m[15] = 1.0;
  48218. };
  48219. /**
  48220. * Disposes the SPS
  48221. */
  48222. SolidParticleSystem.prototype.dispose = function () {
  48223. this.mesh.dispose();
  48224. this.vars = null;
  48225. // drop references to internal big arrays for the GC
  48226. this._positions = null;
  48227. this._indices = null;
  48228. this._normals = null;
  48229. this._uvs = null;
  48230. this._colors = null;
  48231. this._positions32 = null;
  48232. this._normals32 = null;
  48233. this._fixedNormal32 = null;
  48234. this._uvs32 = null;
  48235. this._colors32 = null;
  48236. this.pickedParticles = null;
  48237. };
  48238. /**
  48239. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48240. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48241. */
  48242. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48243. if (!this._isVisibilityBoxLocked) {
  48244. this.mesh.refreshBoundingInfo();
  48245. }
  48246. };
  48247. /**
  48248. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48249. * @param size the size (float) of the visibility box
  48250. * note : this doesn't lock the SPS mesh bounding box.
  48251. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48252. */
  48253. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48254. var vis = size / 2;
  48255. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48256. };
  48257. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48258. // getter and setter
  48259. get: function () {
  48260. return this._alwaysVisible;
  48261. },
  48262. /**
  48263. * Sets the SPS as always visible or not
  48264. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48265. */
  48266. set: function (val) {
  48267. this._alwaysVisible = val;
  48268. this.mesh.alwaysSelectAsActiveMesh = val;
  48269. },
  48270. enumerable: true,
  48271. configurable: true
  48272. });
  48273. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48274. get: function () {
  48275. return this._isVisibilityBoxLocked;
  48276. },
  48277. /**
  48278. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48279. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48280. */
  48281. set: function (val) {
  48282. this._isVisibilityBoxLocked = val;
  48283. this.mesh.getBoundingInfo().isLocked = val;
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48289. // getters
  48290. get: function () {
  48291. return this._computeParticleRotation;
  48292. },
  48293. // Optimizer setters
  48294. /**
  48295. * Tells to `setParticles()` to compute the particle rotations or not.
  48296. * Default value : true. The SPS is faster when it's set to false.
  48297. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48298. */
  48299. set: function (val) {
  48300. this._computeParticleRotation = val;
  48301. },
  48302. enumerable: true,
  48303. configurable: true
  48304. });
  48305. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48306. get: function () {
  48307. return this._computeParticleColor;
  48308. },
  48309. /**
  48310. * Tells to `setParticles()` to compute the particle colors or not.
  48311. * Default value : true. The SPS is faster when it's set to false.
  48312. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48313. */
  48314. set: function (val) {
  48315. this._computeParticleColor = val;
  48316. },
  48317. enumerable: true,
  48318. configurable: true
  48319. });
  48320. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48321. get: function () {
  48322. return this._computeParticleTexture;
  48323. },
  48324. /**
  48325. * Tells to `setParticles()` to compute the particle textures or not.
  48326. * Default value : true. The SPS is faster when it's set to false.
  48327. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48328. */
  48329. set: function (val) {
  48330. this._computeParticleTexture = val;
  48331. },
  48332. enumerable: true,
  48333. configurable: true
  48334. });
  48335. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48336. get: function () {
  48337. return this._computeParticleVertex;
  48338. },
  48339. /**
  48340. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48341. * Default value : false. The SPS is faster when it's set to false.
  48342. * Note : the particle custom vertex positions aren't stored values.
  48343. */
  48344. set: function (val) {
  48345. this._computeParticleVertex = val;
  48346. },
  48347. enumerable: true,
  48348. configurable: true
  48349. });
  48350. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48351. get: function () {
  48352. return this._computeBoundingBox;
  48353. },
  48354. /**
  48355. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48356. */
  48357. set: function (val) {
  48358. this._computeBoundingBox = val;
  48359. },
  48360. enumerable: true,
  48361. configurable: true
  48362. });
  48363. // =======================================================================
  48364. // Particle behavior logic
  48365. // these following methods may be overwritten by the user to fit his needs
  48366. /**
  48367. * This function does nothing. It may be overwritten to set all the particle first values.
  48368. * The SPS doesn't call this function, you may have to call it by your own.
  48369. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48370. */
  48371. SolidParticleSystem.prototype.initParticles = function () {
  48372. };
  48373. /**
  48374. * This function does nothing. It may be overwritten to recycle a particle.
  48375. * The SPS doesn't call this function, you may have to call it by your own.
  48376. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48377. */
  48378. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48379. return particle;
  48380. };
  48381. /**
  48382. * Updates a particle : this function should be overwritten by the user.
  48383. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48384. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48385. * ex : just set a particle position or velocity and recycle conditions
  48386. */
  48387. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48388. return particle;
  48389. };
  48390. /**
  48391. * Updates a vertex of a particle : it can be overwritten by the user.
  48392. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48393. * @param particle the current particle
  48394. * @param vertex the current index of the current particle
  48395. * @param pt the index of the current vertex in the particle shape
  48396. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48397. * ex : just set a vertex particle position
  48398. */
  48399. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48400. return vertex;
  48401. };
  48402. /**
  48403. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48404. * This does nothing and may be overwritten by the user.
  48405. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48406. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48407. * @param update the boolean update value actually passed to setParticles()
  48408. */
  48409. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48410. };
  48411. /**
  48412. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48413. * This will be passed three parameters.
  48414. * This does nothing and may be overwritten by the user.
  48415. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48416. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48417. * @param update the boolean update value actually passed to setParticles()
  48418. */
  48419. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48420. };
  48421. return SolidParticleSystem;
  48422. })();
  48423. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48424. })(BABYLON || (BABYLON = {}));
  48425. var BABYLON;
  48426. (function (BABYLON) {
  48427. var Internals;
  48428. (function (Internals) {
  48429. var FileFaceOrientation = (function () {
  48430. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48431. this.name = name;
  48432. this.worldAxisForNormal = worldAxisForNormal;
  48433. this.worldAxisForFileX = worldAxisForFileX;
  48434. this.worldAxisForFileY = worldAxisForFileY;
  48435. }
  48436. return FileFaceOrientation;
  48437. })();
  48438. ;
  48439. /**
  48440. * Helper class dealing with the extraction of spherical polynomial dataArray
  48441. * from a cube map.
  48442. */
  48443. var CubeMapToSphericalPolynomialTools = (function () {
  48444. function CubeMapToSphericalPolynomialTools() {
  48445. }
  48446. /**
  48447. * Converts a cubemap to the according Spherical Polynomial data.
  48448. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48449. *
  48450. * @param cubeInfo The Cube map to extract the information from.
  48451. * @return The Spherical Polynomial data.
  48452. */
  48453. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48454. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48455. var totalSolidAngle = 0.0;
  48456. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48457. var du = 2.0 / cubeInfo.size;
  48458. var dv = du;
  48459. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48460. var minUV = du * 0.5 - 1.0;
  48461. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48462. var fileFace = this.FileFaces[faceIndex];
  48463. var dataArray = cubeInfo[fileFace.name];
  48464. var v = minUV;
  48465. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48466. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48467. // Because SP is still linear, so summation is fine in that basis.
  48468. for (var y = 0; y < cubeInfo.size; y++) {
  48469. var u = minUV;
  48470. for (var x = 0; x < cubeInfo.size; x++) {
  48471. // World direction (not normalised)
  48472. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48473. worldDirection.normalize();
  48474. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48475. if (1) {
  48476. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  48477. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  48478. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  48479. var color = new BABYLON.Color3(r, g, b);
  48480. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48481. }
  48482. else {
  48483. if (faceIndex == 0) {
  48484. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48485. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48486. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48487. }
  48488. else if (faceIndex == 1) {
  48489. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48490. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48491. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48492. }
  48493. else if (faceIndex == 2) {
  48494. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48495. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48496. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48497. }
  48498. else if (faceIndex == 3) {
  48499. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48500. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48501. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48502. }
  48503. else if (faceIndex == 4) {
  48504. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48505. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48506. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48507. }
  48508. else if (faceIndex == 5) {
  48509. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48510. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48511. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48512. }
  48513. 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]);
  48514. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48515. }
  48516. totalSolidAngle += deltaSolidAngle;
  48517. u += du;
  48518. }
  48519. v += dv;
  48520. }
  48521. }
  48522. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  48523. var correction = correctSolidAngle / totalSolidAngle;
  48524. sphericalHarmonics.scale(correction);
  48525. // Additionally scale by pi -- audit needed
  48526. sphericalHarmonics.scale(1.0 / Math.PI);
  48527. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48528. };
  48529. CubeMapToSphericalPolynomialTools.FileFaces = [
  48530. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48531. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48532. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48533. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48534. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48535. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48536. ];
  48537. return CubeMapToSphericalPolynomialTools;
  48538. })();
  48539. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48540. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48541. })(BABYLON || (BABYLON = {}));
  48542. var BABYLON;
  48543. (function (BABYLON) {
  48544. var Internals;
  48545. (function (Internals) {
  48546. /**
  48547. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48548. */
  48549. var PanoramaToCubeMapTools = (function () {
  48550. function PanoramaToCubeMapTools() {
  48551. }
  48552. /**
  48553. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48554. *
  48555. * @param float32Array The source data.
  48556. * @param inputWidth The width of the input panorama.
  48557. * @param inputhHeight The height of the input panorama.
  48558. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48559. * @return The cubemap data
  48560. */
  48561. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48562. if (!float32Array) {
  48563. throw "ConvertPanoramaToCubemap: input cannot be null";
  48564. }
  48565. if (float32Array.length != inputWidth * inputHeight * 3) {
  48566. throw "ConvertPanoramaToCubemap: input size is wrong";
  48567. }
  48568. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48569. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48570. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48571. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48572. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48573. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48574. return {
  48575. front: textureFront,
  48576. back: textureBack,
  48577. left: textureLeft,
  48578. right: textureRight,
  48579. up: textureUp,
  48580. down: textureDown,
  48581. size: size
  48582. };
  48583. };
  48584. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48585. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48586. var textureArray = new Float32Array(buffer);
  48587. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48588. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48589. var dy = 1 / texSize;
  48590. var fy = 0;
  48591. for (var y = 0; y < texSize; y++) {
  48592. var xv1 = faceData[0];
  48593. var xv2 = faceData[2];
  48594. for (var x = 0; x < texSize; x++) {
  48595. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48596. v.normalize();
  48597. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48598. // 3 channels per pixels
  48599. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48600. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48601. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48602. xv1 = xv1.add(rotDX1);
  48603. xv2 = xv2.add(rotDX2);
  48604. }
  48605. fy += dy;
  48606. }
  48607. return textureArray;
  48608. };
  48609. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48610. var theta = Math.atan2(vDir.z, vDir.x);
  48611. var phi = Math.acos(vDir.y);
  48612. while (theta < -Math.PI)
  48613. theta += 2 * Math.PI;
  48614. while (theta > Math.PI)
  48615. theta -= 2 * Math.PI;
  48616. var dx = theta / Math.PI;
  48617. var dy = phi / Math.PI;
  48618. // recenter.
  48619. dx = dx * 0.5 + 0.5;
  48620. var px = Math.round(dx * inputWidth);
  48621. if (px < 0)
  48622. px = 0;
  48623. else if (px >= inputWidth)
  48624. px = inputWidth - 1;
  48625. var py = Math.round(dy * inputHeight);
  48626. if (py < 0)
  48627. py = 0;
  48628. else if (py >= inputHeight)
  48629. py = inputHeight - 1;
  48630. var inputY = (inputHeight - py - 1);
  48631. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48632. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48633. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48634. return {
  48635. r: r,
  48636. g: g,
  48637. b: b
  48638. };
  48639. };
  48640. PanoramaToCubeMapTools.FACE_FRONT = [
  48641. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48642. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48643. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48644. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48645. ];
  48646. PanoramaToCubeMapTools.FACE_BACK = [
  48647. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48648. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48649. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48650. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48651. ];
  48652. PanoramaToCubeMapTools.FACE_RIGHT = [
  48653. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48654. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48655. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48656. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48657. ];
  48658. PanoramaToCubeMapTools.FACE_LEFT = [
  48659. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48660. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48661. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48662. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48663. ];
  48664. PanoramaToCubeMapTools.FACE_DOWN = [
  48665. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48666. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48667. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48668. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48669. ];
  48670. PanoramaToCubeMapTools.FACE_UP = [
  48671. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48672. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48673. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48674. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48675. ];
  48676. return PanoramaToCubeMapTools;
  48677. })();
  48678. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48679. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48680. })(BABYLON || (BABYLON = {}));
  48681. var BABYLON;
  48682. (function (BABYLON) {
  48683. var Internals;
  48684. (function (Internals) {
  48685. ;
  48686. /**
  48687. * This groups tools to convert HDR texture to native colors array.
  48688. */
  48689. var HDRTools = (function () {
  48690. function HDRTools() {
  48691. }
  48692. HDRTools.Ldexp = function (mantissa, exponent) {
  48693. if (exponent > 1023) {
  48694. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48695. }
  48696. if (exponent < -1074) {
  48697. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48698. }
  48699. return mantissa * Math.pow(2, exponent);
  48700. };
  48701. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48702. if (exponent > 0) {
  48703. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48704. float32array[index + 0] = red * exponent;
  48705. float32array[index + 1] = green * exponent;
  48706. float32array[index + 2] = blue * exponent;
  48707. }
  48708. else {
  48709. float32array[index + 0] = 0;
  48710. float32array[index + 1] = 0;
  48711. float32array[index + 2] = 0;
  48712. }
  48713. };
  48714. HDRTools.readStringLine = function (uint8array, startIndex) {
  48715. var line = "";
  48716. var character = "";
  48717. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48718. character = String.fromCharCode(uint8array[i]);
  48719. if (character == "\n") {
  48720. break;
  48721. }
  48722. line += character;
  48723. }
  48724. return line;
  48725. };
  48726. /**
  48727. * Reads header information from an RGBE texture stored in a native array.
  48728. * More information on this format are available here:
  48729. * https://en.wikipedia.org/wiki/RGBE_image_format
  48730. *
  48731. * @param uint8array The binary file stored in native array.
  48732. * @return The header information.
  48733. */
  48734. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48735. var height = 0;
  48736. var width = 0;
  48737. var line = this.readStringLine(uint8array, 0);
  48738. if (line[0] != '#' || line[1] != '?') {
  48739. throw "Bad HDR Format.";
  48740. }
  48741. var endOfHeader = false;
  48742. var findFormat = false;
  48743. var lineIndex = 0;
  48744. do {
  48745. lineIndex += (line.length + 1);
  48746. line = this.readStringLine(uint8array, lineIndex);
  48747. if (line == "FORMAT=32-bit_rle_rgbe") {
  48748. findFormat = true;
  48749. }
  48750. else if (line.length == 0) {
  48751. endOfHeader = true;
  48752. }
  48753. } while (!endOfHeader);
  48754. if (!findFormat) {
  48755. throw "HDR Bad header format, unsupported FORMAT";
  48756. }
  48757. lineIndex += (line.length + 1);
  48758. line = this.readStringLine(uint8array, lineIndex);
  48759. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48760. var match = sizeRegexp.exec(line);
  48761. // TODO. Support +Y and -X if needed.
  48762. if (match.length < 3) {
  48763. throw "HDR Bad header format, no size";
  48764. }
  48765. width = parseInt(match[2]);
  48766. height = parseInt(match[1]);
  48767. if (width < 8 || width > 0x7fff) {
  48768. throw "HDR Bad header format, unsupported size";
  48769. }
  48770. lineIndex += (line.length + 1);
  48771. return {
  48772. height: height,
  48773. width: width,
  48774. dataPosition: lineIndex
  48775. };
  48776. };
  48777. /**
  48778. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48779. * This RGBE texture needs to store the information as a panorama.
  48780. *
  48781. * More information on this format are available here:
  48782. * https://en.wikipedia.org/wiki/RGBE_image_format
  48783. *
  48784. * @param buffer The binary file stored in an array buffer.
  48785. * @param size The expected size of the extracted cubemap.
  48786. * @return The Cube Map information.
  48787. */
  48788. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48789. var uint8array = new Uint8Array(buffer);
  48790. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48791. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48792. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48793. return cubeMapData;
  48794. };
  48795. /**
  48796. * Returns the pixels data extracted from an RGBE texture.
  48797. * This pixels will be stored left to right up to down in the R G B order in one array.
  48798. *
  48799. * More information on this format are available here:
  48800. * https://en.wikipedia.org/wiki/RGBE_image_format
  48801. *
  48802. * @param uint8array The binary file stored in an array buffer.
  48803. * @param hdrInfo The header information of the file.
  48804. * @return The pixels data in RGB right to left up to down order.
  48805. */
  48806. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48807. // Keep for multi format supports.
  48808. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48809. };
  48810. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48811. var num_scanlines = hdrInfo.height;
  48812. var scanline_width = hdrInfo.width;
  48813. var a, b, c, d, count;
  48814. var dataIndex = hdrInfo.dataPosition;
  48815. var index = 0, endIndex = 0, i = 0;
  48816. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48817. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48818. // 3 channels of 4 bytes per pixel in float.
  48819. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48820. var resultArray = new Float32Array(resultBuffer);
  48821. // read in each successive scanline
  48822. while (num_scanlines > 0) {
  48823. a = uint8array[dataIndex++];
  48824. b = uint8array[dataIndex++];
  48825. c = uint8array[dataIndex++];
  48826. d = uint8array[dataIndex++];
  48827. if (a != 2 || b != 2 || (c & 0x80)) {
  48828. // this file is not run length encoded
  48829. throw "HDR Bad header format, not RLE";
  48830. }
  48831. if (((c << 8) | d) != scanline_width) {
  48832. throw "HDR Bad header format, wrong scan line width";
  48833. }
  48834. index = 0;
  48835. // read each of the four channels for the scanline into the buffer
  48836. for (i = 0; i < 4; i++) {
  48837. endIndex = (i + 1) * scanline_width;
  48838. while (index < endIndex) {
  48839. a = uint8array[dataIndex++];
  48840. b = uint8array[dataIndex++];
  48841. if (a > 128) {
  48842. // a run of the same value
  48843. count = a - 128;
  48844. if ((count == 0) || (count > endIndex - index)) {
  48845. throw "HDR Bad Format, bad scanline data (run)";
  48846. }
  48847. while (count-- > 0) {
  48848. scanLineArray[index++] = b;
  48849. }
  48850. }
  48851. else {
  48852. // a non-run
  48853. count = a;
  48854. if ((count == 0) || (count > endIndex - index)) {
  48855. throw "HDR Bad Format, bad scanline data (non-run)";
  48856. }
  48857. scanLineArray[index++] = b;
  48858. if (--count > 0) {
  48859. for (var j = 0; j < count; j++) {
  48860. scanLineArray[index++] = uint8array[dataIndex++];
  48861. }
  48862. }
  48863. }
  48864. }
  48865. }
  48866. // now convert data from buffer into floats
  48867. for (i = 0; i < scanline_width; i++) {
  48868. a = scanLineArray[i];
  48869. b = scanLineArray[i + scanline_width];
  48870. c = scanLineArray[i + 2 * scanline_width];
  48871. d = scanLineArray[i + 3 * scanline_width];
  48872. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48873. }
  48874. num_scanlines--;
  48875. }
  48876. return resultArray;
  48877. };
  48878. return HDRTools;
  48879. })();
  48880. Internals.HDRTools = HDRTools;
  48881. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48882. })(BABYLON || (BABYLON = {}));
  48883. //_______________________________________________________________
  48884. // Extracted from CubeMapGen:
  48885. // https://code.google.com/archive/p/cubemapgen/
  48886. //
  48887. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48888. //_______________________________________________________________
  48889. var BABYLON;
  48890. (function (BABYLON) {
  48891. var Internals;
  48892. (function (Internals) {
  48893. /**
  48894. * The bounding box information used during the conversion process.
  48895. */
  48896. var CMGBoundinBox = (function () {
  48897. function CMGBoundinBox() {
  48898. this.min = new BABYLON.Vector3(0, 0, 0);
  48899. this.max = new BABYLON.Vector3(0, 0, 0);
  48900. this.clear();
  48901. }
  48902. CMGBoundinBox.prototype.clear = function () {
  48903. this.min.x = CMGBoundinBox.MAX;
  48904. this.min.y = CMGBoundinBox.MAX;
  48905. this.min.z = CMGBoundinBox.MAX;
  48906. this.max.x = CMGBoundinBox.MIN;
  48907. this.max.y = CMGBoundinBox.MIN;
  48908. this.max.z = CMGBoundinBox.MIN;
  48909. };
  48910. CMGBoundinBox.prototype.augment = function (x, y, z) {
  48911. this.min.x = Math.min(this.min.x, x);
  48912. this.min.y = Math.min(this.min.y, y);
  48913. this.min.z = Math.min(this.min.z, z);
  48914. this.max.x = Math.max(this.max.x, x);
  48915. this.max.y = Math.max(this.max.y, y);
  48916. this.max.z = Math.max(this.max.z, z);
  48917. };
  48918. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  48919. this.min.x = Math.max(this.min.x, x);
  48920. this.min.y = Math.max(this.min.y, y);
  48921. this.min.z = Math.max(this.min.z, z);
  48922. };
  48923. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  48924. this.max.x = Math.min(this.max.x, x);
  48925. this.max.y = Math.min(this.max.y, y);
  48926. this.max.z = Math.min(this.max.z, z);
  48927. };
  48928. CMGBoundinBox.prototype.empty = function () {
  48929. if ((this.min.x > this.max.y) ||
  48930. (this.min.y > this.max.y) ||
  48931. (this.min.z > this.max.y)) {
  48932. return true;
  48933. }
  48934. else {
  48935. return false;
  48936. }
  48937. };
  48938. CMGBoundinBox.MAX = Number.MAX_VALUE;
  48939. CMGBoundinBox.MIN = Number.MIN_VALUE;
  48940. return CMGBoundinBox;
  48941. })();
  48942. /**
  48943. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  48944. * required by the glossinees of a material.
  48945. *
  48946. * This only supports the cosine drop power as well as Warp fixup generation method.
  48947. *
  48948. * This is using the process from CubeMapGen described here:
  48949. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48950. */
  48951. var PMREMGenerator = (function () {
  48952. /**
  48953. * Constructor of the generator.
  48954. *
  48955. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  48956. * @param inputSize The size of the cubemap faces
  48957. * @param outputSize The size of the output cubemap faces
  48958. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  48959. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  48960. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  48961. * @param specularPower The max specular level of the desired cubemap
  48962. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  48963. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  48964. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  48965. */
  48966. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  48967. this.input = input;
  48968. this.inputSize = inputSize;
  48969. this.outputSize = outputSize;
  48970. this.maxNumMipLevels = maxNumMipLevels;
  48971. this.numChannels = numChannels;
  48972. this.isFloat = isFloat;
  48973. this.specularPower = specularPower;
  48974. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  48975. this.excludeBase = excludeBase;
  48976. this.fixup = fixup;
  48977. this._outputSurface = [];
  48978. this._numMipLevels = 0;
  48979. }
  48980. /**
  48981. * Launches the filter process and return the result.
  48982. *
  48983. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  48984. */
  48985. PMREMGenerator.prototype.filterCubeMap = function () {
  48986. // Init cubemap processor
  48987. this.init();
  48988. // Filters the cubemap
  48989. this.filterCubeMapMipChain();
  48990. // Returns the filtered mips.
  48991. return this._outputSurface;
  48992. };
  48993. PMREMGenerator.prototype.init = function () {
  48994. var i;
  48995. var j;
  48996. var mipLevelSize;
  48997. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  48998. if (this.maxNumMipLevels == 0) {
  48999. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  49000. }
  49001. //first miplevel size
  49002. mipLevelSize = this.outputSize;
  49003. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  49004. for (j = 0; j < this.maxNumMipLevels; j++) {
  49005. this._outputSurface.length++;
  49006. this._outputSurface[j] = [];
  49007. //Iterate over faces for output images
  49008. for (i = 0; i < 6; i++) {
  49009. this._outputSurface[j].length++;
  49010. // Initializes a new array for the output.
  49011. if (this.isFloat) {
  49012. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49013. }
  49014. else {
  49015. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49016. }
  49017. }
  49018. //next mip level is half size
  49019. mipLevelSize >>= 1;
  49020. this._numMipLevels++;
  49021. //terminate if mip chain becomes too small
  49022. if (mipLevelSize == 0) {
  49023. this.maxNumMipLevels = j;
  49024. return;
  49025. }
  49026. }
  49027. };
  49028. //--------------------------------------------------------------------------------------
  49029. //Cube map filtering and mip chain generation.
  49030. // the cube map filtereing is specified using a number of parameters:
  49031. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  49032. // indicates the region of the hemisphere to filter over for each tap.
  49033. //
  49034. // Note that the top mip level is also a filtered version of the original input images
  49035. // as well in order to create mip chains for diffuse environment illumination.
  49036. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  49037. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  49038. //
  49039. // Then the mip angle used to genreate the next level of the mip chain from the first level
  49040. // is a_InitialMipAngle
  49041. //
  49042. // The angle for the subsequent levels of the mip chain are specified by their parents
  49043. // filtering angle and a per-level scale and bias
  49044. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  49045. //
  49046. //--------------------------------------------------------------------------------------
  49047. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  49048. // First, take count of the lighting model to modify SpecularPower
  49049. // 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;
  49050. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  49051. //Cone angle start (for generating subsequent mip levels)
  49052. var currentSpecularPower = this.specularPower;
  49053. //Build filter lookup tables based on the source miplevel size
  49054. this.precomputeFilterLookupTables(this.inputSize);
  49055. // Note that we need to filter the first level before generating mipmap
  49056. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  49057. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  49058. // TODO : Write a function to copy and scale the base mipmap in output
  49059. // I am just lazy here and just put a high specular power value, and do some if.
  49060. if (this.excludeBase && (levelIndex == 0)) {
  49061. // 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).
  49062. currentSpecularPower = 100000.0;
  49063. }
  49064. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  49065. var srcCubeImage = this.input;
  49066. var dstCubeImage = this._outputSurface[levelIndex];
  49067. var dstSize = this.outputSize >> levelIndex;
  49068. // Compute required angle.
  49069. var angle = this.getBaseFilterAngle(currentSpecularPower);
  49070. // filter cube surfaces
  49071. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  49072. // fix seams
  49073. if (this.fixup) {
  49074. this.fixupCubeEdges(dstCubeImage, dstSize);
  49075. }
  49076. // Decrease the specular power to generate the mipmap chain
  49077. // TODO : Use another method for Exclude (see first comment at start of the function
  49078. if (this.excludeBase && (levelIndex == 0)) {
  49079. currentSpecularPower = this.specularPower;
  49080. }
  49081. currentSpecularPower *= this.cosinePowerDropPerMip;
  49082. }
  49083. };
  49084. //--------------------------------------------------------------------------------------
  49085. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  49086. // It allow to optimize the texel to access base on the specular power.
  49087. //--------------------------------------------------------------------------------------
  49088. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  49089. // We want to find the alpha such that:
  49090. // cos(alpha)^cosinePower = epsilon
  49091. // That's: acos(epsilon^(1/cosinePower))
  49092. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  49093. var angle = 180.0;
  49094. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  49095. angle *= 180.0 / Math.PI; // Convert to degree
  49096. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  49097. return angle;
  49098. };
  49099. //--------------------------------------------------------------------------------------
  49100. //Builds the following lookup tables prior to filtering:
  49101. // -normalizer cube map
  49102. // -tap weight lookup table
  49103. //
  49104. //--------------------------------------------------------------------------------------
  49105. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  49106. var srcTexelAngle;
  49107. var iCubeFace;
  49108. //clear pre-existing normalizer cube map
  49109. this._normCubeMap = [];
  49110. //Normalized vectors per cubeface and per-texel solid angle
  49111. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  49112. };
  49113. //--------------------------------------------------------------------------------------
  49114. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  49115. //
  49116. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  49117. //
  49118. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  49119. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  49120. // below
  49121. //--------------------------------------------------------------------------------------
  49122. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  49123. var iCubeFace;
  49124. var u;
  49125. var v;
  49126. //iterate over cube faces
  49127. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49128. //First three channels for norm cube, and last channel for solid angle
  49129. this._normCubeMap.push(new Float32Array(size * size * 4));
  49130. //fast texture walk, build normalizer cube map
  49131. var facesData = this.input[iCubeFace];
  49132. for (v = 0; v < size; v++) {
  49133. for (u = 0; u < size; u++) {
  49134. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  49135. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  49136. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  49137. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  49138. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  49139. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  49140. }
  49141. }
  49142. }
  49143. };
  49144. //--------------------------------------------------------------------------------------
  49145. // Convert cubemap face texel coordinates and face idx to 3D vector
  49146. // note the U and V coords are integer coords and range from 0 to size-1
  49147. // this routine can be used to generate a normalizer cube map
  49148. //--------------------------------------------------------------------------------------
  49149. // SL BEGIN
  49150. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  49151. var nvcU;
  49152. var nvcV;
  49153. var tempVec;
  49154. // Change from original AMD code
  49155. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49156. // + 0.5f is for texel center addressing
  49157. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  49158. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  49159. // warp fixup
  49160. if (fixup && size > 1) {
  49161. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  49162. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  49163. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  49164. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  49165. }
  49166. // Get current vector
  49167. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  49168. // U contribution
  49169. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49170. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  49171. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  49172. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  49173. // V contribution and Sum
  49174. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49175. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  49176. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  49177. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  49178. //add face axis
  49179. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  49180. PMREMGenerator._vectorTemp.x += faceAxis[0];
  49181. PMREMGenerator._vectorTemp.y += faceAxis[1];
  49182. PMREMGenerator._vectorTemp.z += faceAxis[2];
  49183. //normalize vector
  49184. PMREMGenerator._vectorTemp.normalize();
  49185. return PMREMGenerator._vectorTemp;
  49186. };
  49187. //--------------------------------------------------------------------------------------
  49188. // Convert 3D vector to cubemap face texel coordinates and face idx
  49189. // note the U and V coords are integer coords and range from 0 to size-1
  49190. // this routine can be used to generate a normalizer cube map
  49191. //
  49192. // returns face IDX and texel coords
  49193. //--------------------------------------------------------------------------------------
  49194. // SL BEGIN
  49195. /*
  49196. Mapping Texture Coordinates to Cube Map Faces
  49197. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  49198. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  49199. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  49200. map arrangement in Pixar's RenderMan package.
  49201. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  49202. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  49203. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  49204. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  49205. the major axis direction). The target column in the table below explains how the major axis direction
  49206. maps to the 2D image of a particular cube map target.
  49207. major axis
  49208. direction target sc tc ma
  49209. ---------- --------------------------------- --- --- ---
  49210. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  49211. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  49212. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  49213. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  49214. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  49215. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  49216. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  49217. an updated (s,t) is calculated as follows
  49218. s = ( sc/|ma| + 1 ) / 2
  49219. t = ( tc/|ma| + 1 ) / 2
  49220. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  49221. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  49222. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  49223. */
  49224. // Note this method return U and V in range from 0 to size-1
  49225. // SL END
  49226. // Store the information in vector3 for convenience (faceindex, u, v)
  49227. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  49228. var maxCoord;
  49229. var faceIdx;
  49230. //absolute value 3
  49231. var absX = Math.abs(x);
  49232. var absY = Math.abs(y);
  49233. var absZ = Math.abs(z);
  49234. if (absX >= absY && absX >= absZ) {
  49235. maxCoord = absX;
  49236. if (x >= 0) {
  49237. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  49238. }
  49239. else {
  49240. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49241. }
  49242. }
  49243. else if (absY >= absX && absY >= absZ) {
  49244. maxCoord = absY;
  49245. if (y >= 0) {
  49246. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49247. }
  49248. else {
  49249. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49250. }
  49251. }
  49252. else {
  49253. maxCoord = absZ;
  49254. if (z >= 0) {
  49255. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49256. }
  49257. else {
  49258. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49259. }
  49260. }
  49261. //divide through by max coord so face vector lies on cube face
  49262. var scale = 1 / maxCoord;
  49263. x *= scale;
  49264. y *= scale;
  49265. z *= scale;
  49266. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49267. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  49268. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49269. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  49270. // Modify original AMD code to return value from 0 to Size - 1
  49271. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  49272. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  49273. PMREMGenerator._vectorTemp.x = faceIdx;
  49274. PMREMGenerator._vectorTemp.y = u;
  49275. PMREMGenerator._vectorTemp.z = v;
  49276. return PMREMGenerator._vectorTemp;
  49277. };
  49278. //--------------------------------------------------------------------------------------
  49279. //Original code from Ignacio CastaÒo
  49280. // This formula is from Manne ÷hrstrˆm's thesis.
  49281. // Take two coordiantes in the range [-1, 1] that define a portion of a
  49282. // cube face and return the area of the projection of that portion on the
  49283. // surface of the sphere.
  49284. //--------------------------------------------------------------------------------------
  49285. PMREMGenerator.prototype.areaElement = function (x, y) {
  49286. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  49287. };
  49288. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  49289. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49290. // (+ 0.5f is for texel center addressing)
  49291. u = (2.0 * (u + 0.5) / size) - 1.0;
  49292. v = (2.0 * (v + 0.5) / size) - 1.0;
  49293. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  49294. var invResolution = 1.0 / size;
  49295. // U and V are the -1..1 texture coordinate on the current face.
  49296. // Get projected area for this texel
  49297. var x0 = u - invResolution;
  49298. var y0 = v - invResolution;
  49299. var x1 = u + invResolution;
  49300. var y1 = v + invResolution;
  49301. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  49302. return solidAngle;
  49303. };
  49304. //--------------------------------------------------------------------------------------
  49305. //The key to the speed of these filtering routines is to quickly define a per-face
  49306. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  49307. // Later these pixels are selectively processed based on their dot products to see if
  49308. // they reside within the filtering cone.
  49309. //
  49310. //This is done by computing the smallest per-texel angle to get a conservative estimate
  49311. // of the number of texels needed to be covered in width and height order to filter the
  49312. // region. the bounding box for the center taps face is defined first, and if the
  49313. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  49314. // defined next
  49315. //--------------------------------------------------------------------------------------
  49316. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  49317. // note that pixels within these regions may be rejected
  49318. // based on the anlge
  49319. var iCubeFace;
  49320. var u;
  49321. var v;
  49322. // bounding box per face to specify region to process
  49323. var filterExtents = [];
  49324. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49325. filterExtents.push(new CMGBoundinBox());
  49326. }
  49327. // min angle a src texel can cover (in degrees)
  49328. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  49329. // angle about center tap to define filter cone
  49330. // filter angle is 1/2 the cone angle
  49331. var filterAngle = filterConeAngle / 2.0;
  49332. //ensure filter angle is larger than a texel
  49333. if (filterAngle < srcTexelAngle) {
  49334. filterAngle = srcTexelAngle;
  49335. }
  49336. //ensure filter cone is always smaller than the hemisphere
  49337. if (filterAngle > 90.0) {
  49338. filterAngle = 90.0;
  49339. }
  49340. // the maximum number of texels in 1D the filter cone angle will cover
  49341. // used to determine bounding box size for filter extents
  49342. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  49343. // ensure conservative region always covers at least one texel
  49344. if (filterSize < 1) {
  49345. filterSize = 1;
  49346. }
  49347. // dotProdThresh threshold based on cone angle to determine whether or not taps
  49348. // reside within the cone angle
  49349. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  49350. // process required faces
  49351. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49352. //iterate over dst cube map face texel
  49353. for (v = 0; v < dstSize; v++) {
  49354. for (u = 0; u < dstSize; u++) {
  49355. //get center tap direction
  49356. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  49357. //clear old per-face filter extents
  49358. this.clearFilterExtents(filterExtents);
  49359. //define per-face filter extents
  49360. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  49361. //perform filtering of src faces using filter extents
  49362. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  49363. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  49364. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  49365. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  49366. }
  49367. }
  49368. }
  49369. };
  49370. //--------------------------------------------------------------------------------------
  49371. //Clear filter extents for the 6 cube map faces
  49372. //--------------------------------------------------------------------------------------
  49373. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  49374. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  49375. filterExtents[iCubeFaces].clear();
  49376. }
  49377. };
  49378. //--------------------------------------------------------------------------------------
  49379. //Define per-face bounding box filter extents
  49380. //
  49381. // These define conservative texel regions in each of the faces the filter can possibly
  49382. // process. When the pixels in the regions are actually processed, the dot product
  49383. // between the tap vector and the center tap vector is used to determine the weight of
  49384. // the tap and whether or not the tap is within the cone.
  49385. //
  49386. //--------------------------------------------------------------------------------------
  49387. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  49388. //neighboring face and bleed over amount, and width of BBOX for
  49389. // left, right, top, and bottom edges of this face
  49390. var bleedOverAmount = [0, 0, 0, 0];
  49391. var bleedOverBBoxMin = [0, 0, 0, 0];
  49392. var bleedOverBBoxMax = [0, 0, 0, 0];
  49393. var neighborFace;
  49394. var neighborEdge;
  49395. var oppositeFaceIdx;
  49396. //get face idx, and u, v info from center tap dir
  49397. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  49398. var faceIdx = result.x;
  49399. var u = result.y;
  49400. var v = result.z;
  49401. //define bbox size within face
  49402. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  49403. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  49404. filterExtents[faceIdx].clampMin(0, 0, 0);
  49405. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  49406. //u and v extent in face corresponding to center tap
  49407. var minU = filterExtents[faceIdx].min.x;
  49408. var minV = filterExtents[faceIdx].min.y;
  49409. var maxU = filterExtents[faceIdx].max.x;
  49410. var maxV = filterExtents[faceIdx].max.y;
  49411. //bleed over amounts for face across u=0 edge (left)
  49412. bleedOverAmount[0] = (bboxSize - u);
  49413. bleedOverBBoxMin[0] = minV;
  49414. bleedOverBBoxMax[0] = maxV;
  49415. //bleed over amounts for face across u=1 edge (right)
  49416. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  49417. bleedOverBBoxMin[1] = minV;
  49418. bleedOverBBoxMax[1] = maxV;
  49419. //bleed over to face across v=0 edge (up)
  49420. bleedOverAmount[2] = (bboxSize - v);
  49421. bleedOverBBoxMin[2] = minU;
  49422. bleedOverBBoxMax[2] = maxU;
  49423. //bleed over to face across v=1 edge (down)
  49424. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  49425. bleedOverBBoxMin[3] = minU;
  49426. bleedOverBBoxMax[3] = maxU;
  49427. //compute bleed over regions in neighboring faces
  49428. for (var i = 0; i < 4; i++) {
  49429. if (bleedOverAmount[i] > 0) {
  49430. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  49431. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  49432. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  49433. // be flipped: the cases are
  49434. // if a left edge mates with a left or bottom edge on the neighbor
  49435. // if a top edge mates with a top or right edge on the neighbor
  49436. // if a right edge mates with a right or top edge on the neighbor
  49437. // if a bottom edge mates with a bottom or left edge on the neighbor
  49438. //Seeing as the edges are enumerated as follows
  49439. // left =0
  49440. // right =1
  49441. // top =2
  49442. // bottom =3
  49443. //
  49444. // so if the edge enums are the same, or the sum of the enums == 3,
  49445. // the bbox needs to be flipped
  49446. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  49447. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  49448. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  49449. }
  49450. //The way the bounding box is extended onto the neighboring face
  49451. // depends on which edge of neighboring face abuts with this one
  49452. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  49453. case PMREMGenerator.CP_EDGE_LEFT:
  49454. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  49455. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49456. break;
  49457. case PMREMGenerator.CP_EDGE_RIGHT:
  49458. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  49459. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49460. break;
  49461. case PMREMGenerator.CP_EDGE_TOP:
  49462. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  49463. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  49464. break;
  49465. case PMREMGenerator.CP_EDGE_BOTTOM:
  49466. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  49467. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  49468. break;
  49469. }
  49470. //clamp filter extents in non-center tap faces to remain within surface
  49471. filterExtents[neighborFace].clampMin(0, 0, 0);
  49472. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  49473. }
  49474. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  49475. // from the center tap face, then process the opposite face entirely for now.
  49476. //Note that the cases in which this happens, what usually happens is that
  49477. // more than one edge bleeds onto the opposite face, and the bounding box
  49478. // encompasses the entire cube map face.
  49479. if (bleedOverAmount[i] > srcSize) {
  49480. //determine opposite face
  49481. switch (faceIdx) {
  49482. case PMREMGenerator.CP_FACE_X_POS:
  49483. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49484. break;
  49485. case PMREMGenerator.CP_FACE_X_NEG:
  49486. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  49487. break;
  49488. case PMREMGenerator.CP_FACE_Y_POS:
  49489. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49490. break;
  49491. case PMREMGenerator.CP_FACE_Y_NEG:
  49492. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49493. break;
  49494. case PMREMGenerator.CP_FACE_Z_POS:
  49495. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49496. break;
  49497. case PMREMGenerator.CP_FACE_Z_NEG:
  49498. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49499. break;
  49500. default:
  49501. break;
  49502. }
  49503. //just encompass entire face for now
  49504. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  49505. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  49506. }
  49507. }
  49508. };
  49509. //--------------------------------------------------------------------------------------
  49510. //ProcessFilterExtents
  49511. // Process bounding box in each cube face
  49512. //
  49513. //--------------------------------------------------------------------------------------
  49514. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  49515. //accumulators are 64-bit floats in order to have the precision needed
  49516. // over a summation of a large number of pixels
  49517. var dstAccum = [0, 0, 0, 0];
  49518. var weightAccum = 0;
  49519. var k = 0;
  49520. var nSrcChannels = this.numChannels;
  49521. // norm cube map and srcCubeMap have same face width
  49522. var faceWidth = srcSize;
  49523. //amount to add to pointer to move to next scanline in images
  49524. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  49525. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  49526. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  49527. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  49528. // iterate over cubefaces
  49529. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  49530. //if bbox is non empty
  49531. if (!filterExtents[iFaceIdx].empty()) {
  49532. var uStart = filterExtents[iFaceIdx].min.x;
  49533. var vStart = filterExtents[iFaceIdx].min.y;
  49534. var uEnd = filterExtents[iFaceIdx].max.x;
  49535. var vEnd = filterExtents[iFaceIdx].max.y;
  49536. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  49537. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  49538. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  49539. for (var v = vStart; v <= vEnd; v++) {
  49540. var normCubeRowWalk = 0;
  49541. var srcCubeRowWalk = 0;
  49542. for (var u = uStart; u <= uEnd; u++) {
  49543. //pointer to direction in cube map associated with texel
  49544. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  49545. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  49546. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  49547. //check dot product to see if texel is within cone
  49548. var tapDotProd = texelVectX * centerTapDir.x +
  49549. texelVectY * centerTapDir.y +
  49550. texelVectZ * centerTapDir.z;
  49551. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  49552. //solid angle stored in 4th channel of normalizer/solid angle cube map
  49553. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  49554. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  49555. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  49556. // so just adding one to specularpower do the trick.
  49557. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  49558. //iterate over channels
  49559. for (k = 0; k < nSrcChannels; k++) {
  49560. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  49561. srcCubeRowWalk++;
  49562. }
  49563. weightAccum += weight; //accumulate weight
  49564. }
  49565. else {
  49566. //step across source pixel
  49567. srcCubeRowWalk += nSrcChannels;
  49568. }
  49569. normCubeRowWalk += 4; // 4 channels per norm cube map.
  49570. }
  49571. startIndexNormCubeMap += normCubePitch;
  49572. startIndexSrcCubeMap += srcCubePitch;
  49573. }
  49574. }
  49575. }
  49576. //divide through by weights if weight is non zero
  49577. if (weightAccum != 0.0) {
  49578. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  49579. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  49580. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  49581. if (this.numChannels > 3) {
  49582. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  49583. }
  49584. }
  49585. else {
  49586. // otherwise sample nearest
  49587. // get face idx and u, v texel coordinate in face
  49588. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  49589. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  49590. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  49591. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  49592. if (this.numChannels > 3) {
  49593. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  49594. }
  49595. }
  49596. return PMREMGenerator._vectorTemp;
  49597. };
  49598. //--------------------------------------------------------------------------------------
  49599. // Fixup cube edges
  49600. //
  49601. // average texels on cube map faces across the edges
  49602. // WARP/BENT Method Only.
  49603. //--------------------------------------------------------------------------------------
  49604. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  49605. var k;
  49606. var j;
  49607. var i;
  49608. var iFace;
  49609. var iCorner = 0;
  49610. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  49611. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  49612. // note that if functionality to filter across the three texels for each corner, then
  49613. //indexed by corner and face idx. the array contains the face the start points belongs to.
  49614. var cornerPtr = [
  49615. [[], [], []],
  49616. [[], [], []],
  49617. [[], [], []],
  49618. [[], [], []],
  49619. [[], [], []],
  49620. [[], [], []],
  49621. [[], [], []],
  49622. [[], [], []]
  49623. ];
  49624. //if there is no fixup, or fixup width = 0, do nothing
  49625. if (cubeMapSize < 1) {
  49626. return;
  49627. }
  49628. //special case 1x1 cubemap, average face colors
  49629. if (cubeMapSize == 1) {
  49630. //iterate over channels
  49631. for (k = 0; k < this.numChannels; k++) {
  49632. var accum = 0.0;
  49633. //iterate over faces to accumulate face colors
  49634. for (iFace = 0; iFace < 6; iFace++) {
  49635. accum += cubeMap[iFace][k];
  49636. }
  49637. //compute average over 6 face colors
  49638. accum /= 6.0;
  49639. //iterate over faces to distribute face colors
  49640. for (iFace = 0; iFace < 6; iFace++) {
  49641. cubeMap[iFace][k] = accum;
  49642. }
  49643. }
  49644. return;
  49645. }
  49646. //iterate over faces to collect list of corner texel pointers
  49647. for (iFace = 0; iFace < 6; iFace++) {
  49648. //the 4 corner pointers for this face
  49649. faceCornerStartIndicies[0] = [iFace, 0];
  49650. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  49651. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  49652. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  49653. //iterate over face corners to collect cube corner pointers
  49654. for (iCorner = 0; iCorner < 4; iCorner++) {
  49655. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  49656. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  49657. cornerNumPtrs[corner]++;
  49658. }
  49659. }
  49660. //iterate over corners to average across corner tap values
  49661. for (iCorner = 0; iCorner < 8; iCorner++) {
  49662. for (k = 0; k < this.numChannels; k++) {
  49663. var cornerTapAccum = 0.0;
  49664. //iterate over corner texels and average results
  49665. for (i = 0; i < 3; i++) {
  49666. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  49667. }
  49668. //divide by 3 to compute average of corner tap values
  49669. cornerTapAccum *= (1.0 / 3.0);
  49670. //iterate over corner texels and average results
  49671. for (i = 0; i < 3; i++) {
  49672. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  49673. }
  49674. }
  49675. }
  49676. //iterate over the twelve edges of the cube to average across edges
  49677. for (i = 0; i < 12; i++) {
  49678. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  49679. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  49680. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  49681. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  49682. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  49683. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  49684. var edgeWalk = 0;
  49685. var neighborEdgeWalk = 0;
  49686. //Determine walking pointers based on edge type
  49687. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  49688. switch (edge) {
  49689. case PMREMGenerator.CP_EDGE_LEFT:
  49690. // no change to faceEdgeStartPtr
  49691. edgeWalk = this.numChannels * cubeMapSize;
  49692. break;
  49693. case PMREMGenerator.CP_EDGE_RIGHT:
  49694. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49695. edgeWalk = this.numChannels * cubeMapSize;
  49696. break;
  49697. case PMREMGenerator.CP_EDGE_TOP:
  49698. // no change to faceEdgeStartPtr
  49699. edgeWalk = this.numChannels;
  49700. break;
  49701. case PMREMGenerator.CP_EDGE_BOTTOM:
  49702. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49703. edgeWalk = this.numChannels;
  49704. break;
  49705. }
  49706. //For certain types of edge abutments, the neighbor edge walk needs to
  49707. // be flipped: the cases are
  49708. // if a left edge mates with a left or bottom edge on the neighbor
  49709. // if a top edge mates with a top or right edge on the neighbor
  49710. // if a right edge mates with a right or top edge on the neighbor
  49711. // if a bottom edge mates with a bottom or left edge on the neighbor
  49712. //Seeing as the edges are enumerated as follows
  49713. // left =0
  49714. // right =1
  49715. // top =2
  49716. // bottom =3
  49717. //
  49718. //If the edge enums are the same, or the sum of the enums == 3,
  49719. // the neighbor edge walk needs to be flipped
  49720. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  49721. switch (neighborEdge) {
  49722. case PMREMGenerator.CP_EDGE_LEFT:
  49723. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  49724. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49725. break;
  49726. case PMREMGenerator.CP_EDGE_RIGHT:
  49727. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49728. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49729. break;
  49730. case PMREMGenerator.CP_EDGE_TOP:
  49731. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49732. neighborEdgeWalk = -this.numChannels;
  49733. break;
  49734. case PMREMGenerator.CP_EDGE_BOTTOM:
  49735. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49736. neighborEdgeWalk = -this.numChannels;
  49737. break;
  49738. }
  49739. }
  49740. else {
  49741. //swapped direction neighbor edge walk
  49742. switch (neighborEdge) {
  49743. case PMREMGenerator.CP_EDGE_LEFT:
  49744. //no change to neighborEdgeStartPtr for this case since it points
  49745. // to the upper left corner already
  49746. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49747. break;
  49748. case PMREMGenerator.CP_EDGE_RIGHT:
  49749. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49750. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49751. break;
  49752. case PMREMGenerator.CP_EDGE_TOP:
  49753. //no change to neighborEdgeStartPtr for this case since it points
  49754. // to the upper left corner already
  49755. neighborEdgeWalk = this.numChannels;
  49756. break;
  49757. case PMREMGenerator.CP_EDGE_BOTTOM:
  49758. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49759. neighborEdgeWalk = this.numChannels;
  49760. break;
  49761. }
  49762. }
  49763. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  49764. //nearby neighborhood
  49765. //step ahead one texel on edge
  49766. edgeStartIndex += edgeWalk;
  49767. neighborEdgeStartIndex += neighborEdgeWalk;
  49768. // note that this loop does not process the corner texels, since they have already been
  49769. // averaged across faces across earlier
  49770. for (j = 1; j < (cubeMapSize - 1); j++) {
  49771. //for each set of taps along edge, average them
  49772. // and rewrite the results into the edges
  49773. for (k = 0; k < this.numChannels; k++) {
  49774. var edgeTap = cubeMap[face][edgeStartIndex + k];
  49775. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  49776. //compute average of tap intensity values
  49777. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  49778. //propagate average of taps to edge taps
  49779. cubeMap[face][edgeStartIndex + k] = avgTap;
  49780. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  49781. }
  49782. edgeStartIndex += edgeWalk;
  49783. neighborEdgeStartIndex += neighborEdgeWalk;
  49784. }
  49785. }
  49786. };
  49787. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  49788. PMREMGenerator.CP_UDIR = 0;
  49789. PMREMGenerator.CP_VDIR = 1;
  49790. PMREMGenerator.CP_FACEAXIS = 2;
  49791. //used to index cube faces
  49792. PMREMGenerator.CP_FACE_X_POS = 0;
  49793. PMREMGenerator.CP_FACE_X_NEG = 1;
  49794. PMREMGenerator.CP_FACE_Y_POS = 2;
  49795. PMREMGenerator.CP_FACE_Y_NEG = 3;
  49796. PMREMGenerator.CP_FACE_Z_POS = 4;
  49797. PMREMGenerator.CP_FACE_Z_NEG = 5;
  49798. //used to index image edges
  49799. // NOTE.. the actual number corresponding to the edge is important
  49800. // do not change these, or the code will break
  49801. //
  49802. // CP_EDGE_LEFT is u = 0
  49803. // CP_EDGE_RIGHT is u = width-1
  49804. // CP_EDGE_TOP is v = 0
  49805. // CP_EDGE_BOTTOM is v = height-1
  49806. PMREMGenerator.CP_EDGE_LEFT = 0;
  49807. PMREMGenerator.CP_EDGE_RIGHT = 1;
  49808. PMREMGenerator.CP_EDGE_TOP = 2;
  49809. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  49810. //corners of CUBE map (P or N specifys if it corresponds to the
  49811. // positive or negative direction each of X, Y, and Z
  49812. PMREMGenerator.CP_CORNER_NNN = 0;
  49813. PMREMGenerator.CP_CORNER_NNP = 1;
  49814. PMREMGenerator.CP_CORNER_NPN = 2;
  49815. PMREMGenerator.CP_CORNER_NPP = 3;
  49816. PMREMGenerator.CP_CORNER_PNN = 4;
  49817. PMREMGenerator.CP_CORNER_PNP = 5;
  49818. PMREMGenerator.CP_CORNER_PPN = 6;
  49819. PMREMGenerator.CP_CORNER_PPP = 7;
  49820. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  49821. //3x2 matrices that map cube map indexing vectors in 3d
  49822. // (after face selection and divide through by the
  49823. // _ABSOLUTE VALUE_ of the max coord)
  49824. // into NVC space
  49825. //Note this currently assumes the D3D cube face ordering and orientation
  49826. PMREMGenerator._sgFace2DMapping = [
  49827. //XPOS face
  49828. [[0, 0, -1],
  49829. [0, -1, 0],
  49830. [1, 0, 0]],
  49831. //XNEG face
  49832. [[0, 0, 1],
  49833. [0, -1, 0],
  49834. [-1, 0, 0]],
  49835. //YPOS face
  49836. [[1, 0, 0],
  49837. [0, 0, 1],
  49838. [0, 1, 0]],
  49839. //YNEG face
  49840. [[1, 0, 0],
  49841. [0, 0, -1],
  49842. [0, -1, 0]],
  49843. //ZPOS face
  49844. [[1, 0, 0],
  49845. [0, -1, 0],
  49846. [0, 0, 1]],
  49847. //ZNEG face
  49848. [[-1, 0, 0],
  49849. [0, -1, 0],
  49850. [0, 0, -1]],
  49851. ];
  49852. //------------------------------------------------------------------------------
  49853. // D3D cube map face specification
  49854. // mapping from 3D x,y,z cube map lookup coordinates
  49855. // to 2D within face u,v coordinates
  49856. //
  49857. // --------------------> U direction
  49858. // | (within-face texture space)
  49859. // | _____
  49860. // | | |
  49861. // | | +Y |
  49862. // | _____|_____|_____ _____
  49863. // | | | | | |
  49864. // | | -X | +Z | +X | -Z |
  49865. // | |_____|_____|_____|_____|
  49866. // | | |
  49867. // | | -Y |
  49868. // | |_____|
  49869. // |
  49870. // v V direction
  49871. // (within-face texture space)
  49872. //------------------------------------------------------------------------------
  49873. //Information about neighbors and how texture coorrdinates change across faces
  49874. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  49875. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  49876. //Note this currently assumes the D3D cube face ordering and orientation
  49877. PMREMGenerator._sgCubeNgh = [
  49878. //XPOS face
  49879. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49880. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49881. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49882. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  49883. //XNEG face
  49884. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49885. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  49886. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  49887. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  49888. //YPOS face
  49889. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49890. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49891. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49892. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  49893. //YNEG face
  49894. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49895. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49896. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49897. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  49898. //ZPOS face
  49899. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49900. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49901. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49902. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  49903. //ZNEG face
  49904. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49905. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49906. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  49907. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  49908. ];
  49909. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  49910. // this table is used to average over the edges.
  49911. PMREMGenerator._sgCubeEdgeList = [
  49912. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49913. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49914. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49915. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49916. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49917. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49918. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49919. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49920. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  49921. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49922. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49923. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  49924. ];
  49925. //Information about which of the 8 cube corners are correspond to the
  49926. // the 4 corners in each cube face
  49927. // the order is upper left, upper right, lower left, lower right
  49928. PMREMGenerator._sgCubeCornerList = [
  49929. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  49930. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  49931. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  49932. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  49933. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  49934. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  49935. ];
  49936. return PMREMGenerator;
  49937. })();
  49938. Internals.PMREMGenerator = PMREMGenerator;
  49939. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49940. })(BABYLON || (BABYLON = {}));
  49941. var BABYLON;
  49942. (function (BABYLON) {
  49943. /**
  49944. * This represents a texture coming from an HDR input.
  49945. *
  49946. * The only supported format is currently panorama picture stored in RGBE format.
  49947. * Example of such files can be found on HDRLib: http://hdrlib.com/
  49948. */
  49949. var HDRCubeTexture = (function (_super) {
  49950. __extends(HDRCubeTexture, _super);
  49951. /**
  49952. * Instantiates an HDRTexture from the following parameters.
  49953. *
  49954. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  49955. * @param scene The scene the texture will be used in
  49956. * @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.
  49957. * @param noMipmap Forces to not generate the mipmap if true
  49958. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  49959. * @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)
  49960. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  49961. */
  49962. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49963. if (noMipmap === void 0) { noMipmap = false; }
  49964. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49965. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49966. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49967. _super.call(this, scene);
  49968. this._useInGammaSpace = false;
  49969. this._generateHarmonics = true;
  49970. this._isBABYLONPreprocessed = false;
  49971. /**
  49972. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  49973. */
  49974. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49975. /**
  49976. * The spherical polynomial data extracted from the texture.
  49977. */
  49978. this.sphericalPolynomial = null;
  49979. /**
  49980. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  49981. * This is usefull at run time to apply the good shader.
  49982. */
  49983. this.isPMREM = false;
  49984. if (!url) {
  49985. return;
  49986. }
  49987. this.name = url;
  49988. this.url = url;
  49989. this.hasAlpha = false;
  49990. this.isCube = true;
  49991. this._textureMatrix = BABYLON.Matrix.Identity();
  49992. if (size) {
  49993. this._isBABYLONPreprocessed = false;
  49994. this._noMipmap = noMipmap;
  49995. this._size = size;
  49996. this._useInGammaSpace = useInGammaSpace;
  49997. this._usePMREMGenerator = usePMREMGenerator &&
  49998. scene.getEngine().getCaps().textureLOD &&
  49999. this.getScene().getEngine().getCaps().textureFloat &&
  50000. !this._useInGammaSpace;
  50001. }
  50002. else {
  50003. this._isBABYLONPreprocessed = true;
  50004. this._noMipmap = false;
  50005. this._useInGammaSpace = false;
  50006. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  50007. this.getScene().getEngine().getCaps().textureFloat &&
  50008. !this._useInGammaSpace;
  50009. }
  50010. this.isPMREM = this._usePMREMGenerator;
  50011. this._texture = this._getFromCache(url, this._noMipmap);
  50012. if (!this._texture) {
  50013. if (!scene.useDelayedTextureLoading) {
  50014. this.loadTexture();
  50015. }
  50016. else {
  50017. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50018. }
  50019. }
  50020. }
  50021. /**
  50022. * Occurs when the file is a preprocessed .babylon.hdr file.
  50023. */
  50024. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  50025. var _this = this;
  50026. var mipLevels = 0;
  50027. var floatArrayView = null;
  50028. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  50029. var mips = [];
  50030. var startIndex = 30;
  50031. for (var level = 0; level < mipLevels; level++) {
  50032. mips.push([]);
  50033. // Fill each pixel of the mip level.
  50034. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  50035. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50036. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  50037. mips[level].push(faceData);
  50038. startIndex += faceSize;
  50039. }
  50040. }
  50041. return mips;
  50042. } : null;
  50043. var callback = function (buffer) {
  50044. // Create Native Array Views
  50045. var intArrayView = new Int32Array(buffer);
  50046. floatArrayView = new Float32Array(buffer);
  50047. // Fill header.
  50048. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  50049. _this._size = intArrayView[1]; // CubeMap max mip face size.
  50050. // Update Texture Information.
  50051. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  50052. // Fill polynomial information.
  50053. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  50054. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  50055. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  50056. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  50057. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  50058. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  50059. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  50060. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  50061. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  50062. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  50063. // Fill pixel data.
  50064. mipLevels = intArrayView[29]; // Number of mip levels.
  50065. var startIndex = 30;
  50066. var data = [];
  50067. var faceSize = Math.pow(_this._size, 2) * 3;
  50068. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50069. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  50070. startIndex += faceSize;
  50071. }
  50072. var results = [];
  50073. var byteArray = null;
  50074. // Push each faces.
  50075. for (var k = 0; k < 6; k++) {
  50076. var dataFace = null;
  50077. // If special cases.
  50078. if (!mipmapGenerator) {
  50079. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  50080. dataFace = data[j];
  50081. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50082. // 3 channels of 1 bytes per pixel in bytes.
  50083. var byteBuffer = new ArrayBuffer(faceSize);
  50084. byteArray = new Uint8Array(byteBuffer);
  50085. }
  50086. for (var i = 0; i < _this._size * _this._size; i++) {
  50087. // Put in gamma space if requested.
  50088. if (_this._useInGammaSpace) {
  50089. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50090. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50091. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50092. }
  50093. // Convert to int texture for fallback.
  50094. if (byteArray) {
  50095. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50096. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50097. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50098. // May use luminance instead if the result is not accurate.
  50099. var max = Math.max(Math.max(r, g), b);
  50100. if (max > 255) {
  50101. var scale = 255 / max;
  50102. r *= scale;
  50103. g *= scale;
  50104. b *= scale;
  50105. }
  50106. byteArray[(i * 3) + 0] = r;
  50107. byteArray[(i * 3) + 1] = g;
  50108. byteArray[(i * 3) + 2] = b;
  50109. }
  50110. }
  50111. }
  50112. else {
  50113. dataFace = data[k];
  50114. }
  50115. // Fill the array accordingly.
  50116. if (byteArray) {
  50117. results.push(byteArray);
  50118. }
  50119. else {
  50120. results.push(dataFace);
  50121. }
  50122. }
  50123. return results;
  50124. };
  50125. 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);
  50126. };
  50127. /**
  50128. * Occurs when the file is raw .hdr file.
  50129. */
  50130. HDRCubeTexture.prototype.loadHDRTexture = function () {
  50131. var _this = this;
  50132. var callback = function (buffer) {
  50133. // Extract the raw linear data.
  50134. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  50135. // Generate harmonics if needed.
  50136. if (_this._generateHarmonics) {
  50137. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  50138. }
  50139. var results = [];
  50140. var byteArray = null;
  50141. // Push each faces.
  50142. for (var j = 0; j < 6; j++) {
  50143. // Create uintarray fallback.
  50144. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50145. // 3 channels of 1 bytes per pixel in bytes.
  50146. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  50147. byteArray = new Uint8Array(byteBuffer);
  50148. }
  50149. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  50150. // If special cases.
  50151. if (_this._useInGammaSpace || byteArray) {
  50152. for (var i = 0; i < _this._size * _this._size; i++) {
  50153. // Put in gamma space if requested.
  50154. if (_this._useInGammaSpace) {
  50155. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50156. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50157. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50158. }
  50159. // Convert to int texture for fallback.
  50160. if (byteArray) {
  50161. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50162. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50163. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50164. // May use luminance instead if the result is not accurate.
  50165. var max = Math.max(Math.max(r, g), b);
  50166. if (max > 255) {
  50167. var scale = 255 / max;
  50168. r *= scale;
  50169. g *= scale;
  50170. b *= scale;
  50171. }
  50172. byteArray[(i * 3) + 0] = r;
  50173. byteArray[(i * 3) + 1] = g;
  50174. byteArray[(i * 3) + 2] = b;
  50175. }
  50176. }
  50177. }
  50178. if (byteArray) {
  50179. results.push(byteArray);
  50180. }
  50181. else {
  50182. results.push(dataFace);
  50183. }
  50184. }
  50185. return results;
  50186. };
  50187. var mipmapGenerator = null;
  50188. if (!this._noMipmap &&
  50189. this._usePMREMGenerator) {
  50190. mipmapGenerator = function (data) {
  50191. // Custom setup of the generator matching with the PBR shader values.
  50192. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  50193. return generator.filterCubeMap();
  50194. };
  50195. }
  50196. 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);
  50197. };
  50198. /**
  50199. * Starts the loading process of the texture.
  50200. */
  50201. HDRCubeTexture.prototype.loadTexture = function () {
  50202. if (this._isBABYLONPreprocessed) {
  50203. this.loadBabylonTexture();
  50204. }
  50205. else {
  50206. this.loadHDRTexture();
  50207. }
  50208. };
  50209. HDRCubeTexture.prototype.clone = function () {
  50210. var size = this._isBABYLONPreprocessed ? null : this._size;
  50211. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  50212. // Base texture
  50213. newTexture.level = this.level;
  50214. newTexture.wrapU = this.wrapU;
  50215. newTexture.wrapV = this.wrapV;
  50216. newTexture.coordinatesIndex = this.coordinatesIndex;
  50217. newTexture.coordinatesMode = this.coordinatesMode;
  50218. return newTexture;
  50219. };
  50220. // Methods
  50221. HDRCubeTexture.prototype.delayLoad = function () {
  50222. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50223. return;
  50224. }
  50225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50226. this._texture = this._getFromCache(this.url, this._noMipmap);
  50227. if (!this._texture) {
  50228. this.loadTexture();
  50229. }
  50230. };
  50231. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  50232. return this._textureMatrix;
  50233. };
  50234. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50235. var texture = null;
  50236. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50237. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  50238. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  50239. texture.name = parsedTexture.name;
  50240. texture.hasAlpha = parsedTexture.hasAlpha;
  50241. texture.level = parsedTexture.level;
  50242. texture.coordinatesMode = parsedTexture.coordinatesMode;
  50243. }
  50244. return texture;
  50245. };
  50246. HDRCubeTexture.prototype.serialize = function () {
  50247. if (!this.name) {
  50248. return null;
  50249. }
  50250. var serializationObject = {};
  50251. serializationObject.name = this.name;
  50252. serializationObject.hasAlpha = this.hasAlpha;
  50253. serializationObject.isCube = true;
  50254. serializationObject.level = this.level;
  50255. serializationObject.size = this._size;
  50256. serializationObject.coordinatesMode = this.coordinatesMode;
  50257. serializationObject.useInGammaSpace = this._useInGammaSpace;
  50258. serializationObject.generateHarmonics = this._generateHarmonics;
  50259. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  50260. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  50261. return serializationObject;
  50262. };
  50263. /**
  50264. * Saves as a file the data contained in the texture in a binary format.
  50265. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50266. * as the spherical used in the lighting.
  50267. * @param url The HDR file url.
  50268. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50269. * @param onError Method called if any error happens during download.
  50270. * @return The packed binary data.
  50271. */
  50272. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  50273. if (onError === void 0) { onError = null; }
  50274. var callback = function (buffer) {
  50275. var data = new Blob([buffer], { type: 'application/octet-stream' });
  50276. // Returns a URL you can use as a href.
  50277. var objUrl = window.URL.createObjectURL(data);
  50278. // Simulates a link to it and click to dowload.
  50279. var a = document.createElement("a");
  50280. document.body.appendChild(a);
  50281. a.style.display = "none";
  50282. a.href = objUrl;
  50283. a.download = "envmap.babylon.hdr";
  50284. a.click();
  50285. };
  50286. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  50287. };
  50288. /**
  50289. * Serializes the data contained in the texture in a binary format.
  50290. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50291. * as the spherical used in the lighting.
  50292. * @param url The HDR file url.
  50293. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50294. * @param onError Method called if any error happens during download.
  50295. * @return The packed binary data.
  50296. */
  50297. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  50298. if (onError === void 0) { onError = null; }
  50299. // Needs the url tho create the texture.
  50300. if (!url) {
  50301. return null;
  50302. }
  50303. // Check Power of two size.
  50304. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  50305. return null;
  50306. }
  50307. var getDataCallback = function (dataBuffer) {
  50308. // Extract the raw linear data.
  50309. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  50310. // Generate harmonics if needed.
  50311. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  50312. // Generate seamless faces
  50313. var mipGeneratorArray = [];
  50314. // Data are known to be in +X +Y +Z -X -Y -Z
  50315. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  50316. mipGeneratorArray.push(cubeData.right); // +X
  50317. mipGeneratorArray.push(cubeData.left); // -X
  50318. mipGeneratorArray.push(cubeData.up); // +Y
  50319. mipGeneratorArray.push(cubeData.down); // -Y
  50320. mipGeneratorArray.push(cubeData.front); // +Z
  50321. mipGeneratorArray.push(cubeData.back); // -Z
  50322. // Custom setup of the generator matching with the PBR shader values.
  50323. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  50324. var mippedData = generator.filterCubeMap();
  50325. // Compute required byte length.
  50326. var byteLength = 1 * 4; // Raw Data Version int32.
  50327. byteLength += 4; // CubeMap max mip face size int32.
  50328. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  50329. // Add data size.
  50330. byteLength += 4; // Number of mip levels int32.
  50331. for (var level = 0; level < mippedData.length; level++) {
  50332. var mipSize = size >> level;
  50333. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  50334. }
  50335. // Prepare binary structure.
  50336. var buffer = new ArrayBuffer(byteLength);
  50337. var intArrayView = new Int32Array(buffer);
  50338. var floatArrayView = new Float32Array(buffer);
  50339. // Fill header.
  50340. intArrayView[0] = 1; // Version 1.
  50341. intArrayView[1] = size; // CubeMap max mip face size.
  50342. // Fill polynomial information.
  50343. sphericalPolynomial.x.toArray(floatArrayView, 2);
  50344. sphericalPolynomial.y.toArray(floatArrayView, 5);
  50345. sphericalPolynomial.z.toArray(floatArrayView, 8);
  50346. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  50347. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  50348. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  50349. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  50350. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  50351. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  50352. // Fill pixel data.
  50353. intArrayView[29] = mippedData.length; // Number of mip levels.
  50354. var startIndex = 30;
  50355. for (var level = 0; level < mippedData.length; level++) {
  50356. // Fill each pixel of the mip level.
  50357. var faceSize = Math.pow(size >> level, 2) * 3;
  50358. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50359. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  50360. startIndex += faceSize;
  50361. }
  50362. }
  50363. // Callback.
  50364. callback(buffer);
  50365. };
  50366. // Download and process.
  50367. BABYLON.Tools.LoadFile(url, function (data) {
  50368. getDataCallback(data);
  50369. }, null, null, true, onError);
  50370. };
  50371. HDRCubeTexture._facesMapping = [
  50372. "right",
  50373. "up",
  50374. "front",
  50375. "left",
  50376. "down",
  50377. "back"
  50378. ];
  50379. return HDRCubeTexture;
  50380. })(BABYLON.BaseTexture);
  50381. BABYLON.HDRCubeTexture = HDRCubeTexture;
  50382. })(BABYLON || (BABYLON = {}));
  50383. var BABYLON;
  50384. (function (BABYLON) {
  50385. var Debug;
  50386. (function (Debug) {
  50387. /**
  50388. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  50389. */
  50390. var SkeletonViewer = (function () {
  50391. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  50392. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  50393. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  50394. this.skeleton = skeleton;
  50395. this.mesh = mesh;
  50396. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  50397. this.renderingGroupId = renderingGroupId;
  50398. this.color = BABYLON.Color3.White();
  50399. this._debugLines = [];
  50400. this._isEnabled = false;
  50401. this._scene = scene;
  50402. this.update();
  50403. this._renderFunction = this.update.bind(this);
  50404. }
  50405. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  50406. get: function () {
  50407. return this._isEnabled;
  50408. },
  50409. set: function (value) {
  50410. if (this._isEnabled === value) {
  50411. return;
  50412. }
  50413. this._isEnabled = value;
  50414. if (value) {
  50415. this._scene.registerBeforeRender(this._renderFunction);
  50416. }
  50417. else {
  50418. this._scene.unregisterBeforeRender(this._renderFunction);
  50419. }
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  50425. if (x === void 0) { x = 0; }
  50426. if (y === void 0) { y = 0; }
  50427. if (z === void 0) { z = 0; }
  50428. var tmat = BABYLON.Tmp.Matrix[0];
  50429. var parentBone = bone.getParent();
  50430. tmat.copyFrom(bone.getLocalMatrix());
  50431. if (x !== 0 || y !== 0 || z !== 0) {
  50432. var tmat2 = BABYLON.Tmp.Matrix[1];
  50433. BABYLON.Matrix.IdentityToRef(tmat2);
  50434. tmat2.m[12] = x;
  50435. tmat2.m[13] = y;
  50436. tmat2.m[14] = z;
  50437. tmat2.multiplyToRef(tmat, tmat);
  50438. }
  50439. if (parentBone) {
  50440. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  50441. }
  50442. tmat.multiplyToRef(meshMat, tmat);
  50443. position.x = tmat.m[12];
  50444. position.y = tmat.m[13];
  50445. position.z = tmat.m[14];
  50446. };
  50447. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  50448. var len = bones.length;
  50449. for (var i = 0; i < len; i++) {
  50450. var bone = bones[i];
  50451. var points = this._debugLines[i];
  50452. if (!points) {
  50453. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50454. this._debugLines[i] = points;
  50455. }
  50456. this._getBonePosition(points[0], bone, meshMat);
  50457. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  50458. }
  50459. };
  50460. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  50461. var len = bones.length;
  50462. var boneNum = 0;
  50463. for (var i = len - 1; i >= 0; i--) {
  50464. var childBone = bones[i];
  50465. var parentBone = childBone.getParent();
  50466. if (!parentBone) {
  50467. continue;
  50468. }
  50469. var points = this._debugLines[boneNum];
  50470. if (!points) {
  50471. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50472. this._debugLines[boneNum] = points;
  50473. }
  50474. this._getBonePosition(points[0], childBone, meshMat);
  50475. this._getBonePosition(points[1], parentBone, meshMat);
  50476. boneNum++;
  50477. }
  50478. };
  50479. SkeletonViewer.prototype.update = function () {
  50480. if (this.autoUpdateBonesMatrices) {
  50481. this._updateBoneMatrix(this.skeleton.bones[0]);
  50482. }
  50483. if (this.skeleton.bones[0].length === undefined) {
  50484. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50485. }
  50486. else {
  50487. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50488. }
  50489. if (!this._debugMesh) {
  50490. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  50491. this._debugMesh.renderingGroupId = this.renderingGroupId;
  50492. }
  50493. else {
  50494. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  50495. }
  50496. this._debugMesh.color = this.color;
  50497. };
  50498. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  50499. if (bone.getParent()) {
  50500. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  50501. }
  50502. var children = bone.children;
  50503. var len = children.length;
  50504. for (var i = 0; i < len; i++) {
  50505. this._updateBoneMatrix(children[i]);
  50506. }
  50507. };
  50508. SkeletonViewer.prototype.dispose = function () {
  50509. if (this._debugMesh) {
  50510. this.isEnabled = false;
  50511. this._debugMesh.dispose();
  50512. this._debugMesh = null;
  50513. }
  50514. };
  50515. return SkeletonViewer;
  50516. })();
  50517. Debug.SkeletonViewer = SkeletonViewer;
  50518. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  50519. })(BABYLON || (BABYLON = {}));
  50520. var BABYLON;
  50521. (function (BABYLON) {
  50522. /**
  50523. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  50524. * It can help converting any input color in a desired output one. This can then be used to create effects
  50525. * from sepia, black and white to sixties or futuristic rendering...
  50526. *
  50527. * The only supported format is currently 3dl.
  50528. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  50529. */
  50530. var ColorGradingTexture = (function (_super) {
  50531. __extends(ColorGradingTexture, _super);
  50532. /**
  50533. * Instantiates a ColorGradingTexture from the following parameters.
  50534. *
  50535. * @param url The location of the color gradind data (currently only supporting 3dl)
  50536. * @param scene The scene the texture will be used in
  50537. */
  50538. function ColorGradingTexture(url, scene) {
  50539. _super.call(this, scene);
  50540. if (!url) {
  50541. return;
  50542. }
  50543. this._textureMatrix = BABYLON.Matrix.Identity();
  50544. this.name = url;
  50545. this.url = url;
  50546. this.hasAlpha = false;
  50547. this.isCube = false;
  50548. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50549. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50550. this.anisotropicFilteringLevel = 1;
  50551. this._texture = this._getFromCache(url, true);
  50552. if (!this._texture) {
  50553. if (!scene.useDelayedTextureLoading) {
  50554. this.loadTexture();
  50555. }
  50556. else {
  50557. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50558. }
  50559. }
  50560. }
  50561. /**
  50562. * Returns the texture matrix used in most of the material.
  50563. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  50564. */
  50565. ColorGradingTexture.prototype.getTextureMatrix = function () {
  50566. return this._textureMatrix;
  50567. };
  50568. /**
  50569. * Occurs when the file being loaded is a .3dl LUT file.
  50570. */
  50571. ColorGradingTexture.prototype.load3dlTexture = function () {
  50572. var _this = this;
  50573. var mipLevels = 0;
  50574. var floatArrayView = null;
  50575. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50576. this._texture = texture;
  50577. var callback = function (text) {
  50578. var data;
  50579. var tempData;
  50580. var line;
  50581. var lines = text.split('\n');
  50582. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  50583. var maxColor = 0;
  50584. for (var i = 0; i < lines.length; i++) {
  50585. line = lines[i];
  50586. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  50587. continue;
  50588. if (line.indexOf('#') === 0)
  50589. continue;
  50590. var words = line.split(" ");
  50591. if (size === 0) {
  50592. // Number of space + one
  50593. size = words.length;
  50594. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  50595. tempData = new Float32Array(size * size * size * 4);
  50596. continue;
  50597. }
  50598. if (size != 0) {
  50599. var r = Math.max(parseInt(words[0]), 0);
  50600. var g = Math.max(parseInt(words[1]), 0);
  50601. var b = Math.max(parseInt(words[2]), 0);
  50602. maxColor = Math.max(r, maxColor);
  50603. maxColor = Math.max(g, maxColor);
  50604. maxColor = Math.max(b, maxColor);
  50605. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  50606. tempData[pixelStorageIndex + 0] = r;
  50607. tempData[pixelStorageIndex + 1] = g;
  50608. tempData[pixelStorageIndex + 2] = b;
  50609. tempData[pixelStorageIndex + 3] = 0;
  50610. pixelIndexSlice++;
  50611. if (pixelIndexSlice % size == 0) {
  50612. pixelIndexH++;
  50613. pixelIndexSlice = 0;
  50614. if (pixelIndexH % size == 0) {
  50615. pixelIndexW++;
  50616. pixelIndexH = 0;
  50617. }
  50618. }
  50619. }
  50620. }
  50621. for (var i = 0; i < tempData.length; i++) {
  50622. var value = tempData[i];
  50623. data[i] = (value / maxColor * 255);
  50624. }
  50625. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  50626. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  50627. };
  50628. BABYLON.Tools.LoadFile(this.url, callback);
  50629. return this._texture;
  50630. };
  50631. /**
  50632. * Starts the loading process of the texture.
  50633. */
  50634. ColorGradingTexture.prototype.loadTexture = function () {
  50635. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  50636. this.load3dlTexture();
  50637. }
  50638. };
  50639. /**
  50640. * Clones the color gradind texture.
  50641. */
  50642. ColorGradingTexture.prototype.clone = function () {
  50643. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  50644. // Base texture
  50645. newTexture.level = this.level;
  50646. return newTexture;
  50647. };
  50648. /**
  50649. * Called during delayed load for textures.
  50650. */
  50651. ColorGradingTexture.prototype.delayLoad = function () {
  50652. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50653. return;
  50654. }
  50655. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50656. this._texture = this._getFromCache(this.url, true);
  50657. if (!this._texture) {
  50658. this.loadTexture();
  50659. }
  50660. };
  50661. /**
  50662. * Parses a color grading texture serialized by Babylon.
  50663. * @param parsedTexture The texture information being parsedTexture
  50664. * @param scene The scene to load the texture in
  50665. * @param rootUrl The root url of the data assets to load
  50666. * @return A color gradind texture
  50667. */
  50668. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50669. var texture = null;
  50670. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50671. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  50672. texture.name = parsedTexture.name;
  50673. texture.level = parsedTexture.level;
  50674. }
  50675. return texture;
  50676. };
  50677. /**
  50678. * Serializes the LUT texture to json format.
  50679. */
  50680. ColorGradingTexture.prototype.serialize = function () {
  50681. if (!this.name) {
  50682. return null;
  50683. }
  50684. var serializationObject = {};
  50685. serializationObject.name = this.name;
  50686. serializationObject.level = this.level;
  50687. return serializationObject;
  50688. };
  50689. /**
  50690. * Empty line regex stored for GC.
  50691. */
  50692. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  50693. return ColorGradingTexture;
  50694. })(BABYLON.BaseTexture);
  50695. BABYLON.ColorGradingTexture = ColorGradingTexture;
  50696. })(BABYLON || (BABYLON = {}));
  50697. var BABYLON;
  50698. (function (BABYLON) {
  50699. var PBRMaterialDefines = (function (_super) {
  50700. __extends(PBRMaterialDefines, _super);
  50701. function PBRMaterialDefines() {
  50702. _super.call(this);
  50703. this.ALBEDO = false;
  50704. this.AMBIENT = false;
  50705. this.OPACITY = false;
  50706. this.OPACITYRGB = false;
  50707. this.REFLECTION = false;
  50708. this.EMISSIVE = false;
  50709. this.REFLECTIVITY = false;
  50710. this.BUMP = false;
  50711. this.PARALLAX = false;
  50712. this.PARALLAXOCCLUSION = false;
  50713. this.SPECULAROVERALPHA = false;
  50714. this.CLIPPLANE = false;
  50715. this.ALPHATEST = false;
  50716. this.ALPHAFROMALBEDO = false;
  50717. this.POINTSIZE = false;
  50718. this.FOG = false;
  50719. this.SPECULARTERM = false;
  50720. this.OPACITYFRESNEL = false;
  50721. this.EMISSIVEFRESNEL = false;
  50722. this.FRESNEL = false;
  50723. this.NORMAL = false;
  50724. this.UV1 = false;
  50725. this.UV2 = false;
  50726. this.VERTEXCOLOR = false;
  50727. this.VERTEXALPHA = false;
  50728. this.NUM_BONE_INFLUENCERS = 0;
  50729. this.BonesPerMesh = 0;
  50730. this.INSTANCES = false;
  50731. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  50732. this.MICROSURFACEAUTOMATIC = false;
  50733. this.EMISSIVEASILLUMINATION = false;
  50734. this.LINKEMISSIVEWITHALBEDO = false;
  50735. this.LIGHTMAP = false;
  50736. this.USELIGHTMAPASSHADOWMAP = false;
  50737. this.REFLECTIONMAP_3D = false;
  50738. this.REFLECTIONMAP_SPHERICAL = false;
  50739. this.REFLECTIONMAP_PLANAR = false;
  50740. this.REFLECTIONMAP_CUBIC = false;
  50741. this.REFLECTIONMAP_PROJECTION = false;
  50742. this.REFLECTIONMAP_SKYBOX = false;
  50743. this.REFLECTIONMAP_EXPLICIT = false;
  50744. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  50745. this.INVERTCUBICMAP = false;
  50746. this.LOGARITHMICDEPTH = false;
  50747. this.CAMERATONEMAP = false;
  50748. this.CAMERACONTRAST = false;
  50749. this.CAMERACOLORGRADING = false;
  50750. this.OVERLOADEDVALUES = false;
  50751. this.OVERLOADEDSHADOWVALUES = false;
  50752. this.USESPHERICALFROMREFLECTIONMAP = false;
  50753. this.REFRACTION = false;
  50754. this.REFRACTIONMAP_3D = false;
  50755. this.LINKREFRACTIONTOTRANSPARENCY = false;
  50756. this.REFRACTIONMAPINLINEARSPACE = false;
  50757. this.LODBASEDMICROSFURACE = false;
  50758. this.USEPHYSICALLIGHTFALLOFF = false;
  50759. this.RADIANCEOVERALPHA = false;
  50760. this.USEPMREMREFLECTION = false;
  50761. this.USEPMREMREFRACTION = false;
  50762. this.OPENGLNORMALMAP = false;
  50763. this.INVERTNORMALMAPX = false;
  50764. this.INVERTNORMALMAPY = false;
  50765. this.rebuild();
  50766. }
  50767. return PBRMaterialDefines;
  50768. })(BABYLON.MaterialDefines);
  50769. /**
  50770. * The Physically based material of BJS.
  50771. *
  50772. * This offers the main features of a standard PBR material.
  50773. * For more information, please refer to the documentation :
  50774. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  50775. */
  50776. var PBRMaterial = (function (_super) {
  50777. __extends(PBRMaterial, _super);
  50778. /**
  50779. * Instantiates a new PBRMaterial instance.
  50780. *
  50781. * @param name The material name
  50782. * @param scene The scene the material will be use in.
  50783. */
  50784. function PBRMaterial(name, scene) {
  50785. var _this = this;
  50786. _super.call(this, name, scene);
  50787. /**
  50788. * Intensity of the direct lights e.g. the four lights available in your scene.
  50789. * This impacts both the direct diffuse and specular highlights.
  50790. */
  50791. this.directIntensity = 1.0;
  50792. /**
  50793. * Intensity of the emissive part of the material.
  50794. * This helps controlling the emissive effect without modifying the emissive color.
  50795. */
  50796. this.emissiveIntensity = 1.0;
  50797. /**
  50798. * Intensity of the environment e.g. how much the environment will light the object
  50799. * either through harmonics for rough material or through the refelction for shiny ones.
  50800. */
  50801. this.environmentIntensity = 1.0;
  50802. /**
  50803. * This is a special control allowing the reduction of the specular highlights coming from the
  50804. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  50805. */
  50806. this.specularIntensity = 1.0;
  50807. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  50808. /**
  50809. * Debug Control allowing disabling the bump map on this material.
  50810. */
  50811. this.disableBumpMap = false;
  50812. /**
  50813. * Debug Control helping enforcing or dropping the darkness of shadows.
  50814. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  50815. */
  50816. this.overloadedShadowIntensity = 1.0;
  50817. /**
  50818. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  50819. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  50820. */
  50821. this.overloadedShadeIntensity = 1.0;
  50822. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  50823. /**
  50824. * The camera exposure used on this material.
  50825. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  50826. * This corresponds to a photographic exposure.
  50827. */
  50828. this.cameraExposure = 1.0;
  50829. /**
  50830. * The camera contrast used on this material.
  50831. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  50832. */
  50833. this.cameraContrast = 1.0;
  50834. /**
  50835. * Color Grading 2D Lookup Texture.
  50836. * This allows special effects like sepia, black and white to sixties rendering style.
  50837. */
  50838. this.cameraColorGradingTexture = null;
  50839. this._cameraColorGradingScaleOffset = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50840. this._cameraColorGradingInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50841. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  50842. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  50843. /**
  50844. * Debug Control allowing to overload the ambient color.
  50845. * This as to be use with the overloadedAmbientIntensity parameter.
  50846. */
  50847. this.overloadedAmbient = BABYLON.Color3.White();
  50848. /**
  50849. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  50850. */
  50851. this.overloadedAmbientIntensity = 0.0;
  50852. /**
  50853. * Debug Control allowing to overload the albedo color.
  50854. * This as to be use with the overloadedAlbedoIntensity parameter.
  50855. */
  50856. this.overloadedAlbedo = BABYLON.Color3.White();
  50857. /**
  50858. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  50859. */
  50860. this.overloadedAlbedoIntensity = 0.0;
  50861. /**
  50862. * Debug Control allowing to overload the reflectivity color.
  50863. * This as to be use with the overloadedReflectivityIntensity parameter.
  50864. */
  50865. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  50866. /**
  50867. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  50868. */
  50869. this.overloadedReflectivityIntensity = 0.0;
  50870. /**
  50871. * Debug Control allowing to overload the emissive color.
  50872. * This as to be use with the overloadedEmissiveIntensity parameter.
  50873. */
  50874. this.overloadedEmissive = BABYLON.Color3.White();
  50875. /**
  50876. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  50877. */
  50878. this.overloadedEmissiveIntensity = 0.0;
  50879. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  50880. /**
  50881. * Debug Control allowing to overload the reflection color.
  50882. * This as to be use with the overloadedReflectionIntensity parameter.
  50883. */
  50884. this.overloadedReflection = BABYLON.Color3.White();
  50885. /**
  50886. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  50887. */
  50888. this.overloadedReflectionIntensity = 0.0;
  50889. /**
  50890. * Debug Control allowing to overload the microsurface.
  50891. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  50892. */
  50893. this.overloadedMicroSurface = 0.0;
  50894. /**
  50895. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  50896. */
  50897. this.overloadedMicroSurfaceIntensity = 0.0;
  50898. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  50899. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  50900. /**
  50901. * AKA Diffuse Color in other nomenclature.
  50902. */
  50903. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  50904. /**
  50905. * AKA Specular Color in other nomenclature.
  50906. */
  50907. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  50908. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  50909. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  50910. /**
  50911. * AKA Glossiness in other nomenclature.
  50912. */
  50913. this.microSurface = 0.9;
  50914. /**
  50915. * source material index of refraction (IOR)' / 'destination material IOR.
  50916. */
  50917. this.indexOfRefraction = 0.66;
  50918. /**
  50919. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  50920. */
  50921. this.invertRefractionY = false;
  50922. /**
  50923. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  50924. * Materials half opaque for instance using refraction could benefit from this control.
  50925. */
  50926. this.linkRefractionWithTransparency = false;
  50927. /**
  50928. * The emissive and albedo are linked to never be more than one (Energy conservation).
  50929. */
  50930. this.linkEmissiveWithAlbedo = false;
  50931. this.useLightmapAsShadowmap = false;
  50932. /**
  50933. * In this mode, the emissive informtaion will always be added to the lighting once.
  50934. * A light for instance can be thought as emissive.
  50935. */
  50936. this.useEmissiveAsIllumination = false;
  50937. /**
  50938. * Secifies that the alpha is coming form the albedo channel alpha channel.
  50939. */
  50940. this.useAlphaFromAlbedoTexture = false;
  50941. /**
  50942. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  50943. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  50944. */
  50945. this.useSpecularOverAlpha = true;
  50946. /**
  50947. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  50948. */
  50949. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  50950. /**
  50951. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  50952. * The material will try to infer what glossiness each pixel should be.
  50953. */
  50954. this.useAutoMicroSurfaceFromReflectivityMap = false;
  50955. /**
  50956. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  50957. * the creation of the material.
  50958. */
  50959. this.useScalarInLinearSpace = false;
  50960. /**
  50961. * BJS is using an harcoded light falloff based on a manually sets up range.
  50962. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  50963. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  50964. */
  50965. this.usePhysicalLightFalloff = true;
  50966. /**
  50967. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  50968. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  50969. */
  50970. this.useRadianceOverAlpha = true;
  50971. /**
  50972. * Allows using the bump map in parallax mode.
  50973. */
  50974. this.useParallax = false;
  50975. /**
  50976. * Allows using the bump map in parallax occlusion mode.
  50977. */
  50978. this.useParallaxOcclusion = false;
  50979. /**
  50980. * Controls the scale bias of the parallax mode.
  50981. */
  50982. this.parallaxScaleBias = 0.05;
  50983. /**
  50984. * If sets to true, disables all the lights affecting the material.
  50985. */
  50986. this.disableLighting = false;
  50987. /**
  50988. * Number of Simultaneous lights allowed on the material.
  50989. */
  50990. this.maxSimultaneousLights = 4;
  50991. /**
  50992. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  50993. */
  50994. this.invertNormalMapX = false;
  50995. /**
  50996. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  50997. */
  50998. this.invertNormalMapY = false;
  50999. this._renderTargets = new BABYLON.SmartArray(16);
  51000. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  51001. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  51002. this._tempColor = new BABYLON.Color3();
  51003. this._defines = new PBRMaterialDefines();
  51004. this._cachedDefines = new PBRMaterialDefines();
  51005. this._myScene = null;
  51006. this._myShadowGenerator = null;
  51007. this._cachedDefines.BonesPerMesh = -1;
  51008. this.getRenderTargetTextures = function () {
  51009. _this._renderTargets.reset();
  51010. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  51011. _this._renderTargets.push(_this.reflectionTexture);
  51012. }
  51013. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  51014. _this._renderTargets.push(_this.refractionTexture);
  51015. }
  51016. return _this._renderTargets;
  51017. };
  51018. }
  51019. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  51020. get: function () {
  51021. return this._useLogarithmicDepth;
  51022. },
  51023. set: function (value) {
  51024. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  51025. },
  51026. enumerable: true,
  51027. configurable: true
  51028. });
  51029. PBRMaterial.prototype.needAlphaBlending = function () {
  51030. if (this.linkRefractionWithTransparency) {
  51031. return false;
  51032. }
  51033. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  51034. };
  51035. PBRMaterial.prototype.needAlphaTesting = function () {
  51036. if (this.linkRefractionWithTransparency) {
  51037. return false;
  51038. }
  51039. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  51040. };
  51041. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  51042. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  51043. };
  51044. PBRMaterial.prototype.getAlphaTestTexture = function () {
  51045. return this.albedoTexture;
  51046. };
  51047. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51048. if (!mesh) {
  51049. return true;
  51050. }
  51051. if (this._defines.INSTANCES !== useInstances) {
  51052. return false;
  51053. }
  51054. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  51055. return true;
  51056. }
  51057. return false;
  51058. };
  51059. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  51060. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  51061. };
  51062. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  51063. if (!useScalarInLinear) {
  51064. color.toLinearSpaceToRef(ref);
  51065. }
  51066. else {
  51067. ref.r = color.r;
  51068. ref.g = color.g;
  51069. ref.b = color.b;
  51070. }
  51071. };
  51072. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  51073. var lightIndex = 0;
  51074. var depthValuesAlreadySet = false;
  51075. for (var index = 0; index < scene.lights.length; index++) {
  51076. var light = scene.lights[index];
  51077. if (!light.isEnabled()) {
  51078. continue;
  51079. }
  51080. if (!light.canAffectMesh(mesh)) {
  51081. continue;
  51082. }
  51083. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  51084. // GAMMA CORRECTION.
  51085. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  51086. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  51087. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  51088. if (defines["SPECULARTERM"]) {
  51089. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  51090. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  51091. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  51092. }
  51093. // Shadows
  51094. if (scene.shadowsEnabled) {
  51095. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  51096. }
  51097. lightIndex++;
  51098. if (lightIndex === maxSimultaneousLights)
  51099. break;
  51100. }
  51101. };
  51102. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  51103. if (this.checkReadyOnlyOnce) {
  51104. if (this._wasPreviouslyReady) {
  51105. return true;
  51106. }
  51107. }
  51108. var scene = this.getScene();
  51109. if (!this.checkReadyOnEveryCall) {
  51110. if (this._renderId === scene.getRenderId()) {
  51111. if (this._checkCache(scene, mesh, useInstances)) {
  51112. return true;
  51113. }
  51114. }
  51115. }
  51116. var engine = scene.getEngine();
  51117. var needNormals = false;
  51118. var needUVs = false;
  51119. this._defines.reset();
  51120. if (scene.texturesEnabled) {
  51121. // Textures
  51122. if (scene.texturesEnabled) {
  51123. if (scene.getEngine().getCaps().textureLOD) {
  51124. this._defines.LODBASEDMICROSFURACE = true;
  51125. }
  51126. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51127. if (!this.albedoTexture.isReady()) {
  51128. return false;
  51129. }
  51130. else {
  51131. needUVs = true;
  51132. this._defines.ALBEDO = true;
  51133. }
  51134. }
  51135. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51136. if (!this.ambientTexture.isReady()) {
  51137. return false;
  51138. }
  51139. else {
  51140. needUVs = true;
  51141. this._defines.AMBIENT = true;
  51142. }
  51143. }
  51144. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51145. if (!this.opacityTexture.isReady()) {
  51146. return false;
  51147. }
  51148. else {
  51149. needUVs = true;
  51150. this._defines.OPACITY = true;
  51151. if (this.opacityTexture.getAlphaFromRGB) {
  51152. this._defines.OPACITYRGB = true;
  51153. }
  51154. }
  51155. }
  51156. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51157. if (!this.reflectionTexture.isReady()) {
  51158. return false;
  51159. }
  51160. else {
  51161. needNormals = true;
  51162. this._defines.REFLECTION = true;
  51163. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  51164. this._defines.INVERTCUBICMAP = true;
  51165. }
  51166. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  51167. switch (this.reflectionTexture.coordinatesMode) {
  51168. case BABYLON.Texture.CUBIC_MODE:
  51169. case BABYLON.Texture.INVCUBIC_MODE:
  51170. this._defines.REFLECTIONMAP_CUBIC = true;
  51171. break;
  51172. case BABYLON.Texture.EXPLICIT_MODE:
  51173. this._defines.REFLECTIONMAP_EXPLICIT = true;
  51174. break;
  51175. case BABYLON.Texture.PLANAR_MODE:
  51176. this._defines.REFLECTIONMAP_PLANAR = true;
  51177. break;
  51178. case BABYLON.Texture.PROJECTION_MODE:
  51179. this._defines.REFLECTIONMAP_PROJECTION = true;
  51180. break;
  51181. case BABYLON.Texture.SKYBOX_MODE:
  51182. this._defines.REFLECTIONMAP_SKYBOX = true;
  51183. break;
  51184. case BABYLON.Texture.SPHERICAL_MODE:
  51185. this._defines.REFLECTIONMAP_SPHERICAL = true;
  51186. break;
  51187. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  51188. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  51189. break;
  51190. }
  51191. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  51192. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  51193. needNormals = true;
  51194. if (this.reflectionTexture.isPMREM) {
  51195. this._defines.USEPMREMREFLECTION = true;
  51196. }
  51197. }
  51198. }
  51199. }
  51200. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51201. if (!this.lightmapTexture.isReady()) {
  51202. return false;
  51203. }
  51204. else {
  51205. needUVs = true;
  51206. this._defines.LIGHTMAP = true;
  51207. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  51208. }
  51209. }
  51210. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51211. if (!this.emissiveTexture.isReady()) {
  51212. return false;
  51213. }
  51214. else {
  51215. needUVs = true;
  51216. this._defines.EMISSIVE = true;
  51217. }
  51218. }
  51219. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51220. if (!this.reflectivityTexture.isReady()) {
  51221. return false;
  51222. }
  51223. else {
  51224. needUVs = true;
  51225. this._defines.REFLECTIVITY = true;
  51226. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  51227. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  51228. }
  51229. }
  51230. }
  51231. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51232. if (!this.bumpTexture.isReady()) {
  51233. return false;
  51234. }
  51235. else {
  51236. needUVs = true;
  51237. this._defines.BUMP = true;
  51238. if (this.useParallax) {
  51239. this._defines.PARALLAX = true;
  51240. if (this.useParallaxOcclusion) {
  51241. this._defines.PARALLAXOCCLUSION = true;
  51242. }
  51243. }
  51244. if (this.invertNormalMapX) {
  51245. this._defines.INVERTNORMALMAPX = true;
  51246. }
  51247. if (this.invertNormalMapY) {
  51248. this._defines.INVERTNORMALMAPY = true;
  51249. }
  51250. }
  51251. }
  51252. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51253. if (!this.refractionTexture.isReady()) {
  51254. return false;
  51255. }
  51256. else {
  51257. needUVs = true;
  51258. this._defines.REFRACTION = true;
  51259. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  51260. if (this.linkRefractionWithTransparency) {
  51261. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  51262. }
  51263. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  51264. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  51265. if (this.refractionTexture.isPMREM) {
  51266. this._defines.USEPMREMREFRACTION = true;
  51267. }
  51268. }
  51269. }
  51270. }
  51271. if (this.cameraColorGradingTexture) {
  51272. if (!this.cameraColorGradingTexture.isReady()) {
  51273. return false;
  51274. }
  51275. else {
  51276. this._defines.CAMERACOLORGRADING = true;
  51277. }
  51278. }
  51279. }
  51280. // Effect
  51281. if (scene.clipPlane) {
  51282. this._defines.CLIPPLANE = true;
  51283. }
  51284. if (engine.getAlphaTesting()) {
  51285. this._defines.ALPHATEST = true;
  51286. }
  51287. if (this._shouldUseAlphaFromAlbedoTexture()) {
  51288. this._defines.ALPHAFROMALBEDO = true;
  51289. }
  51290. if (this.useEmissiveAsIllumination) {
  51291. this._defines.EMISSIVEASILLUMINATION = true;
  51292. }
  51293. if (this.linkEmissiveWithAlbedo) {
  51294. this._defines.LINKEMISSIVEWITHALBEDO = true;
  51295. }
  51296. if (this.useLogarithmicDepth) {
  51297. this._defines.LOGARITHMICDEPTH = true;
  51298. }
  51299. if (this.cameraContrast != 1) {
  51300. this._defines.CAMERACONTRAST = true;
  51301. }
  51302. if (this.cameraExposure != 1) {
  51303. this._defines.CAMERATONEMAP = true;
  51304. }
  51305. if (this.overloadedShadeIntensity != 1 ||
  51306. this.overloadedShadowIntensity != 1) {
  51307. this._defines.OVERLOADEDSHADOWVALUES = true;
  51308. }
  51309. if (this.overloadedMicroSurfaceIntensity > 0 ||
  51310. this.overloadedEmissiveIntensity > 0 ||
  51311. this.overloadedReflectivityIntensity > 0 ||
  51312. this.overloadedAlbedoIntensity > 0 ||
  51313. this.overloadedAmbientIntensity > 0 ||
  51314. this.overloadedReflectionIntensity > 0) {
  51315. this._defines.OVERLOADEDVALUES = true;
  51316. }
  51317. // Point size
  51318. if (this.pointsCloud || scene.forcePointsCloud) {
  51319. this._defines.POINTSIZE = true;
  51320. }
  51321. // Fog
  51322. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51323. this._defines.FOG = true;
  51324. }
  51325. if (scene.lightsEnabled && !this.disableLighting) {
  51326. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  51327. }
  51328. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51329. // Fresnel
  51330. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  51331. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51332. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  51333. this._defines.OPACITYFRESNEL = true;
  51334. }
  51335. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51336. this._defines.EMISSIVEFRESNEL = true;
  51337. }
  51338. needNormals = true;
  51339. this._defines.FRESNEL = true;
  51340. }
  51341. }
  51342. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  51343. this._defines.SPECULAROVERALPHA = true;
  51344. }
  51345. if (this.usePhysicalLightFalloff) {
  51346. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  51347. }
  51348. if (this.useRadianceOverAlpha) {
  51349. this._defines.RADIANCEOVERALPHA = true;
  51350. }
  51351. // Attribs
  51352. if (mesh) {
  51353. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51354. this._defines.NORMAL = true;
  51355. }
  51356. if (needUVs) {
  51357. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51358. this._defines.UV1 = true;
  51359. }
  51360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51361. this._defines.UV2 = true;
  51362. }
  51363. }
  51364. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51365. this._defines.VERTEXCOLOR = true;
  51366. if (mesh.hasVertexAlpha) {
  51367. this._defines.VERTEXALPHA = true;
  51368. }
  51369. }
  51370. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51371. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  51372. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  51373. }
  51374. // Instances
  51375. if (useInstances) {
  51376. this._defines.INSTANCES = true;
  51377. }
  51378. }
  51379. // Get correct effect
  51380. if (!this._defines.isEqual(this._cachedDefines)) {
  51381. this._defines.cloneTo(this._cachedDefines);
  51382. scene.resetCachedMaterial();
  51383. // Fallbacks
  51384. var fallbacks = new BABYLON.EffectFallbacks();
  51385. if (this._defines.REFLECTION) {
  51386. fallbacks.addFallback(0, "REFLECTION");
  51387. }
  51388. if (this._defines.REFRACTION) {
  51389. fallbacks.addFallback(0, "REFRACTION");
  51390. }
  51391. if (this._defines.REFLECTIVITY) {
  51392. fallbacks.addFallback(0, "REFLECTIVITY");
  51393. }
  51394. if (this._defines.BUMP) {
  51395. fallbacks.addFallback(0, "BUMP");
  51396. }
  51397. if (this._defines.PARALLAX) {
  51398. fallbacks.addFallback(1, "PARALLAX");
  51399. }
  51400. if (this._defines.PARALLAXOCCLUSION) {
  51401. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  51402. }
  51403. if (this._defines.SPECULAROVERALPHA) {
  51404. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  51405. }
  51406. if (this._defines.FOG) {
  51407. fallbacks.addFallback(1, "FOG");
  51408. }
  51409. if (this._defines.POINTSIZE) {
  51410. fallbacks.addFallback(0, "POINTSIZE");
  51411. }
  51412. if (this._defines.LOGARITHMICDEPTH) {
  51413. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  51414. }
  51415. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  51416. if (this._defines.SPECULARTERM) {
  51417. fallbacks.addFallback(0, "SPECULARTERM");
  51418. }
  51419. if (this._defines.OPACITYFRESNEL) {
  51420. fallbacks.addFallback(1, "OPACITYFRESNEL");
  51421. }
  51422. if (this._defines.EMISSIVEFRESNEL) {
  51423. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  51424. }
  51425. if (this._defines.FRESNEL) {
  51426. fallbacks.addFallback(3, "FRESNEL");
  51427. }
  51428. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  51429. fallbacks.addCPUSkinningFallback(0, mesh);
  51430. }
  51431. //Attributes
  51432. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51433. if (this._defines.NORMAL) {
  51434. attribs.push(BABYLON.VertexBuffer.NormalKind);
  51435. }
  51436. if (this._defines.UV1) {
  51437. attribs.push(BABYLON.VertexBuffer.UVKind);
  51438. }
  51439. if (this._defines.UV2) {
  51440. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51441. }
  51442. if (this._defines.VERTEXCOLOR) {
  51443. attribs.push(BABYLON.VertexBuffer.ColorKind);
  51444. }
  51445. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  51446. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  51447. // Legacy browser patch
  51448. var shaderName = "pbr";
  51449. if (!scene.getEngine().getCaps().standardDerivatives) {
  51450. shaderName = "legacypbr";
  51451. }
  51452. var join = this._defines.toString();
  51453. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  51454. "vFogInfos", "vFogColor", "pointSize",
  51455. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  51456. "mBones",
  51457. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  51458. "depthValues",
  51459. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  51460. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  51461. "logarithmicDepthConstant",
  51462. "vSphericalX", "vSphericalY", "vSphericalZ",
  51463. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  51464. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  51465. "vMicrosurfaceTextureLods",
  51466. "vCameraInfos", "vCameraColorGradingInfos", "vCameraColorGradingScaleOffset"
  51467. ];
  51468. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  51469. "cameraColorGrading2DSampler"];
  51470. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  51471. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  51472. }
  51473. if (!this._effect.isReady()) {
  51474. return false;
  51475. }
  51476. this._renderId = scene.getRenderId();
  51477. this._wasPreviouslyReady = true;
  51478. if (mesh) {
  51479. if (!mesh._materialDefines) {
  51480. mesh._materialDefines = new PBRMaterialDefines();
  51481. }
  51482. this._defines.cloneTo(mesh._materialDefines);
  51483. }
  51484. return true;
  51485. };
  51486. PBRMaterial.prototype.unbind = function () {
  51487. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  51488. this._effect.setTexture("reflection2DSampler", null);
  51489. }
  51490. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  51491. this._effect.setTexture("refraction2DSampler", null);
  51492. }
  51493. _super.prototype.unbind.call(this);
  51494. };
  51495. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  51496. this._effect.setMatrix("world", world);
  51497. };
  51498. PBRMaterial.prototype.bind = function (world, mesh) {
  51499. this._myScene = this.getScene();
  51500. // Matrices
  51501. this.bindOnlyWorldMatrix(world);
  51502. // Bones
  51503. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  51504. if (this._myScene.getCachedMaterial() !== this) {
  51505. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  51506. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51507. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  51508. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  51509. }
  51510. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51511. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  51512. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  51513. }
  51514. }
  51515. // Textures
  51516. if (this._myScene.texturesEnabled) {
  51517. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51518. this._effect.setTexture("albedoSampler", this.albedoTexture);
  51519. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  51520. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  51521. }
  51522. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51523. this._effect.setTexture("ambientSampler", this.ambientTexture);
  51524. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  51525. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  51526. }
  51527. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51528. this._effect.setTexture("opacitySampler", this.opacityTexture);
  51529. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  51530. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  51531. }
  51532. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51533. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  51534. if (this.reflectionTexture.isCube) {
  51535. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  51536. }
  51537. else {
  51538. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  51539. }
  51540. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  51541. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  51542. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  51543. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  51544. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  51545. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  51546. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  51547. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  51548. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  51549. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  51550. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  51551. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  51552. }
  51553. }
  51554. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51555. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  51556. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  51557. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  51558. }
  51559. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51560. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  51561. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  51562. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  51563. }
  51564. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51565. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  51566. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  51567. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  51568. }
  51569. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51570. this._effect.setTexture("bumpSampler", this.bumpTexture);
  51571. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  51572. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  51573. }
  51574. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51575. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  51576. var depth = 1.0;
  51577. if (this.refractionTexture.isCube) {
  51578. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  51579. }
  51580. else {
  51581. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  51582. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  51583. if (this.refractionTexture.depth) {
  51584. depth = this.refractionTexture.depth;
  51585. }
  51586. }
  51587. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  51588. }
  51589. if ((this.reflectionTexture || this.refractionTexture)) {
  51590. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  51591. }
  51592. if (this.cameraColorGradingTexture) {
  51593. this._effect.setTexture("cameraColorGrading2DSampler", this.cameraColorGradingTexture);
  51594. this._cameraColorGradingInfos.x = this.cameraColorGradingTexture.level; // Texture Level
  51595. this._cameraColorGradingInfos.y = this.cameraColorGradingTexture.getSize().height; // Texture Size example with 8
  51596. this._cameraColorGradingInfos.z = this._cameraColorGradingInfos.y - 1.0; // SizeMinusOne 8 - 1
  51597. this._cameraColorGradingInfos.w = 1 / this._cameraColorGradingInfos.y; // Space of 1 slice 1 / 8
  51598. this._effect.setFloat4("vCameraColorGradingInfos", this._cameraColorGradingInfos.x, this._cameraColorGradingInfos.y, this._cameraColorGradingInfos.z, this._cameraColorGradingInfos.w);
  51599. var slicePixelSizeU = this._cameraColorGradingInfos.w / this._cameraColorGradingInfos.y; // Space of 1 pixel in U direction, e.g. 1/64
  51600. var slicePixelSizeV = 1.0 / this._cameraColorGradingInfos.y; // Space of 1 pixel in V direction, e.g. 1/8
  51601. this._cameraColorGradingScaleOffset.x = this._cameraColorGradingInfos.z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  51602. this._cameraColorGradingScaleOffset.y = this._cameraColorGradingInfos.z /
  51603. this._cameraColorGradingInfos.y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  51604. this._cameraColorGradingScaleOffset.z = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  51605. this._cameraColorGradingScaleOffset.w = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  51606. this._effect.setFloat4("vCameraColorGradingScaleOffset", this._cameraColorGradingScaleOffset.x, this._cameraColorGradingScaleOffset.y, this._cameraColorGradingScaleOffset.z, this._cameraColorGradingScaleOffset.w);
  51607. }
  51608. }
  51609. // Clip plane
  51610. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  51611. // Point size
  51612. if (this.pointsCloud) {
  51613. this._effect.setFloat("pointSize", this.pointSize);
  51614. }
  51615. // Colors
  51616. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  51617. // GAMMA CORRECTION.
  51618. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  51619. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  51620. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  51621. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  51622. // GAMMA CORRECTION.
  51623. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  51624. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  51625. // GAMMA CORRECTION.
  51626. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  51627. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  51628. }
  51629. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  51630. // GAMMA CORRECTION.
  51631. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  51632. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  51633. // Lights
  51634. if (this._myScene.lightsEnabled && !this.disableLighting) {
  51635. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  51636. }
  51637. // View
  51638. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  51639. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  51640. }
  51641. // Fog
  51642. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  51643. this._lightingInfos.x = this.directIntensity;
  51644. this._lightingInfos.y = this.emissiveIntensity;
  51645. this._lightingInfos.z = this.environmentIntensity;
  51646. this._lightingInfos.w = this.specularIntensity;
  51647. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  51648. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  51649. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  51650. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  51651. this._cameraInfos.x = this.cameraExposure;
  51652. this._cameraInfos.y = this.cameraContrast;
  51653. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  51654. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  51655. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  51656. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  51657. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  51658. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  51659. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  51660. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  51661. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  51662. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  51663. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  51664. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  51665. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  51666. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  51667. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  51668. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  51669. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  51670. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  51671. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  51672. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  51673. // Log. depth
  51674. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  51675. }
  51676. _super.prototype.bind.call(this, world, mesh);
  51677. this._myScene = null;
  51678. };
  51679. PBRMaterial.prototype.getAnimatables = function () {
  51680. var results = [];
  51681. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  51682. results.push(this.albedoTexture);
  51683. }
  51684. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  51685. results.push(this.ambientTexture);
  51686. }
  51687. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  51688. results.push(this.opacityTexture);
  51689. }
  51690. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  51691. results.push(this.reflectionTexture);
  51692. }
  51693. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  51694. results.push(this.emissiveTexture);
  51695. }
  51696. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  51697. results.push(this.reflectivityTexture);
  51698. }
  51699. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  51700. results.push(this.bumpTexture);
  51701. }
  51702. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  51703. results.push(this.lightmapTexture);
  51704. }
  51705. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  51706. results.push(this.refractionTexture);
  51707. }
  51708. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  51709. results.push(this.cameraColorGradingTexture);
  51710. }
  51711. return results;
  51712. };
  51713. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  51714. if (forceDisposeTextures) {
  51715. if (this.albedoTexture) {
  51716. this.albedoTexture.dispose();
  51717. }
  51718. if (this.ambientTexture) {
  51719. this.ambientTexture.dispose();
  51720. }
  51721. if (this.opacityTexture) {
  51722. this.opacityTexture.dispose();
  51723. }
  51724. if (this.reflectionTexture) {
  51725. this.reflectionTexture.dispose();
  51726. }
  51727. if (this.emissiveTexture) {
  51728. this.emissiveTexture.dispose();
  51729. }
  51730. if (this.reflectivityTexture) {
  51731. this.reflectivityTexture.dispose();
  51732. }
  51733. if (this.bumpTexture) {
  51734. this.bumpTexture.dispose();
  51735. }
  51736. if (this.lightmapTexture) {
  51737. this.lightmapTexture.dispose();
  51738. }
  51739. if (this.refractionTexture) {
  51740. this.refractionTexture.dispose();
  51741. }
  51742. if (this.cameraColorGradingTexture) {
  51743. this.cameraColorGradingTexture.dispose();
  51744. }
  51745. }
  51746. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  51747. };
  51748. PBRMaterial.prototype.clone = function (name) {
  51749. var _this = this;
  51750. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  51751. };
  51752. PBRMaterial.prototype.serialize = function () {
  51753. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  51754. serializationObject.customType = "BABYLON.PBRMaterial";
  51755. return serializationObject;
  51756. };
  51757. // Statics
  51758. PBRMaterial.Parse = function (source, scene, rootUrl) {
  51759. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  51760. };
  51761. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  51762. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  51763. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  51764. PBRMaterial._scaledReflection = new BABYLON.Color3();
  51765. __decorate([
  51766. BABYLON.serialize()
  51767. ], PBRMaterial.prototype, "directIntensity", void 0);
  51768. __decorate([
  51769. BABYLON.serialize()
  51770. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  51771. __decorate([
  51772. BABYLON.serialize()
  51773. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  51774. __decorate([
  51775. BABYLON.serialize()
  51776. ], PBRMaterial.prototype, "specularIntensity", void 0);
  51777. __decorate([
  51778. BABYLON.serialize()
  51779. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  51780. __decorate([
  51781. BABYLON.serialize()
  51782. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  51783. __decorate([
  51784. BABYLON.serialize()
  51785. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  51786. __decorate([
  51787. BABYLON.serialize()
  51788. ], PBRMaterial.prototype, "cameraExposure", void 0);
  51789. __decorate([
  51790. BABYLON.serialize()
  51791. ], PBRMaterial.prototype, "cameraContrast", void 0);
  51792. __decorate([
  51793. BABYLON.serializeAsTexture()
  51794. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  51795. __decorate([
  51796. BABYLON.serializeAsColor3()
  51797. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  51798. __decorate([
  51799. BABYLON.serialize()
  51800. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  51801. __decorate([
  51802. BABYLON.serializeAsColor3()
  51803. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  51804. __decorate([
  51805. BABYLON.serialize()
  51806. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  51807. __decorate([
  51808. BABYLON.serializeAsColor3()
  51809. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  51810. __decorate([
  51811. BABYLON.serialize()
  51812. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  51813. __decorate([
  51814. BABYLON.serializeAsColor3()
  51815. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  51816. __decorate([
  51817. BABYLON.serialize()
  51818. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  51819. __decorate([
  51820. BABYLON.serializeAsColor3()
  51821. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  51822. __decorate([
  51823. BABYLON.serialize()
  51824. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  51825. __decorate([
  51826. BABYLON.serialize()
  51827. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  51828. __decorate([
  51829. BABYLON.serialize()
  51830. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  51831. __decorate([
  51832. BABYLON.serializeAsTexture()
  51833. ], PBRMaterial.prototype, "albedoTexture", void 0);
  51834. __decorate([
  51835. BABYLON.serializeAsTexture()
  51836. ], PBRMaterial.prototype, "ambientTexture", void 0);
  51837. __decorate([
  51838. BABYLON.serializeAsTexture()
  51839. ], PBRMaterial.prototype, "opacityTexture", void 0);
  51840. __decorate([
  51841. BABYLON.serializeAsTexture()
  51842. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  51843. __decorate([
  51844. BABYLON.serializeAsTexture()
  51845. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  51846. __decorate([
  51847. BABYLON.serializeAsTexture()
  51848. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  51849. __decorate([
  51850. BABYLON.serializeAsTexture()
  51851. ], PBRMaterial.prototype, "bumpTexture", void 0);
  51852. __decorate([
  51853. BABYLON.serializeAsTexture()
  51854. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  51855. __decorate([
  51856. BABYLON.serializeAsTexture()
  51857. ], PBRMaterial.prototype, "refractionTexture", void 0);
  51858. __decorate([
  51859. BABYLON.serializeAsColor3("ambient")
  51860. ], PBRMaterial.prototype, "ambientColor", void 0);
  51861. __decorate([
  51862. BABYLON.serializeAsColor3("albedo")
  51863. ], PBRMaterial.prototype, "albedoColor", void 0);
  51864. __decorate([
  51865. BABYLON.serializeAsColor3("reflectivity")
  51866. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  51867. __decorate([
  51868. BABYLON.serializeAsColor3("reflection")
  51869. ], PBRMaterial.prototype, "reflectionColor", void 0);
  51870. __decorate([
  51871. BABYLON.serializeAsColor3("emissive")
  51872. ], PBRMaterial.prototype, "emissiveColor", void 0);
  51873. __decorate([
  51874. BABYLON.serialize()
  51875. ], PBRMaterial.prototype, "microSurface", void 0);
  51876. __decorate([
  51877. BABYLON.serialize()
  51878. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  51879. __decorate([
  51880. BABYLON.serialize()
  51881. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  51882. __decorate([
  51883. BABYLON.serializeAsFresnelParameters()
  51884. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  51885. __decorate([
  51886. BABYLON.serializeAsFresnelParameters()
  51887. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  51888. __decorate([
  51889. BABYLON.serialize()
  51890. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  51891. __decorate([
  51892. BABYLON.serialize()
  51893. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  51894. __decorate([
  51895. BABYLON.serialize()
  51896. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  51897. __decorate([
  51898. BABYLON.serialize()
  51899. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  51900. __decorate([
  51901. BABYLON.serialize()
  51902. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  51903. __decorate([
  51904. BABYLON.serialize()
  51905. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  51906. __decorate([
  51907. BABYLON.serialize()
  51908. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  51909. __decorate([
  51910. BABYLON.serialize()
  51911. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  51912. __decorate([
  51913. BABYLON.serialize()
  51914. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  51915. __decorate([
  51916. BABYLON.serialize()
  51917. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  51918. __decorate([
  51919. BABYLON.serialize()
  51920. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  51921. __decorate([
  51922. BABYLON.serialize()
  51923. ], PBRMaterial.prototype, "useParallax", void 0);
  51924. __decorate([
  51925. BABYLON.serialize()
  51926. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  51927. __decorate([
  51928. BABYLON.serialize()
  51929. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  51930. __decorate([
  51931. BABYLON.serialize()
  51932. ], PBRMaterial.prototype, "disableLighting", void 0);
  51933. __decorate([
  51934. BABYLON.serialize()
  51935. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  51936. __decorate([
  51937. BABYLON.serialize()
  51938. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  51939. __decorate([
  51940. BABYLON.serialize()
  51941. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  51942. __decorate([
  51943. BABYLON.serialize()
  51944. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  51945. return PBRMaterial;
  51946. })(BABYLON.Material);
  51947. BABYLON.PBRMaterial = PBRMaterial;
  51948. })(BABYLON || (BABYLON = {}));
  51949. var BABYLON;
  51950. (function (BABYLON) {
  51951. var DebugLayer = (function () {
  51952. function DebugLayer(scene) {
  51953. var _this = this;
  51954. this._transformationMatrix = BABYLON.Matrix.Identity();
  51955. this._enabled = false;
  51956. this._labelsEnabled = false;
  51957. this._displayStatistics = true;
  51958. this._displayTree = false;
  51959. this._displayLogs = false;
  51960. this._skeletonViewers = new Array();
  51961. this._identityMatrix = BABYLON.Matrix.Identity();
  51962. this.axisRatio = 0.02;
  51963. this.accentColor = "orange";
  51964. this._scene = scene;
  51965. this._syncPositions = function () {
  51966. var engine = _this._scene.getEngine();
  51967. var canvasRect = engine.getRenderingCanvasClientRect();
  51968. if (_this._showUI) {
  51969. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  51970. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  51971. _this._statsDiv.style.width = "400px";
  51972. _this._statsDiv.style.height = "auto";
  51973. _this._statsSubsetDiv.style.maxHeight = "240px";
  51974. _this._optionsDiv.style.left = "0px";
  51975. _this._optionsDiv.style.top = "10px";
  51976. _this._optionsDiv.style.width = "200px";
  51977. _this._optionsDiv.style.height = "auto";
  51978. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  51979. _this._logDiv.style.left = "0px";
  51980. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  51981. _this._logDiv.style.width = "600px";
  51982. _this._logDiv.style.height = "160px";
  51983. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  51984. _this._treeDiv.style.top = "10px";
  51985. _this._treeDiv.style.width = "300px";
  51986. _this._treeDiv.style.height = "auto";
  51987. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  51988. }
  51989. _this._globalDiv.style.left = canvasRect.left + "px";
  51990. _this._globalDiv.style.top = canvasRect.top + "px";
  51991. _this._drawingCanvas.style.left = "0px";
  51992. _this._drawingCanvas.style.top = "0px";
  51993. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  51994. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  51995. var devicePixelRatio = window.devicePixelRatio || 1;
  51996. var context = _this._drawingContext;
  51997. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  51998. context.mozBackingStorePixelRatio ||
  51999. context.msBackingStorePixelRatio ||
  52000. context.oBackingStorePixelRatio ||
  52001. context.backingStorePixelRatio || 1;
  52002. _this._ratio = devicePixelRatio / backingStoreRatio;
  52003. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  52004. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  52005. };
  52006. this._onCanvasClick = function (evt) {
  52007. _this._clickPosition = {
  52008. x: evt.clientX * _this._ratio,
  52009. y: evt.clientY * _this._ratio
  52010. };
  52011. };
  52012. this._syncUI = function () {
  52013. if (_this._showUI) {
  52014. if (_this._displayStatistics) {
  52015. _this._displayStats();
  52016. _this._statsDiv.style.display = "";
  52017. }
  52018. else {
  52019. _this._statsDiv.style.display = "none";
  52020. }
  52021. if (_this._displayLogs) {
  52022. _this._logDiv.style.display = "";
  52023. }
  52024. else {
  52025. _this._logDiv.style.display = "none";
  52026. }
  52027. if (_this._displayTree) {
  52028. _this._treeDiv.style.display = "";
  52029. if (_this._needToRefreshMeshesTree) {
  52030. _this._needToRefreshMeshesTree = false;
  52031. _this._refreshMeshesTreeContent();
  52032. }
  52033. }
  52034. else {
  52035. _this._treeDiv.style.display = "none";
  52036. }
  52037. }
  52038. };
  52039. this._syncData = function () {
  52040. if (_this._labelsEnabled || !_this._showUI) {
  52041. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  52042. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  52043. var engine = _this._scene.getEngine();
  52044. var viewport = _this._camera.viewport;
  52045. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52046. // Meshes
  52047. var meshes = _this._camera.getActiveMeshes();
  52048. var index;
  52049. var projectedPosition;
  52050. for (index = 0; index < meshes.length; index++) {
  52051. var mesh = meshes.data[index];
  52052. var position = mesh.getBoundingInfo().boundingSphere.center;
  52053. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52054. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  52055. _this._renderAxis(projectedPosition, mesh, globalViewport);
  52056. }
  52057. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  52058. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  52059. }
  52060. }
  52061. // Cameras
  52062. var cameras = _this._scene.cameras;
  52063. for (index = 0; index < cameras.length; index++) {
  52064. var camera = cameras[index];
  52065. if (camera === _this._camera) {
  52066. continue;
  52067. }
  52068. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52069. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  52070. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  52071. _this._camera.detachControl(engine.getRenderingCanvas());
  52072. _this._camera = camera;
  52073. _this._camera.attachControl(engine.getRenderingCanvas());
  52074. }, function () { return "purple"; });
  52075. }
  52076. }
  52077. // Lights
  52078. var lights = _this._scene.lights;
  52079. for (index = 0; index < lights.length; index++) {
  52080. var light = lights[index];
  52081. if (light.position) {
  52082. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  52083. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  52084. _this._renderLabel(light.name, projectedPosition, -20, function () {
  52085. light.setEnabled(!light.isEnabled());
  52086. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  52087. }
  52088. }
  52089. }
  52090. }
  52091. _this._clickPosition = undefined;
  52092. };
  52093. }
  52094. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  52095. while (this._treeSubsetDiv.hasChildNodes()) {
  52096. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  52097. }
  52098. // Add meshes
  52099. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  52100. sortedArray.sort(function (a, b) {
  52101. if (a.name === b.name) {
  52102. return 0;
  52103. }
  52104. return (a.name > b.name) ? 1 : -1;
  52105. });
  52106. for (var index = 0; index < sortedArray.length; index++) {
  52107. var mesh = sortedArray[index];
  52108. if (!mesh.isEnabled()) {
  52109. continue;
  52110. }
  52111. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  52112. m.isVisible = element.checked;
  52113. }, mesh);
  52114. }
  52115. };
  52116. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  52117. this._drawingContext.beginPath();
  52118. this._drawingContext.moveTo(zero.x, zero.y);
  52119. this._drawingContext.lineTo(unit.x, unit.y);
  52120. this._drawingContext.strokeStyle = color;
  52121. this._drawingContext.lineWidth = 4;
  52122. this._drawingContext.stroke();
  52123. this._drawingContext.font = "normal 14px Segoe UI";
  52124. this._drawingContext.fillStyle = color;
  52125. this._drawingContext.fillText(label, unitText.x, unitText.y);
  52126. };
  52127. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  52128. var position = mesh.getBoundingInfo().boundingSphere.center;
  52129. var worldMatrix = mesh.getWorldMatrix();
  52130. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  52131. var unit = (unprojectedVector.subtract(position)).length();
  52132. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52133. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52134. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  52135. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52136. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52137. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  52138. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  52139. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  52140. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  52141. };
  52142. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  52143. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  52144. this._drawingContext.font = "normal 12px Segoe UI";
  52145. var textMetrics = this._drawingContext.measureText(text);
  52146. var centerX = projectedPosition.x - textMetrics.width / 2;
  52147. var centerY = projectedPosition.y;
  52148. var clientRect = this._drawingCanvas.getBoundingClientRect();
  52149. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  52150. onClick();
  52151. }
  52152. this._drawingContext.beginPath();
  52153. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  52154. this._drawingContext.fillStyle = getFillStyle();
  52155. this._drawingContext.globalAlpha = 0.5;
  52156. this._drawingContext.fill();
  52157. this._drawingContext.globalAlpha = 1.0;
  52158. this._drawingContext.strokeStyle = '#FFFFFF';
  52159. this._drawingContext.lineWidth = 1;
  52160. this._drawingContext.stroke();
  52161. this._drawingContext.fillStyle = "#FFFFFF";
  52162. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  52163. this._drawingContext.beginPath();
  52164. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  52165. this._drawingContext.fill();
  52166. }
  52167. };
  52168. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  52169. if (!this._clickPosition) {
  52170. return false;
  52171. }
  52172. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  52173. return false;
  52174. }
  52175. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  52176. return false;
  52177. }
  52178. return true;
  52179. };
  52180. DebugLayer.prototype.isVisible = function () {
  52181. return this._enabled;
  52182. };
  52183. DebugLayer.prototype.hide = function () {
  52184. if (!this._enabled) {
  52185. return;
  52186. }
  52187. this._enabled = false;
  52188. var engine = this._scene.getEngine();
  52189. this._scene.unregisterBeforeRender(this._syncData);
  52190. this._scene.unregisterAfterRender(this._syncUI);
  52191. this._rootElement.removeChild(this._globalDiv);
  52192. this._scene.forceShowBoundingBoxes = false;
  52193. this._scene.forceWireframe = false;
  52194. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  52195. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  52196. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  52197. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  52198. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  52199. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  52200. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  52201. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  52202. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  52203. this._scene.shadowsEnabled = true;
  52204. this._scene.particlesEnabled = true;
  52205. this._scene.postProcessesEnabled = true;
  52206. this._scene.collisionsEnabled = true;
  52207. this._scene.lightsEnabled = true;
  52208. this._scene.texturesEnabled = true;
  52209. this._scene.lensFlaresEnabled = true;
  52210. this._scene.proceduralTexturesEnabled = true;
  52211. this._scene.renderTargetsEnabled = true;
  52212. this._scene.probesEnabled = true;
  52213. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  52214. this._clearSkeletonViewers();
  52215. };
  52216. DebugLayer.prototype._clearSkeletonViewers = function () {
  52217. for (var index = 0; index < this._skeletonViewers.length; index++) {
  52218. this._skeletonViewers[index].dispose();
  52219. }
  52220. this._skeletonViewers = [];
  52221. };
  52222. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  52223. if (showUI === void 0) { showUI = true; }
  52224. if (camera === void 0) { camera = null; }
  52225. if (rootElement === void 0) { rootElement = null; }
  52226. if (this._enabled) {
  52227. return;
  52228. }
  52229. this._enabled = true;
  52230. if (camera) {
  52231. this._camera = camera;
  52232. }
  52233. else {
  52234. this._camera = this._scene.activeCamera;
  52235. }
  52236. this._showUI = showUI;
  52237. var engine = this._scene.getEngine();
  52238. this._globalDiv = document.createElement("div");
  52239. this._rootElement = rootElement || document.body;
  52240. this._rootElement.appendChild(this._globalDiv);
  52241. this._generateDOMelements();
  52242. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  52243. this._syncPositions();
  52244. this._scene.registerBeforeRender(this._syncData);
  52245. this._scene.registerAfterRender(this._syncUI);
  52246. };
  52247. DebugLayer.prototype._clearLabels = function () {
  52248. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  52249. for (var index = 0; index < this._scene.meshes.length; index++) {
  52250. var mesh = this._scene.meshes[index];
  52251. mesh.renderOverlay = false;
  52252. }
  52253. };
  52254. DebugLayer.prototype._generateheader = function (root, text) {
  52255. var header = document.createElement("div");
  52256. header.innerHTML = text + "&nbsp;";
  52257. header.style.textAlign = "right";
  52258. header.style.width = "100%";
  52259. header.style.color = "white";
  52260. header.style.backgroundColor = "Black";
  52261. header.style.padding = "5px 5px 4px 0px";
  52262. header.style.marginLeft = "-5px";
  52263. header.style.fontWeight = "bold";
  52264. root.appendChild(header);
  52265. };
  52266. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  52267. var label = document.createElement("label");
  52268. label.style.display = "inline";
  52269. label.innerHTML = title;
  52270. label.style.color = color;
  52271. root.appendChild(label);
  52272. root.appendChild(document.createElement("br"));
  52273. };
  52274. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  52275. if (tag === void 0) { tag = null; }
  52276. var label = document.createElement("label");
  52277. label.style.display = "inline";
  52278. var boundingBoxesCheckbox = document.createElement("input");
  52279. boundingBoxesCheckbox.type = "checkbox";
  52280. boundingBoxesCheckbox.checked = initialState;
  52281. boundingBoxesCheckbox.style.display = "inline";
  52282. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  52283. boundingBoxesCheckbox.style.verticalAlign = "sub";
  52284. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  52285. task(evt.target, tag);
  52286. });
  52287. label.appendChild(boundingBoxesCheckbox);
  52288. var container = document.createElement("span");
  52289. var leftPart = document.createElement("span");
  52290. var rightPart = document.createElement("span");
  52291. rightPart.style.cssFloat = "right";
  52292. leftPart.innerHTML = leftTitle;
  52293. rightPart.innerHTML = rightTitle;
  52294. rightPart.style.fontSize = "12px";
  52295. rightPart.style.maxWidth = "200px";
  52296. container.appendChild(leftPart);
  52297. container.appendChild(rightPart);
  52298. label.appendChild(container);
  52299. root.appendChild(label);
  52300. root.appendChild(document.createElement("br"));
  52301. };
  52302. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  52303. if (tag === void 0) { tag = null; }
  52304. var label = document.createElement("label");
  52305. label.style.display = "inline";
  52306. var checkBox = document.createElement("input");
  52307. checkBox.type = "checkbox";
  52308. checkBox.checked = initialState;
  52309. checkBox.style.display = "inline";
  52310. checkBox.style.margin = "0px 5px 0px 0px";
  52311. checkBox.style.verticalAlign = "sub";
  52312. checkBox.addEventListener("change", function (evt) {
  52313. task(evt.target, tag);
  52314. });
  52315. label.appendChild(checkBox);
  52316. label.appendChild(document.createTextNode(title));
  52317. root.appendChild(label);
  52318. root.appendChild(document.createElement("br"));
  52319. };
  52320. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  52321. if (tag === void 0) { tag = null; }
  52322. var button = document.createElement("button");
  52323. button.innerHTML = title;
  52324. button.style.height = "24px";
  52325. button.style.width = "150px";
  52326. button.style.marginBottom = "5px";
  52327. button.style.color = "#444444";
  52328. button.style.border = "1px solid white";
  52329. button.className = "debugLayerButton";
  52330. button.addEventListener("click", function (evt) {
  52331. task(evt.target, tag);
  52332. });
  52333. root.appendChild(button);
  52334. root.appendChild(document.createElement("br"));
  52335. };
  52336. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  52337. if (tag === void 0) { tag = null; }
  52338. var label = document.createElement("label");
  52339. label.style.display = "inline";
  52340. var boundingBoxesRadio = document.createElement("input");
  52341. boundingBoxesRadio.type = "radio";
  52342. boundingBoxesRadio.name = name;
  52343. boundingBoxesRadio.checked = initialState;
  52344. boundingBoxesRadio.style.display = "inline";
  52345. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  52346. boundingBoxesRadio.style.verticalAlign = "sub";
  52347. boundingBoxesRadio.addEventListener("change", function (evt) {
  52348. task(evt.target, tag);
  52349. });
  52350. label.appendChild(boundingBoxesRadio);
  52351. label.appendChild(document.createTextNode(title));
  52352. root.appendChild(label);
  52353. root.appendChild(document.createElement("br"));
  52354. };
  52355. DebugLayer.prototype._generateDOMelements = function () {
  52356. var _this = this;
  52357. this._globalDiv.id = "DebugLayer";
  52358. this._globalDiv.style.position = "absolute";
  52359. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  52360. this._globalDiv.style.fontSize = "14px";
  52361. this._globalDiv.style.color = "white";
  52362. // Drawing canvas
  52363. this._drawingCanvas = document.createElement("canvas");
  52364. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  52365. this._drawingCanvas.style.position = "absolute";
  52366. this._drawingCanvas.style.pointerEvents = "none";
  52367. this._drawingCanvas.style.backgroundColor = "transparent";
  52368. this._drawingContext = this._drawingCanvas.getContext("2d");
  52369. this._globalDiv.appendChild(this._drawingCanvas);
  52370. if (this._showUI) {
  52371. var background = "rgba(128, 128, 128, 0.4)";
  52372. var border = "rgb(180, 180, 180) solid 1px";
  52373. // Stats
  52374. this._statsDiv = document.createElement("div");
  52375. this._statsDiv.id = "DebugLayerStats";
  52376. this._statsDiv.style.border = border;
  52377. this._statsDiv.style.position = "absolute";
  52378. this._statsDiv.style.background = background;
  52379. this._statsDiv.style.padding = "0px 0px 0px 5px";
  52380. this._generateheader(this._statsDiv, "STATISTICS");
  52381. this._statsSubsetDiv = document.createElement("div");
  52382. this._statsSubsetDiv.style.paddingTop = "5px";
  52383. this._statsSubsetDiv.style.paddingBottom = "5px";
  52384. this._statsSubsetDiv.style.overflowY = "auto";
  52385. this._statsDiv.appendChild(this._statsSubsetDiv);
  52386. // Tree
  52387. this._treeDiv = document.createElement("div");
  52388. this._treeDiv.id = "DebugLayerTree";
  52389. this._treeDiv.style.border = border;
  52390. this._treeDiv.style.position = "absolute";
  52391. this._treeDiv.style.background = background;
  52392. this._treeDiv.style.padding = "0px 0px 0px 5px";
  52393. this._treeDiv.style.display = "none";
  52394. this._generateheader(this._treeDiv, "MESHES TREE");
  52395. this._treeSubsetDiv = document.createElement("div");
  52396. this._treeSubsetDiv.style.paddingTop = "5px";
  52397. this._treeSubsetDiv.style.paddingRight = "5px";
  52398. this._treeSubsetDiv.style.overflowY = "auto";
  52399. this._treeSubsetDiv.style.maxHeight = "300px";
  52400. this._treeDiv.appendChild(this._treeSubsetDiv);
  52401. this._needToRefreshMeshesTree = true;
  52402. // Logs
  52403. this._logDiv = document.createElement("div");
  52404. this._logDiv.style.border = border;
  52405. this._logDiv.id = "DebugLayerLogs";
  52406. this._logDiv.style.position = "absolute";
  52407. this._logDiv.style.background = background;
  52408. this._logDiv.style.padding = "0px 0px 0px 5px";
  52409. this._logDiv.style.display = "none";
  52410. this._generateheader(this._logDiv, "LOGS");
  52411. this._logSubsetDiv = document.createElement("div");
  52412. this._logSubsetDiv.style.height = "127px";
  52413. this._logSubsetDiv.style.paddingTop = "5px";
  52414. this._logSubsetDiv.style.overflowY = "auto";
  52415. this._logSubsetDiv.style.fontSize = "12px";
  52416. this._logSubsetDiv.style.fontFamily = "consolas";
  52417. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  52418. this._logDiv.appendChild(this._logSubsetDiv);
  52419. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  52420. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  52421. };
  52422. // Options
  52423. this._optionsDiv = document.createElement("div");
  52424. this._optionsDiv.id = "DebugLayerOptions";
  52425. this._optionsDiv.style.border = border;
  52426. this._optionsDiv.style.position = "absolute";
  52427. this._optionsDiv.style.background = background;
  52428. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  52429. this._optionsDiv.style.overflowY = "auto";
  52430. this._generateheader(this._optionsDiv, "OPTIONS");
  52431. this._optionsSubsetDiv = document.createElement("div");
  52432. this._optionsSubsetDiv.style.paddingTop = "5px";
  52433. this._optionsSubsetDiv.style.paddingBottom = "5px";
  52434. this._optionsSubsetDiv.style.overflowY = "auto";
  52435. this._optionsSubsetDiv.style.maxHeight = "200px";
  52436. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  52437. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  52438. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  52439. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  52440. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  52441. _this._displayTree = element.checked;
  52442. _this._needToRefreshMeshesTree = true;
  52443. });
  52444. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52445. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  52446. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  52447. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  52448. _this._labelsEnabled = element.checked;
  52449. if (!_this._labelsEnabled) {
  52450. _this._clearLabels();
  52451. }
  52452. });
  52453. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  52454. if (element.checked) {
  52455. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  52456. }
  52457. else {
  52458. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  52459. }
  52460. });
  52461. ;
  52462. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52463. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  52464. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  52465. if (element.checked) {
  52466. _this._scene.forceWireframe = false;
  52467. _this._scene.forcePointsCloud = false;
  52468. }
  52469. });
  52470. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  52471. if (element.checked) {
  52472. _this._scene.forceWireframe = true;
  52473. _this._scene.forcePointsCloud = false;
  52474. }
  52475. });
  52476. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  52477. if (element.checked) {
  52478. _this._scene.forceWireframe = false;
  52479. _this._scene.forcePointsCloud = true;
  52480. }
  52481. });
  52482. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52483. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  52484. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  52485. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  52486. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  52487. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  52488. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  52489. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  52490. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  52491. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  52492. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  52493. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  52494. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52495. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  52496. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  52497. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  52498. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  52499. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  52500. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  52501. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  52502. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  52503. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  52504. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  52505. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  52506. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  52507. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  52508. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  52509. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  52510. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  52511. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52512. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  52513. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  52514. if (element.checked) {
  52515. _this._scene.headphone = true;
  52516. }
  52517. });
  52518. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  52519. if (element.checked) {
  52520. _this._scene.headphone = false;
  52521. }
  52522. });
  52523. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  52524. _this._scene.audioEnabled = !element.checked;
  52525. });
  52526. }
  52527. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52528. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  52529. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  52530. if (!element.checked) {
  52531. _this._clearSkeletonViewers();
  52532. return;
  52533. }
  52534. for (var index = 0; index < _this._scene.meshes.length; index++) {
  52535. var mesh = _this._scene.meshes[index];
  52536. if (mesh.skeleton) {
  52537. var found = false;
  52538. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  52539. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  52540. found = true;
  52541. break;
  52542. }
  52543. }
  52544. if (found) {
  52545. continue;
  52546. }
  52547. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  52548. viewer.isEnabled = true;
  52549. _this._skeletonViewers.push(viewer);
  52550. }
  52551. }
  52552. });
  52553. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52554. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  52555. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  52556. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  52557. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  52558. if (_this._camera) {
  52559. console.log(_this._camera);
  52560. }
  52561. else {
  52562. console.warn("No camera defined, or debug layer created before camera creation!");
  52563. }
  52564. });
  52565. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  52566. this._globalDiv.appendChild(this._statsDiv);
  52567. this._globalDiv.appendChild(this._logDiv);
  52568. this._globalDiv.appendChild(this._optionsDiv);
  52569. this._globalDiv.appendChild(this._treeDiv);
  52570. }
  52571. };
  52572. DebugLayer.prototype._displayStats = function () {
  52573. var scene = this._scene;
  52574. var engine = scene.getEngine();
  52575. var glInfo = engine.getGlInfo();
  52576. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  52577. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52578. + "<b>Count</b><br>"
  52579. + "Total meshes: " + scene.meshes.length + "<br>"
  52580. + "Total lights: " + scene.lights.length + "<br>"
  52581. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  52582. + "Total materials: " + scene.materials.length + "<br>"
  52583. + "Total textures: " + scene.textures.length + "<br>"
  52584. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  52585. + "Active indices: " + scene.getActiveIndices() + "<br>"
  52586. + "Active bones: " + scene.getActiveBones() + "<br>"
  52587. + "Active particles: " + scene.getActiveParticles() + "<br>"
  52588. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  52589. + "<b>Duration</b><br>"
  52590. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  52591. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  52592. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  52593. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  52594. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  52595. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  52596. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  52597. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  52598. + "</div>"
  52599. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52600. + "<b>Extensions</b><br>"
  52601. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  52602. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  52603. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  52604. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  52605. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  52606. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  52607. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  52608. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  52609. + "</div><br>"
  52610. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  52611. + "<b>Caps.</b><br>"
  52612. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  52613. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  52614. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  52615. + "<b>Info</b><br>"
  52616. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  52617. + glInfo.version + "<br>"
  52618. + "</div><br>"
  52619. + glInfo.renderer + "<br>";
  52620. if (this.customStatsFunction) {
  52621. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  52622. }
  52623. };
  52624. return DebugLayer;
  52625. })();
  52626. BABYLON.DebugLayer = DebugLayer;
  52627. })(BABYLON || (BABYLON = {}));
  52628. 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#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\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>\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>\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}","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>\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>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \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#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 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\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\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\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,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\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>\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}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec2 origin;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvec4 pos;\npos.xy=(pos2.xy-origin)*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\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":"vec4 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}\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;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\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}","sprite2dPixelShader":"varying vec2 vUV;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.w == 0.0) {\ndiscard;\n}\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 origin;\natt vec2 textureSize;\natt float frame;\natt float invertY;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\n\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x)+off.x,(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\npos.xy=(pos2.xy*sizeUV*textureSize)-origin;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\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":"uniform sampler2D textureSampler;\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;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\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","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","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}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 origin;\natt vec2 textureSize;\natt vec4 color;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\nvColor=color;\nvec4 pos;\npos.xy=(pos2.xy*sizeUV*textureSize)-origin;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,zBias.y);\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}"};
  52629. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","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#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#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\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\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)\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,vec3(1.,1.,1.));\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}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\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\n#ifdef CAMERACOLORGRADING\nvec4 colorGrades(vec4 color,sampler2D texture,vec4 vCameraColorGradingInfos,vec4 vCameraColorGradingScaleOffset) \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(texture,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(texture,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}\n#endif","pbrLightFunctions":"\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 rangeRadius,float roughness,float NdotV,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=computeLightFalloff(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);\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,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nattenuation*=cosAngle;\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);\nresult.specular=specTerm*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 roughness,float NdotV,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);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\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,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,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,NdotL);\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\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","pbrShadowFunctions":"\n#ifdef SHADOWS\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#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\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;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\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;\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#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#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\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}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\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;\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#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\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\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);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\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\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\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#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\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;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\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;\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;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\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}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\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;\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;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\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);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  52630. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},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 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(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?!1:!!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||0>V)return;0>h&&(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 m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,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(f,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(f,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(f=g*-m+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(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(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),f=g*-m+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(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(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),f=g*-m+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(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(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;s>c;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;a>c;++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;r>s;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;s>t;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;a>t;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 r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"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,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},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.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),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},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.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.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,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-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 s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,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,s=t.y+(i.y-t.y)*r;return new n(o,s)},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.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}();t.Vector2=o;var s=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)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,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 s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);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.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],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=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=s/a,o.y=e/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){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},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,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-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 s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,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,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},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){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},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 s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},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,s,e){var h=r.normalize(),a=s.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=c,e.y=y,e.z=f},n}();t.Vector3=s;var e=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 s(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,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;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.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},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,s=i.height+(n.height-i.height)*r;return new t(o,s)},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,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),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=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,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,s=this.z*this.w,e=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+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+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],s=r[4],e=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=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+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){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},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,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);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),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*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]?!1: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],s=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]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},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;16>t;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;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;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],s=this.m[4],e=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],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,b=-(s*v-e*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,C=s*x-a*p,Z=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,H=e*y-h*m,N=s*c-a*u,V=s*y-h*u,D=s*m-e*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*P)*F,t.m[6]=-(i*A-r*C+o*Z)*F,t.m[10]=(i*L-n*C+o*S)*F,t.m[14]=-(i*P-n*Z+r*S)*F,t.m[3]=-(n*I-r*q+o*H)*F,t.m[7]=(i*I-r*N+o*V)*F,t.m[11]=-(i*q-n*N+o*D)*F,t.m[15]=(i*H-n*V+r*D)*F,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 s(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;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=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],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],C=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*F+e*C,i[n+1]=r*d+o*_+s*A+e*Z,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*b+s*P+e*I,i[n+4]=h*v+a*R+u*F+m*C,i[n+5]=h*d+a*_+u*A+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*P+m*I,i[n+8]=y*v+c*R+p*F+f*C,i[n+9]=y*d+c*_+p*A+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*P+f*I,i[n+12]=l*v+x*R+z*F+w*C,i[n+13]=l*d+x*_+z*A+w*Z,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*P+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;16>i;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){\no.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=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;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*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)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(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);return a.FromRotationMatrixToRef(u,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;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||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,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,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]=l,z.m[15]=x,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),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),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),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+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(),s=0;16>s;s++)o.m[s]=i.m[s]*(1-r)+n.m[s]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new s(0,0,0),e=new a,h=new s(0,0,0);i.decompose(o,e,h);var u=new s(0,0,0),m=new a,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=a.Slerp(e,m,r),f=s.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(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.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,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),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]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,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]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*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.GetFinalMatrix=function(i,n,r,o,s,e){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,e-s,0,u+h/2,a/2+m,s,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,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new s(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,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*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,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*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=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.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 s.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;6>r;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 s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*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 l=t.Orientation,x=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=x;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),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(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((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.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,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(e,h,a),m=u.angle.radians()/s;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;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(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.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]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),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]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.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 e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},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 e=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;o>=a;a++)e.push(new s(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(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(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 s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.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(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},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=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(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 T=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(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=T;var R=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.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=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.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={}));";
  52631. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  52632. module.exports = BABYLON;
  52633. };