babylon.max.js 2.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792
  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. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = 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.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. }());
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. }());
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. }());
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. 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);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. }());
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.clone = function () {
  1188. return new Vector4(this.x, this.y, this.z, this.w);
  1189. };
  1190. Vector4.prototype.copyFrom = function (source) {
  1191. this.x = source.x;
  1192. this.y = source.y;
  1193. this.z = source.z;
  1194. this.w = source.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1198. this.x = x;
  1199. this.y = y;
  1200. this.z = z;
  1201. this.w = w;
  1202. return this;
  1203. };
  1204. // Statics
  1205. Vector4.FromArray = function (array, offset) {
  1206. if (!offset) {
  1207. offset = 0;
  1208. }
  1209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1210. };
  1211. Vector4.FromArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1218. result.x = array[offset];
  1219. result.y = array[offset + 1];
  1220. result.z = array[offset + 2];
  1221. result.w = array[offset + 3];
  1222. };
  1223. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1224. result.x = x;
  1225. result.y = y;
  1226. result.z = z;
  1227. result.w = w;
  1228. };
  1229. Vector4.Zero = function () {
  1230. return new Vector4(0, 0, 0, 0);
  1231. };
  1232. Vector4.Normalize = function (vector) {
  1233. var result = Vector4.Zero();
  1234. Vector4.NormalizeToRef(vector, result);
  1235. return result;
  1236. };
  1237. Vector4.NormalizeToRef = function (vector, result) {
  1238. result.copyFrom(vector);
  1239. result.normalize();
  1240. };
  1241. Vector4.Minimize = function (left, right) {
  1242. var min = left.clone();
  1243. min.MinimizeInPlace(right);
  1244. return min;
  1245. };
  1246. Vector4.Maximize = function (left, right) {
  1247. var max = left.clone();
  1248. max.MaximizeInPlace(right);
  1249. return max;
  1250. };
  1251. Vector4.Distance = function (value1, value2) {
  1252. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1253. };
  1254. Vector4.DistanceSquared = function (value1, value2) {
  1255. var x = value1.x - value2.x;
  1256. var y = value1.y - value2.y;
  1257. var z = value1.z - value2.z;
  1258. var w = value1.w - value2.w;
  1259. return (x * x) + (y * y) + (z * z) + (w * w);
  1260. };
  1261. Vector4.Center = function (value1, value2) {
  1262. var center = value1.add(value2);
  1263. center.scaleInPlace(0.5);
  1264. return center;
  1265. };
  1266. return Vector4;
  1267. }());
  1268. BABYLON.Vector4 = Vector4;
  1269. var Quaternion = (function () {
  1270. function Quaternion(x, y, z, w) {
  1271. if (x === void 0) { x = 0; }
  1272. if (y === void 0) { y = 0; }
  1273. if (z === void 0) { z = 0; }
  1274. if (w === void 0) { w = 1; }
  1275. this.x = x;
  1276. this.y = y;
  1277. this.z = z;
  1278. this.w = w;
  1279. }
  1280. Quaternion.prototype.toString = function () {
  1281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1282. };
  1283. Quaternion.prototype.asArray = function () {
  1284. return [this.x, this.y, this.z, this.w];
  1285. };
  1286. Quaternion.prototype.equals = function (otherQuaternion) {
  1287. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1288. };
  1289. Quaternion.prototype.clone = function () {
  1290. return new Quaternion(this.x, this.y, this.z, this.w);
  1291. };
  1292. Quaternion.prototype.copyFrom = function (other) {
  1293. this.x = other.x;
  1294. this.y = other.y;
  1295. this.z = other.z;
  1296. this.w = other.w;
  1297. return this;
  1298. };
  1299. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1300. this.x = x;
  1301. this.y = y;
  1302. this.z = z;
  1303. this.w = w;
  1304. return this;
  1305. };
  1306. Quaternion.prototype.add = function (other) {
  1307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1308. };
  1309. Quaternion.prototype.subtract = function (other) {
  1310. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1311. };
  1312. Quaternion.prototype.scale = function (value) {
  1313. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1314. };
  1315. Quaternion.prototype.multiply = function (q1) {
  1316. var result = new Quaternion(0, 0, 0, 1.0);
  1317. this.multiplyToRef(q1, result);
  1318. return result;
  1319. };
  1320. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1321. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1322. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1323. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1324. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1325. result.copyFromFloats(x, y, z, w);
  1326. return this;
  1327. };
  1328. Quaternion.prototype.multiplyInPlace = function (q1) {
  1329. this.multiplyToRef(q1, this);
  1330. return this;
  1331. };
  1332. Quaternion.prototype.conjugateToRef = function (ref) {
  1333. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugateInPlace = function () {
  1337. this.x *= -1;
  1338. this.y *= -1;
  1339. this.z *= -1;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.conjugate = function () {
  1343. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1344. return result;
  1345. };
  1346. Quaternion.prototype.length = function () {
  1347. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1348. };
  1349. Quaternion.prototype.normalize = function () {
  1350. var length = 1.0 / this.length();
  1351. this.x *= length;
  1352. this.y *= length;
  1353. this.z *= length;
  1354. this.w *= length;
  1355. return this;
  1356. };
  1357. Quaternion.prototype.toEulerAngles = function (order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var result = Vector3.Zero();
  1360. this.toEulerAnglesToRef(result, order);
  1361. return result;
  1362. };
  1363. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1364. if (order === void 0) { order = "YZX"; }
  1365. var heading, attitude, bank;
  1366. var x = this.x, y = this.y, z = this.z, w = this.w;
  1367. switch (order) {
  1368. case "YZX":
  1369. var test = x * y + z * w;
  1370. if (test > 0.499) {
  1371. heading = 2 * Math.atan2(x, w);
  1372. attitude = Math.PI / 2;
  1373. bank = 0;
  1374. }
  1375. if (test < -0.499) {
  1376. heading = -2 * Math.atan2(x, w);
  1377. attitude = -Math.PI / 2;
  1378. bank = 0;
  1379. }
  1380. if (isNaN(heading)) {
  1381. var sqx = x * x;
  1382. var sqy = y * y;
  1383. var sqz = z * z;
  1384. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1385. attitude = Math.asin(2 * test); // attitude
  1386. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1387. }
  1388. break;
  1389. default:
  1390. throw new Error("Euler order " + order + " not supported yet.");
  1391. }
  1392. result.y = heading;
  1393. result.z = attitude;
  1394. result.x = bank;
  1395. return this;
  1396. };
  1397. ;
  1398. Quaternion.prototype.toRotationMatrix = function (result) {
  1399. var xx = this.x * this.x;
  1400. var yy = this.y * this.y;
  1401. var zz = this.z * this.z;
  1402. var xy = this.x * this.y;
  1403. var zw = this.z * this.w;
  1404. var zx = this.z * this.x;
  1405. var yw = this.y * this.w;
  1406. var yz = this.y * this.z;
  1407. var xw = this.x * this.w;
  1408. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1409. result.m[1] = 2.0 * (xy + zw);
  1410. result.m[2] = 2.0 * (zx - yw);
  1411. result.m[3] = 0;
  1412. result.m[4] = 2.0 * (xy - zw);
  1413. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1414. result.m[6] = 2.0 * (yz + xw);
  1415. result.m[7] = 0;
  1416. result.m[8] = 2.0 * (zx + yw);
  1417. result.m[9] = 2.0 * (yz - xw);
  1418. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1419. result.m[11] = 0;
  1420. result.m[12] = 0;
  1421. result.m[13] = 0;
  1422. result.m[14] = 0;
  1423. result.m[15] = 1.0;
  1424. return this;
  1425. };
  1426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1427. Quaternion.FromRotationMatrixToRef(matrix, this);
  1428. return this;
  1429. };
  1430. // Statics
  1431. Quaternion.FromRotationMatrix = function (matrix) {
  1432. var result = new Quaternion();
  1433. Quaternion.FromRotationMatrixToRef(matrix, result);
  1434. return result;
  1435. };
  1436. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1437. var data = matrix.m;
  1438. var m11 = data[0], m12 = data[4], m13 = data[8];
  1439. var m21 = data[1], m22 = data[5], m23 = data[9];
  1440. var m31 = data[2], m32 = data[6], m33 = data[10];
  1441. var trace = m11 + m22 + m33;
  1442. var s;
  1443. if (trace > 0) {
  1444. s = 0.5 / Math.sqrt(trace + 1.0);
  1445. result.w = 0.25 / s;
  1446. result.x = (m32 - m23) * s;
  1447. result.y = (m13 - m31) * s;
  1448. result.z = (m21 - m12) * s;
  1449. }
  1450. else if (m11 > m22 && m11 > m33) {
  1451. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1452. result.w = (m32 - m23) / s;
  1453. result.x = 0.25 * s;
  1454. result.y = (m12 + m21) / s;
  1455. result.z = (m13 + m31) / s;
  1456. }
  1457. else if (m22 > m33) {
  1458. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1459. result.w = (m13 - m31) / s;
  1460. result.x = (m12 + m21) / s;
  1461. result.y = 0.25 * s;
  1462. result.z = (m23 + m32) / s;
  1463. }
  1464. else {
  1465. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1466. result.w = (m21 - m12) / s;
  1467. result.x = (m13 + m31) / s;
  1468. result.y = (m23 + m32) / s;
  1469. result.z = 0.25 * s;
  1470. }
  1471. };
  1472. Quaternion.Inverse = function (q) {
  1473. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1474. };
  1475. Quaternion.Identity = function () {
  1476. return new Quaternion(0, 0, 0, 1);
  1477. };
  1478. Quaternion.RotationAxis = function (axis, angle) {
  1479. var result = new Quaternion();
  1480. var sin = Math.sin(angle / 2);
  1481. axis.normalize();
  1482. result.w = Math.cos(angle / 2);
  1483. result.x = axis.x * sin;
  1484. result.y = axis.y * sin;
  1485. result.z = axis.z * sin;
  1486. return result;
  1487. };
  1488. Quaternion.FromArray = function (array, offset) {
  1489. if (!offset) {
  1490. offset = 0;
  1491. }
  1492. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1493. };
  1494. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1495. var result = new Quaternion();
  1496. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1497. return result;
  1498. };
  1499. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1500. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1501. var halfRoll = roll * 0.5;
  1502. var halfPitch = pitch * 0.5;
  1503. var halfYaw = yaw * 0.5;
  1504. var sinRoll = Math.sin(halfRoll);
  1505. var cosRoll = Math.cos(halfRoll);
  1506. var sinPitch = Math.sin(halfPitch);
  1507. var cosPitch = Math.cos(halfPitch);
  1508. var sinYaw = Math.sin(halfYaw);
  1509. var cosYaw = Math.cos(halfYaw);
  1510. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1511. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1512. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1513. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1514. };
  1515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1516. var result = new Quaternion();
  1517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1518. return result;
  1519. };
  1520. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1521. // Produces a quaternion from Euler angles in the z-x-z orientation
  1522. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1523. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1524. var halfBeta = beta * 0.5;
  1525. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1526. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1527. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1528. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1529. };
  1530. Quaternion.Slerp = function (left, right, amount) {
  1531. var num2;
  1532. var num3;
  1533. var num = amount;
  1534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1535. var flag = false;
  1536. if (num4 < 0) {
  1537. flag = true;
  1538. num4 = -num4;
  1539. }
  1540. if (num4 > 0.999999) {
  1541. num3 = 1 - num;
  1542. num2 = flag ? -num : num;
  1543. }
  1544. else {
  1545. var num5 = Math.acos(num4);
  1546. var num6 = (1.0 / Math.sin(num5));
  1547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1549. }
  1550. 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));
  1551. };
  1552. return Quaternion;
  1553. }());
  1554. BABYLON.Quaternion = Quaternion;
  1555. var Matrix = (function () {
  1556. function Matrix() {
  1557. this.m = new Float32Array(16);
  1558. }
  1559. // Properties
  1560. Matrix.prototype.isIdentity = function () {
  1561. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1562. return false;
  1563. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1564. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1565. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1566. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1567. return false;
  1568. return true;
  1569. };
  1570. Matrix.prototype.determinant = function () {
  1571. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1572. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1573. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1574. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1575. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1576. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1577. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1578. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1579. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1580. };
  1581. // Methods
  1582. Matrix.prototype.toArray = function () {
  1583. return this.m;
  1584. };
  1585. Matrix.prototype.asArray = function () {
  1586. return this.toArray();
  1587. };
  1588. Matrix.prototype.invert = function () {
  1589. this.invertToRef(this);
  1590. return this;
  1591. };
  1592. Matrix.prototype.reset = function () {
  1593. for (var index = 0; index < 16; index++) {
  1594. this.m[index] = 0;
  1595. }
  1596. return this;
  1597. };
  1598. Matrix.prototype.add = function (other) {
  1599. var result = new Matrix();
  1600. this.addToRef(other, result);
  1601. return result;
  1602. };
  1603. Matrix.prototype.addToRef = function (other, result) {
  1604. for (var index = 0; index < 16; index++) {
  1605. result.m[index] = this.m[index] + other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.addToSelf = function (other) {
  1610. for (var index = 0; index < 16; index++) {
  1611. this.m[index] += other.m[index];
  1612. }
  1613. return this;
  1614. };
  1615. Matrix.prototype.invertToRef = function (other) {
  1616. var l1 = this.m[0];
  1617. var l2 = this.m[1];
  1618. var l3 = this.m[2];
  1619. var l4 = this.m[3];
  1620. var l5 = this.m[4];
  1621. var l6 = this.m[5];
  1622. var l7 = this.m[6];
  1623. var l8 = this.m[7];
  1624. var l9 = this.m[8];
  1625. var l10 = this.m[9];
  1626. var l11 = this.m[10];
  1627. var l12 = this.m[11];
  1628. var l13 = this.m[12];
  1629. var l14 = this.m[13];
  1630. var l15 = this.m[14];
  1631. var l16 = this.m[15];
  1632. var l17 = (l11 * l16) - (l12 * l15);
  1633. var l18 = (l10 * l16) - (l12 * l14);
  1634. var l19 = (l10 * l15) - (l11 * l14);
  1635. var l20 = (l9 * l16) - (l12 * l13);
  1636. var l21 = (l9 * l15) - (l11 * l13);
  1637. var l22 = (l9 * l14) - (l10 * l13);
  1638. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1639. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1640. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1641. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1642. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1643. var l28 = (l7 * l16) - (l8 * l15);
  1644. var l29 = (l6 * l16) - (l8 * l14);
  1645. var l30 = (l6 * l15) - (l7 * l14);
  1646. var l31 = (l5 * l16) - (l8 * l13);
  1647. var l32 = (l5 * l15) - (l7 * l13);
  1648. var l33 = (l5 * l14) - (l6 * l13);
  1649. var l34 = (l7 * l12) - (l8 * l11);
  1650. var l35 = (l6 * l12) - (l8 * l10);
  1651. var l36 = (l6 * l11) - (l7 * l10);
  1652. var l37 = (l5 * l12) - (l8 * l9);
  1653. var l38 = (l5 * l11) - (l7 * l9);
  1654. var l39 = (l5 * l10) - (l6 * l9);
  1655. other.m[0] = l23 * l27;
  1656. other.m[4] = l24 * l27;
  1657. other.m[8] = l25 * l27;
  1658. other.m[12] = l26 * l27;
  1659. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1660. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1661. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1662. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1663. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1664. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1665. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1666. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1667. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1668. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1669. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1670. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1671. return this;
  1672. };
  1673. Matrix.prototype.setTranslation = function (vector3) {
  1674. this.m[12] = vector3.x;
  1675. this.m[13] = vector3.y;
  1676. this.m[14] = vector3.z;
  1677. return this;
  1678. };
  1679. Matrix.prototype.multiply = function (other) {
  1680. var result = new Matrix();
  1681. this.multiplyToRef(other, result);
  1682. return result;
  1683. };
  1684. Matrix.prototype.copyFrom = function (other) {
  1685. for (var index = 0; index < 16; index++) {
  1686. this.m[index] = other.m[index];
  1687. }
  1688. return this;
  1689. };
  1690. Matrix.prototype.copyToArray = function (array, offset) {
  1691. if (offset === void 0) { offset = 0; }
  1692. for (var index = 0; index < 16; index++) {
  1693. array[offset + index] = this.m[index];
  1694. }
  1695. return this;
  1696. };
  1697. Matrix.prototype.multiplyToRef = function (other, result) {
  1698. this.multiplyToArray(other, result.m, 0);
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1702. var tm0 = this.m[0];
  1703. var tm1 = this.m[1];
  1704. var tm2 = this.m[2];
  1705. var tm3 = this.m[3];
  1706. var tm4 = this.m[4];
  1707. var tm5 = this.m[5];
  1708. var tm6 = this.m[6];
  1709. var tm7 = this.m[7];
  1710. var tm8 = this.m[8];
  1711. var tm9 = this.m[9];
  1712. var tm10 = this.m[10];
  1713. var tm11 = this.m[11];
  1714. var tm12 = this.m[12];
  1715. var tm13 = this.m[13];
  1716. var tm14 = this.m[14];
  1717. var tm15 = this.m[15];
  1718. var om0 = other.m[0];
  1719. var om1 = other.m[1];
  1720. var om2 = other.m[2];
  1721. var om3 = other.m[3];
  1722. var om4 = other.m[4];
  1723. var om5 = other.m[5];
  1724. var om6 = other.m[6];
  1725. var om7 = other.m[7];
  1726. var om8 = other.m[8];
  1727. var om9 = other.m[9];
  1728. var om10 = other.m[10];
  1729. var om11 = other.m[11];
  1730. var om12 = other.m[12];
  1731. var om13 = other.m[13];
  1732. var om14 = other.m[14];
  1733. var om15 = other.m[15];
  1734. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1735. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1736. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1737. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1738. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1739. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1740. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1741. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1742. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1743. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1744. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1745. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1746. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1747. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1748. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1749. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1750. return this;
  1751. };
  1752. Matrix.prototype.equals = function (value) {
  1753. return value &&
  1754. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1755. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1756. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1757. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1758. };
  1759. Matrix.prototype.clone = function () {
  1760. 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]);
  1761. };
  1762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1763. translation.x = this.m[12];
  1764. translation.y = this.m[13];
  1765. translation.z = this.m[14];
  1766. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1767. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1768. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1769. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1770. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1771. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1772. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1773. rotation.x = 0;
  1774. rotation.y = 0;
  1775. rotation.z = 0;
  1776. rotation.w = 1;
  1777. return false;
  1778. }
  1779. 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);
  1780. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1781. return true;
  1782. };
  1783. // Statics
  1784. Matrix.FromArray = function (array, offset) {
  1785. var result = new Matrix();
  1786. if (!offset) {
  1787. offset = 0;
  1788. }
  1789. Matrix.FromArrayToRef(array, offset, result);
  1790. return result;
  1791. };
  1792. Matrix.FromArrayToRef = function (array, offset, result) {
  1793. for (var index = 0; index < 16; index++) {
  1794. result.m[index] = array[index + offset];
  1795. }
  1796. };
  1797. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = array[index + offset] * scale;
  1800. }
  1801. };
  1802. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1803. result.m[0] = initialM11;
  1804. result.m[1] = initialM12;
  1805. result.m[2] = initialM13;
  1806. result.m[3] = initialM14;
  1807. result.m[4] = initialM21;
  1808. result.m[5] = initialM22;
  1809. result.m[6] = initialM23;
  1810. result.m[7] = initialM24;
  1811. result.m[8] = initialM31;
  1812. result.m[9] = initialM32;
  1813. result.m[10] = initialM33;
  1814. result.m[11] = initialM34;
  1815. result.m[12] = initialM41;
  1816. result.m[13] = initialM42;
  1817. result.m[14] = initialM43;
  1818. result.m[15] = initialM44;
  1819. };
  1820. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1821. var result = new Matrix();
  1822. result.m[0] = initialM11;
  1823. result.m[1] = initialM12;
  1824. result.m[2] = initialM13;
  1825. result.m[3] = initialM14;
  1826. result.m[4] = initialM21;
  1827. result.m[5] = initialM22;
  1828. result.m[6] = initialM23;
  1829. result.m[7] = initialM24;
  1830. result.m[8] = initialM31;
  1831. result.m[9] = initialM32;
  1832. result.m[10] = initialM33;
  1833. result.m[11] = initialM34;
  1834. result.m[12] = initialM41;
  1835. result.m[13] = initialM42;
  1836. result.m[14] = initialM43;
  1837. result.m[15] = initialM44;
  1838. return result;
  1839. };
  1840. Matrix.Compose = function (scale, rotation, translation) {
  1841. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1842. var rotationMatrix = Matrix.Identity();
  1843. rotation.toRotationMatrix(rotationMatrix);
  1844. result = result.multiply(rotationMatrix);
  1845. result.setTranslation(translation);
  1846. return result;
  1847. };
  1848. Matrix.Identity = function () {
  1849. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1850. };
  1851. Matrix.IdentityToRef = function (result) {
  1852. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1853. };
  1854. Matrix.Zero = function () {
  1855. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1856. };
  1857. Matrix.RotationX = function (angle) {
  1858. var result = new Matrix();
  1859. Matrix.RotationXToRef(angle, result);
  1860. return result;
  1861. };
  1862. Matrix.Invert = function (source) {
  1863. var result = new Matrix();
  1864. source.invertToRef(result);
  1865. return result;
  1866. };
  1867. Matrix.RotationXToRef = function (angle, result) {
  1868. var s = Math.sin(angle);
  1869. var c = Math.cos(angle);
  1870. result.m[0] = 1.0;
  1871. result.m[15] = 1.0;
  1872. result.m[5] = c;
  1873. result.m[10] = c;
  1874. result.m[9] = -s;
  1875. result.m[6] = s;
  1876. result.m[1] = 0;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[4] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[11] = 0;
  1883. result.m[12] = 0;
  1884. result.m[13] = 0;
  1885. result.m[14] = 0;
  1886. };
  1887. Matrix.RotationY = function (angle) {
  1888. var result = new Matrix();
  1889. Matrix.RotationYToRef(angle, result);
  1890. return result;
  1891. };
  1892. Matrix.RotationYToRef = function (angle, result) {
  1893. var s = Math.sin(angle);
  1894. var c = Math.cos(angle);
  1895. result.m[5] = 1.0;
  1896. result.m[15] = 1.0;
  1897. result.m[0] = c;
  1898. result.m[2] = -s;
  1899. result.m[8] = s;
  1900. result.m[10] = c;
  1901. result.m[1] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[6] = 0;
  1905. result.m[7] = 0;
  1906. result.m[9] = 0;
  1907. result.m[11] = 0;
  1908. result.m[12] = 0;
  1909. result.m[13] = 0;
  1910. result.m[14] = 0;
  1911. };
  1912. Matrix.RotationZ = function (angle) {
  1913. var result = new Matrix();
  1914. Matrix.RotationZToRef(angle, result);
  1915. return result;
  1916. };
  1917. Matrix.RotationZToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[10] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[0] = c;
  1923. result.m[1] = s;
  1924. result.m[4] = -s;
  1925. result.m[5] = c;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationAxis = function (axis, angle) {
  1938. var result = Matrix.Zero();
  1939. Matrix.RotationAxisToRef(axis, angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1943. var s = Math.sin(-angle);
  1944. var c = Math.cos(-angle);
  1945. var c1 = 1 - c;
  1946. axis.normalize();
  1947. result.m[0] = (axis.x * axis.x) * c1 + c;
  1948. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1949. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1950. result.m[3] = 0.0;
  1951. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1952. result.m[5] = (axis.y * axis.y) * c1 + c;
  1953. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1954. result.m[7] = 0.0;
  1955. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1956. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1957. result.m[10] = (axis.z * axis.z) * c1 + c;
  1958. result.m[11] = 0.0;
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1962. var result = new Matrix();
  1963. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1967. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1968. this._tempQuaternion.toRotationMatrix(result);
  1969. };
  1970. Matrix.Scaling = function (x, y, z) {
  1971. var result = Matrix.Zero();
  1972. Matrix.ScalingToRef(x, y, z, result);
  1973. return result;
  1974. };
  1975. Matrix.ScalingToRef = function (x, y, z, result) {
  1976. result.m[0] = x;
  1977. result.m[1] = 0;
  1978. result.m[2] = 0;
  1979. result.m[3] = 0;
  1980. result.m[4] = 0;
  1981. result.m[5] = y;
  1982. result.m[6] = 0;
  1983. result.m[7] = 0;
  1984. result.m[8] = 0;
  1985. result.m[9] = 0;
  1986. result.m[10] = z;
  1987. result.m[11] = 0;
  1988. result.m[12] = 0;
  1989. result.m[13] = 0;
  1990. result.m[14] = 0;
  1991. result.m[15] = 1.0;
  1992. };
  1993. Matrix.Translation = function (x, y, z) {
  1994. var result = Matrix.Identity();
  1995. Matrix.TranslationToRef(x, y, z, result);
  1996. return result;
  1997. };
  1998. Matrix.TranslationToRef = function (x, y, z, result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2000. };
  2001. Matrix.Lerp = function (startValue, endValue, gradient) {
  2002. var startScale = new Vector3(0, 0, 0);
  2003. var startRotation = new Quaternion();
  2004. var startTranslation = new Vector3(0, 0, 0);
  2005. startValue.decompose(startScale, startRotation, startTranslation);
  2006. var endScale = new Vector3(0, 0, 0);
  2007. var endRotation = new Quaternion();
  2008. var endTranslation = new Vector3(0, 0, 0);
  2009. endValue.decompose(endScale, endRotation, endTranslation);
  2010. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2011. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2012. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2013. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2014. };
  2015. Matrix.LookAtLH = function (eye, target, up) {
  2016. var result = Matrix.Zero();
  2017. Matrix.LookAtLHToRef(eye, target, up, result);
  2018. return result;
  2019. };
  2020. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2021. // Z axis
  2022. target.subtractToRef(eye, this._zAxis);
  2023. this._zAxis.normalize();
  2024. // X axis
  2025. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2026. if (this._xAxis.lengthSquared() === 0) {
  2027. this._xAxis.x = 1.0;
  2028. }
  2029. else {
  2030. this._xAxis.normalize();
  2031. }
  2032. // Y axis
  2033. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2034. this._yAxis.normalize();
  2035. // Eye angles
  2036. var ex = -Vector3.Dot(this._xAxis, eye);
  2037. var ey = -Vector3.Dot(this._yAxis, eye);
  2038. var ez = -Vector3.Dot(this._zAxis, eye);
  2039. 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);
  2040. };
  2041. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2047. var hw = 2.0 / width;
  2048. var hh = 2.0 / height;
  2049. var id = 1.0 / (zfar - znear);
  2050. var nid = znear / (znear - zfar);
  2051. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2052. };
  2053. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2054. var matrix = Matrix.Zero();
  2055. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2056. return matrix;
  2057. };
  2058. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2059. result.m[0] = 2.0 / (right - left);
  2060. result.m[1] = result.m[2] = result.m[3] = 0;
  2061. result.m[5] = 2.0 / (top - bottom);
  2062. result.m[4] = result.m[6] = result.m[7] = 0;
  2063. result.m[10] = -1.0 / (znear - zfar);
  2064. result.m[8] = result.m[9] = result.m[11] = 0;
  2065. result.m[12] = (left + right) / (left - right);
  2066. result.m[13] = (top + bottom) / (bottom - top);
  2067. result.m[14] = znear / (znear - zfar);
  2068. result.m[15] = 1.0;
  2069. };
  2070. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2071. var matrix = Matrix.Zero();
  2072. matrix.m[0] = (2.0 * znear) / width;
  2073. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2074. matrix.m[5] = (2.0 * znear) / height;
  2075. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2076. matrix.m[10] = -zfar / (znear - zfar);
  2077. matrix.m[8] = matrix.m[9] = 0.0;
  2078. matrix.m[11] = 1.0;
  2079. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2080. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2081. return matrix;
  2082. };
  2083. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2084. var matrix = Matrix.Zero();
  2085. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2086. return matrix;
  2087. };
  2088. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2089. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2090. var tan = 1.0 / (Math.tan(fov * 0.5));
  2091. if (isVerticalFovFixed) {
  2092. result.m[0] = tan / aspect;
  2093. }
  2094. else {
  2095. result.m[0] = tan;
  2096. }
  2097. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2098. if (isVerticalFovFixed) {
  2099. result.m[5] = tan;
  2100. }
  2101. else {
  2102. result.m[5] = tan * aspect;
  2103. }
  2104. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2105. result.m[8] = result.m[9] = 0.0;
  2106. result.m[10] = -zfar / (znear - zfar);
  2107. result.m[11] = 1.0;
  2108. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2109. result.m[14] = (znear * zfar) / (znear - zfar);
  2110. };
  2111. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2112. var cw = viewport.width;
  2113. var ch = viewport.height;
  2114. var cx = viewport.x;
  2115. var cy = viewport.y;
  2116. 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);
  2117. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2118. };
  2119. Matrix.GetAsMatrix2x2 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1],
  2122. matrix.m[4], matrix.m[5]
  2123. ]);
  2124. };
  2125. Matrix.GetAsMatrix3x3 = function (matrix) {
  2126. return new Float32Array([
  2127. matrix.m[0], matrix.m[1], matrix.m[2],
  2128. matrix.m[4], matrix.m[5], matrix.m[6],
  2129. matrix.m[8], matrix.m[9], matrix.m[10]
  2130. ]);
  2131. };
  2132. Matrix.Transpose = function (matrix) {
  2133. var result = new Matrix();
  2134. result.m[0] = matrix.m[0];
  2135. result.m[1] = matrix.m[4];
  2136. result.m[2] = matrix.m[8];
  2137. result.m[3] = matrix.m[12];
  2138. result.m[4] = matrix.m[1];
  2139. result.m[5] = matrix.m[5];
  2140. result.m[6] = matrix.m[9];
  2141. result.m[7] = matrix.m[13];
  2142. result.m[8] = matrix.m[2];
  2143. result.m[9] = matrix.m[6];
  2144. result.m[10] = matrix.m[10];
  2145. result.m[11] = matrix.m[14];
  2146. result.m[12] = matrix.m[3];
  2147. result.m[13] = matrix.m[7];
  2148. result.m[14] = matrix.m[11];
  2149. result.m[15] = matrix.m[15];
  2150. return result;
  2151. };
  2152. Matrix.Reflection = function (plane) {
  2153. var matrix = new Matrix();
  2154. Matrix.ReflectionToRef(plane, matrix);
  2155. return matrix;
  2156. };
  2157. Matrix.ReflectionToRef = function (plane, result) {
  2158. plane.normalize();
  2159. var x = plane.normal.x;
  2160. var y = plane.normal.y;
  2161. var z = plane.normal.z;
  2162. var temp = -2 * x;
  2163. var temp2 = -2 * y;
  2164. var temp3 = -2 * z;
  2165. result.m[0] = (temp * x) + 1;
  2166. result.m[1] = temp2 * x;
  2167. result.m[2] = temp3 * x;
  2168. result.m[3] = 0.0;
  2169. result.m[4] = temp * y;
  2170. result.m[5] = (temp2 * y) + 1;
  2171. result.m[6] = temp3 * y;
  2172. result.m[7] = 0.0;
  2173. result.m[8] = temp * z;
  2174. result.m[9] = temp2 * z;
  2175. result.m[10] = (temp3 * z) + 1;
  2176. result.m[11] = 0.0;
  2177. result.m[12] = temp * plane.d;
  2178. result.m[13] = temp2 * plane.d;
  2179. result.m[14] = temp3 * plane.d;
  2180. result.m[15] = 1.0;
  2181. };
  2182. Matrix._tempQuaternion = new Quaternion();
  2183. Matrix._xAxis = Vector3.Zero();
  2184. Matrix._yAxis = Vector3.Zero();
  2185. Matrix._zAxis = Vector3.Zero();
  2186. return Matrix;
  2187. }());
  2188. BABYLON.Matrix = Matrix;
  2189. var Plane = (function () {
  2190. function Plane(a, b, c, d) {
  2191. this.normal = new Vector3(a, b, c);
  2192. this.d = d;
  2193. }
  2194. Plane.prototype.asArray = function () {
  2195. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2196. };
  2197. // Methods
  2198. Plane.prototype.clone = function () {
  2199. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2200. };
  2201. Plane.prototype.normalize = function () {
  2202. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2203. var magnitude = 0;
  2204. if (norm !== 0) {
  2205. magnitude = 1.0 / norm;
  2206. }
  2207. this.normal.x *= magnitude;
  2208. this.normal.y *= magnitude;
  2209. this.normal.z *= magnitude;
  2210. this.d *= magnitude;
  2211. return this;
  2212. };
  2213. Plane.prototype.transform = function (transformation) {
  2214. var transposedMatrix = Matrix.Transpose(transformation);
  2215. var x = this.normal.x;
  2216. var y = this.normal.y;
  2217. var z = this.normal.z;
  2218. var d = this.d;
  2219. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2220. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2221. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2222. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2223. return new Plane(normalX, normalY, normalZ, finalD);
  2224. };
  2225. Plane.prototype.dotCoordinate = function (point) {
  2226. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2227. };
  2228. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2229. var x1 = point2.x - point1.x;
  2230. var y1 = point2.y - point1.y;
  2231. var z1 = point2.z - point1.z;
  2232. var x2 = point3.x - point1.x;
  2233. var y2 = point3.y - point1.y;
  2234. var z2 = point3.z - point1.z;
  2235. var yz = (y1 * z2) - (z1 * y2);
  2236. var xz = (z1 * x2) - (x1 * z2);
  2237. var xy = (x1 * y2) - (y1 * x2);
  2238. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2239. var invPyth;
  2240. if (pyth !== 0) {
  2241. invPyth = 1.0 / pyth;
  2242. }
  2243. else {
  2244. invPyth = 0;
  2245. }
  2246. this.normal.x = yz * invPyth;
  2247. this.normal.y = xz * invPyth;
  2248. this.normal.z = xy * invPyth;
  2249. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2250. return this;
  2251. };
  2252. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2253. var dot = Vector3.Dot(this.normal, direction);
  2254. return (dot <= epsilon);
  2255. };
  2256. Plane.prototype.signedDistanceTo = function (point) {
  2257. return Vector3.Dot(point, this.normal) + this.d;
  2258. };
  2259. // Statics
  2260. Plane.FromArray = function (array) {
  2261. return new Plane(array[0], array[1], array[2], array[3]);
  2262. };
  2263. Plane.FromPoints = function (point1, point2, point3) {
  2264. var result = new Plane(0, 0, 0, 0);
  2265. result.copyFromPoints(point1, point2, point3);
  2266. return result;
  2267. };
  2268. Plane.FromPositionAndNormal = function (origin, normal) {
  2269. var result = new Plane(0, 0, 0, 0);
  2270. normal.normalize();
  2271. result.normal = normal;
  2272. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2273. return result;
  2274. };
  2275. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2276. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2277. return Vector3.Dot(point, normal) + d;
  2278. };
  2279. return Plane;
  2280. }());
  2281. BABYLON.Plane = Plane;
  2282. var Viewport = (function () {
  2283. function Viewport(x, y, width, height) {
  2284. this.x = x;
  2285. this.y = y;
  2286. this.width = width;
  2287. this.height = height;
  2288. }
  2289. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2291. };
  2292. return Viewport;
  2293. }());
  2294. BABYLON.Viewport = Viewport;
  2295. var Frustum = (function () {
  2296. function Frustum() {
  2297. }
  2298. Frustum.GetPlanes = function (transform) {
  2299. var frustumPlanes = [];
  2300. for (var index = 0; index < 6; index++) {
  2301. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2302. }
  2303. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2304. return frustumPlanes;
  2305. };
  2306. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2307. // Near
  2308. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2309. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2310. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2311. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2312. frustumPlanes[0].normalize();
  2313. // Far
  2314. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2315. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2316. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2317. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2318. frustumPlanes[1].normalize();
  2319. // Left
  2320. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2321. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2322. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2323. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2324. frustumPlanes[2].normalize();
  2325. // Right
  2326. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2327. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2328. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2329. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2330. frustumPlanes[3].normalize();
  2331. // Top
  2332. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2333. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2334. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2335. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2336. frustumPlanes[4].normalize();
  2337. // Bottom
  2338. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2339. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2340. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2341. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2342. frustumPlanes[5].normalize();
  2343. };
  2344. return Frustum;
  2345. }());
  2346. BABYLON.Frustum = Frustum;
  2347. (function (Space) {
  2348. Space[Space["LOCAL"] = 0] = "LOCAL";
  2349. Space[Space["WORLD"] = 1] = "WORLD";
  2350. })(BABYLON.Space || (BABYLON.Space = {}));
  2351. var Space = BABYLON.Space;
  2352. var Axis = (function () {
  2353. function Axis() {
  2354. }
  2355. Axis.X = new Vector3(1, 0, 0);
  2356. Axis.Y = new Vector3(0, 1, 0);
  2357. Axis.Z = new Vector3(0, 0, 1);
  2358. return Axis;
  2359. }());
  2360. BABYLON.Axis = Axis;
  2361. ;
  2362. var BezierCurve = (function () {
  2363. function BezierCurve() {
  2364. }
  2365. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2366. // Extract X (which is equal to time here)
  2367. var f0 = 1 - 3 * x2 + 3 * x1;
  2368. var f1 = 3 * x2 - 6 * x1;
  2369. var f2 = 3 * x1;
  2370. var refinedT = t;
  2371. for (var i = 0; i < 5; i++) {
  2372. var refinedT2 = refinedT * refinedT;
  2373. var refinedT3 = refinedT2 * refinedT;
  2374. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2375. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2376. refinedT -= (x - t) * slope;
  2377. refinedT = Math.min(1, Math.max(0, refinedT));
  2378. }
  2379. // Resolve cubic bezier for the given x
  2380. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2381. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2382. Math.pow(refinedT, 3);
  2383. };
  2384. return BezierCurve;
  2385. }());
  2386. BABYLON.BezierCurve = BezierCurve;
  2387. (function (Orientation) {
  2388. Orientation[Orientation["CW"] = 0] = "CW";
  2389. Orientation[Orientation["CCW"] = 1] = "CCW";
  2390. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2391. var Orientation = BABYLON.Orientation;
  2392. var Angle = (function () {
  2393. function Angle(radians) {
  2394. var _this = this;
  2395. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2396. this.radians = function () { return _this._radians; };
  2397. this._radians = radians;
  2398. if (this._radians < 0)
  2399. this._radians += (2 * Math.PI);
  2400. }
  2401. Angle.BetweenTwoPoints = function (a, b) {
  2402. var delta = b.subtract(a);
  2403. var theta = Math.atan2(delta.y, delta.x);
  2404. return new Angle(theta);
  2405. };
  2406. Angle.FromRadians = function (radians) {
  2407. return new Angle(radians);
  2408. };
  2409. Angle.FromDegrees = function (degrees) {
  2410. return new Angle(degrees * Math.PI / 180);
  2411. };
  2412. return Angle;
  2413. }());
  2414. BABYLON.Angle = Angle;
  2415. var Arc2 = (function () {
  2416. function Arc2(startPoint, midPoint, endPoint) {
  2417. this.startPoint = startPoint;
  2418. this.midPoint = midPoint;
  2419. this.endPoint = endPoint;
  2420. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2421. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2422. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2423. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2424. 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);
  2425. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2426. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2427. var a1 = this.startAngle.degrees();
  2428. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2429. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2430. // angles correction
  2431. if (a2 - a1 > +180.0)
  2432. a2 -= 360.0;
  2433. if (a2 - a1 < -180.0)
  2434. a2 += 360.0;
  2435. if (a3 - a2 > +180.0)
  2436. a3 -= 360.0;
  2437. if (a3 - a2 < -180.0)
  2438. a3 += 360.0;
  2439. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2440. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2441. }
  2442. return Arc2;
  2443. }());
  2444. BABYLON.Arc2 = Arc2;
  2445. var Path2 = (function () {
  2446. function Path2(x, y) {
  2447. this._points = new Array();
  2448. this._length = 0;
  2449. this.closed = false;
  2450. this._points.push(new Vector2(x, y));
  2451. }
  2452. Path2.prototype.addLineTo = function (x, y) {
  2453. if (closed) {
  2454. //Tools.Error("cannot add lines to closed paths");
  2455. return this;
  2456. }
  2457. var newPoint = new Vector2(x, y);
  2458. var previousPoint = this._points[this._points.length - 1];
  2459. this._points.push(newPoint);
  2460. this._length += newPoint.subtract(previousPoint).length();
  2461. return this;
  2462. };
  2463. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2464. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2465. if (closed) {
  2466. //Tools.Error("cannot add arcs to closed paths");
  2467. return this;
  2468. }
  2469. var startPoint = this._points[this._points.length - 1];
  2470. var midPoint = new Vector2(midX, midY);
  2471. var endPoint = new Vector2(endX, endY);
  2472. var arc = new Arc2(startPoint, midPoint, endPoint);
  2473. var increment = arc.angle.radians() / numberOfSegments;
  2474. if (arc.orientation === Orientation.CW)
  2475. increment *= -1;
  2476. var currentAngle = arc.startAngle.radians() + increment;
  2477. for (var i = 0; i < numberOfSegments; i++) {
  2478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2480. this.addLineTo(x, y);
  2481. currentAngle += increment;
  2482. }
  2483. return this;
  2484. };
  2485. Path2.prototype.close = function () {
  2486. this.closed = true;
  2487. return this;
  2488. };
  2489. Path2.prototype.length = function () {
  2490. var result = this._length;
  2491. if (!this.closed) {
  2492. var lastPoint = this._points[this._points.length - 1];
  2493. var firstPoint = this._points[0];
  2494. result += (firstPoint.subtract(lastPoint).length());
  2495. }
  2496. return result;
  2497. };
  2498. Path2.prototype.getPoints = function () {
  2499. return this._points;
  2500. };
  2501. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2502. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2503. //Tools.Error("normalized length position should be between 0 and 1.");
  2504. return Vector2.Zero();
  2505. }
  2506. var lengthPosition = normalizedLengthPosition * this.length();
  2507. var previousOffset = 0;
  2508. for (var i = 0; i < this._points.length; i++) {
  2509. var j = (i + 1) % this._points.length;
  2510. var a = this._points[i];
  2511. var b = this._points[j];
  2512. var bToA = b.subtract(a);
  2513. var nextOffset = (bToA.length() + previousOffset);
  2514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2515. var dir = bToA.normalize();
  2516. var localOffset = lengthPosition - previousOffset;
  2517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2518. }
  2519. previousOffset = nextOffset;
  2520. }
  2521. //Tools.Error("internal error");
  2522. return Vector2.Zero();
  2523. };
  2524. Path2.StartingAt = function (x, y) {
  2525. return new Path2(x, y);
  2526. };
  2527. return Path2;
  2528. }());
  2529. BABYLON.Path2 = Path2;
  2530. var Path3D = (function () {
  2531. /**
  2532. * new Path3D(path, normal, raw)
  2533. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2534. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2535. * path : an array of Vector3, the curve axis of the Path3D
  2536. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2537. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2538. */
  2539. function Path3D(path, firstNormal, raw) {
  2540. this.path = path;
  2541. this._curve = new Array();
  2542. this._distances = new Array();
  2543. this._tangents = new Array();
  2544. this._normals = new Array();
  2545. this._binormals = new Array();
  2546. for (var p = 0; p < path.length; p++) {
  2547. this._curve[p] = path[p].clone(); // hard copy
  2548. }
  2549. this._raw = raw || false;
  2550. this._compute(firstNormal);
  2551. }
  2552. /**
  2553. * Returns the Path3D array of successive Vector3 designing its curve.
  2554. */
  2555. Path3D.prototype.getCurve = function () {
  2556. return this._curve;
  2557. };
  2558. /**
  2559. * Returns an array populated with tangent vectors on each Path3D curve point.
  2560. */
  2561. Path3D.prototype.getTangents = function () {
  2562. return this._tangents;
  2563. };
  2564. /**
  2565. * Returns an array populated with normal vectors on each Path3D curve point.
  2566. */
  2567. Path3D.prototype.getNormals = function () {
  2568. return this._normals;
  2569. };
  2570. /**
  2571. * Returns an array populated with binormal vectors on each Path3D curve point.
  2572. */
  2573. Path3D.prototype.getBinormals = function () {
  2574. return this._binormals;
  2575. };
  2576. /**
  2577. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2578. */
  2579. Path3D.prototype.getDistances = function () {
  2580. return this._distances;
  2581. };
  2582. /**
  2583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2584. * Returns the same object updated.
  2585. */
  2586. Path3D.prototype.update = function (path, firstNormal) {
  2587. for (var p = 0; p < path.length; p++) {
  2588. this._curve[p].x = path[p].x;
  2589. this._curve[p].y = path[p].y;
  2590. this._curve[p].z = path[p].z;
  2591. }
  2592. this._compute(firstNormal);
  2593. return this;
  2594. };
  2595. // private function compute() : computes tangents, normals and binormals
  2596. Path3D.prototype._compute = function (firstNormal) {
  2597. var l = this._curve.length;
  2598. // first and last tangents
  2599. this._tangents[0] = this._getFirstNonNullVector(0);
  2600. if (!this._raw) {
  2601. this._tangents[0].normalize();
  2602. }
  2603. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2604. if (!this._raw) {
  2605. this._tangents[l - 1].normalize();
  2606. }
  2607. // normals and binormals at first point : arbitrary vector with _normalVector()
  2608. var tg0 = this._tangents[0];
  2609. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2610. this._normals[0] = pp0;
  2611. if (!this._raw) {
  2612. this._normals[0].normalize();
  2613. }
  2614. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2615. if (!this._raw) {
  2616. this._binormals[0].normalize();
  2617. }
  2618. this._distances[0] = 0;
  2619. // normals and binormals : next points
  2620. var prev; // previous vector (segment)
  2621. var cur; // current vector (segment)
  2622. var curTang; // current tangent
  2623. // previous normal
  2624. var prevBinor; // previous binormal
  2625. for (var i = 1; i < l; i++) {
  2626. // tangents
  2627. prev = this._getLastNonNullVector(i);
  2628. if (i < l - 1) {
  2629. cur = this._getFirstNonNullVector(i);
  2630. this._tangents[i] = prev.add(cur);
  2631. this._tangents[i].normalize();
  2632. }
  2633. this._distances[i] = this._distances[i - 1] + prev.length();
  2634. // normals and binormals
  2635. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2636. curTang = this._tangents[i];
  2637. prevBinor = this._binormals[i - 1];
  2638. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2639. if (!this._raw) {
  2640. this._normals[i].normalize();
  2641. }
  2642. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2643. if (!this._raw) {
  2644. this._binormals[i].normalize();
  2645. }
  2646. }
  2647. };
  2648. // private function getFirstNonNullVector(index)
  2649. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2650. Path3D.prototype._getFirstNonNullVector = function (index) {
  2651. var i = 1;
  2652. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2653. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2654. i++;
  2655. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2656. }
  2657. return nNVector;
  2658. };
  2659. // private function getLastNonNullVector(index)
  2660. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2661. Path3D.prototype._getLastNonNullVector = function (index) {
  2662. var i = 1;
  2663. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2664. while (nLVector.length() === 0 && index > i + 1) {
  2665. i++;
  2666. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2667. }
  2668. return nLVector;
  2669. };
  2670. // private function normalVector(v0, vt, va) :
  2671. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2672. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2673. Path3D.prototype._normalVector = function (v0, vt, va) {
  2674. var normal0;
  2675. if (va === undefined || va === null) {
  2676. var point;
  2677. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2678. point = new Vector3(0, -1, 0);
  2679. }
  2680. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2681. point = new Vector3(1, 0, 0);
  2682. }
  2683. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2684. point = new Vector3(0, 0, 1);
  2685. }
  2686. normal0 = Vector3.Cross(vt, point);
  2687. }
  2688. else {
  2689. normal0 = Vector3.Cross(vt, va);
  2690. Vector3.CrossToRef(normal0, vt, normal0);
  2691. }
  2692. normal0.normalize();
  2693. return normal0;
  2694. };
  2695. return Path3D;
  2696. }());
  2697. BABYLON.Path3D = Path3D;
  2698. var Curve3 = (function () {
  2699. /**
  2700. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2701. * A Curve3 is designed from a series of successive Vector3.
  2702. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2703. */
  2704. function Curve3(points) {
  2705. this._length = 0;
  2706. this._points = points;
  2707. this._length = this._computeLength(points);
  2708. }
  2709. /**
  2710. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2711. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2712. * @param v1 (Vector3) the control point
  2713. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2714. * @param nbPoints (integer) the wanted number of points in the curve
  2715. */
  2716. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2717. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2718. var bez = new Array();
  2719. var equation = function (t, val0, val1, val2) {
  2720. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2721. return res;
  2722. };
  2723. for (var i = 0; i <= nbPoints; i++) {
  2724. 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)));
  2725. }
  2726. return new Curve3(bez);
  2727. };
  2728. /**
  2729. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2730. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2731. * @param v1 (Vector3) the first control point
  2732. * @param v2 (Vector3) the second control point
  2733. * @param v3 (Vector3) the end point of the Cubic Bezier
  2734. * @param nbPoints (integer) the wanted number of points in the curve
  2735. */
  2736. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2737. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2738. var bez = new Array();
  2739. var equation = function (t, val0, val1, val2, val3) {
  2740. 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;
  2741. return res;
  2742. };
  2743. for (var i = 0; i <= nbPoints; i++) {
  2744. 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)));
  2745. }
  2746. return new Curve3(bez);
  2747. };
  2748. /**
  2749. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2750. * @param p1 (Vector3) the origin point of the Hermite Spline
  2751. * @param t1 (Vector3) the tangent vector at the origin point
  2752. * @param p2 (Vector3) the end point of the Hermite Spline
  2753. * @param t2 (Vector3) the tangent vector at the end point
  2754. * @param nbPoints (integer) the wanted number of points in the curve
  2755. */
  2756. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2757. var hermite = new Array();
  2758. var step = 1 / nbPoints;
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2761. }
  2762. return new Curve3(hermite);
  2763. };
  2764. /**
  2765. * Returns the Curve3 stored array of successive Vector3
  2766. */
  2767. Curve3.prototype.getPoints = function () {
  2768. return this._points;
  2769. };
  2770. /**
  2771. * Returns the computed length (float) of the curve.
  2772. */
  2773. Curve3.prototype.length = function () {
  2774. return this._length;
  2775. };
  2776. /**
  2777. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2778. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2779. * curveA and curveB keep unchanged.
  2780. */
  2781. Curve3.prototype.continue = function (curve) {
  2782. var lastPoint = this._points[this._points.length - 1];
  2783. var continuedPoints = this._points.slice();
  2784. var curvePoints = curve.getPoints();
  2785. for (var i = 1; i < curvePoints.length; i++) {
  2786. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2787. }
  2788. var continuedCurve = new Curve3(continuedPoints);
  2789. return continuedCurve;
  2790. };
  2791. Curve3.prototype._computeLength = function (path) {
  2792. var l = 0;
  2793. for (var i = 1; i < path.length; i++) {
  2794. l += (path[i].subtract(path[i - 1])).length();
  2795. }
  2796. return l;
  2797. };
  2798. return Curve3;
  2799. }());
  2800. BABYLON.Curve3 = Curve3;
  2801. // SphericalHarmonics
  2802. var SphericalHarmonics = (function () {
  2803. function SphericalHarmonics() {
  2804. this.L00 = Vector3.Zero();
  2805. this.L1_1 = Vector3.Zero();
  2806. this.L10 = Vector3.Zero();
  2807. this.L11 = Vector3.Zero();
  2808. this.L2_2 = Vector3.Zero();
  2809. this.L2_1 = Vector3.Zero();
  2810. this.L20 = Vector3.Zero();
  2811. this.L21 = Vector3.Zero();
  2812. this.L22 = Vector3.Zero();
  2813. }
  2814. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2815. var colorVector = new Vector3(color.r, color.g, color.b);
  2816. var c = colorVector.scale(deltaSolidAngle);
  2817. this.L00 = this.L00.add(c.scale(0.282095));
  2818. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2819. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2820. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2821. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2822. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2823. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2824. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2825. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2826. };
  2827. SphericalHarmonics.prototype.scale = function (scale) {
  2828. this.L00 = this.L00.scale(scale);
  2829. this.L1_1 = this.L1_1.scale(scale);
  2830. this.L10 = this.L10.scale(scale);
  2831. this.L11 = this.L11.scale(scale);
  2832. this.L2_2 = this.L2_2.scale(scale);
  2833. this.L2_1 = this.L2_1.scale(scale);
  2834. this.L20 = this.L20.scale(scale);
  2835. this.L21 = this.L21.scale(scale);
  2836. this.L22 = this.L22.scale(scale);
  2837. };
  2838. return SphericalHarmonics;
  2839. }());
  2840. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2841. // SphericalPolynomial
  2842. var SphericalPolynomial = (function () {
  2843. function SphericalPolynomial() {
  2844. this.x = Vector3.Zero();
  2845. this.y = Vector3.Zero();
  2846. this.z = Vector3.Zero();
  2847. this.xx = Vector3.Zero();
  2848. this.yy = Vector3.Zero();
  2849. this.zz = Vector3.Zero();
  2850. this.xy = Vector3.Zero();
  2851. this.yz = Vector3.Zero();
  2852. this.zx = Vector3.Zero();
  2853. }
  2854. SphericalPolynomial.prototype.addAmbient = function (color) {
  2855. var colorVector = new Vector3(color.r, color.g, color.b);
  2856. this.xx = this.xx.add(colorVector);
  2857. this.yy = this.yy.add(colorVector);
  2858. this.zz = this.zz.add(colorVector);
  2859. };
  2860. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2861. var result = new SphericalPolynomial();
  2862. result.x = harmonics.L11.scale(1.02333);
  2863. result.y = harmonics.L1_1.scale(1.02333);
  2864. result.z = harmonics.L10.scale(1.02333);
  2865. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2866. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2867. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2868. result.yz = harmonics.L2_1.scale(0.858086);
  2869. result.zx = harmonics.L21.scale(0.858086);
  2870. result.xy = harmonics.L2_2.scale(0.858086);
  2871. return result;
  2872. };
  2873. return SphericalPolynomial;
  2874. }());
  2875. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2876. // Vertex formats
  2877. var PositionNormalVertex = (function () {
  2878. function PositionNormalVertex(position, normal) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. this.position = position;
  2882. this.normal = normal;
  2883. }
  2884. PositionNormalVertex.prototype.clone = function () {
  2885. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2886. };
  2887. return PositionNormalVertex;
  2888. }());
  2889. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2890. var PositionNormalTextureVertex = (function () {
  2891. function PositionNormalTextureVertex(position, normal, uv) {
  2892. if (position === void 0) { position = Vector3.Zero(); }
  2893. if (normal === void 0) { normal = Vector3.Up(); }
  2894. if (uv === void 0) { uv = Vector2.Zero(); }
  2895. this.position = position;
  2896. this.normal = normal;
  2897. this.uv = uv;
  2898. }
  2899. PositionNormalTextureVertex.prototype.clone = function () {
  2900. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2901. };
  2902. return PositionNormalTextureVertex;
  2903. }());
  2904. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2905. // Temporary pre-allocated objects for engine internal use
  2906. // usage in any internal function :
  2907. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2908. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2909. var Tmp = (function () {
  2910. function Tmp() {
  2911. }
  2912. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2913. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2914. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2915. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2916. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2917. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2918. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2919. Matrix.Zero(), Matrix.Zero(),
  2920. Matrix.Zero(), Matrix.Zero(),
  2921. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2922. return Tmp;
  2923. }());
  2924. BABYLON.Tmp = Tmp;
  2925. })(BABYLON || (BABYLON = {}));
  2926. var BABYLON;
  2927. (function (BABYLON) {
  2928. function generateSerializableMember(type, sourceName) {
  2929. return function (target, propertyKey) {
  2930. if (!target.__serializableMembers) {
  2931. target.__serializableMembers = {};
  2932. }
  2933. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2934. };
  2935. }
  2936. function serialize(sourceName) {
  2937. return generateSerializableMember(0, sourceName); // value member
  2938. }
  2939. BABYLON.serialize = serialize;
  2940. function serializeAsTexture(sourceName) {
  2941. return generateSerializableMember(1, sourceName); // texture member
  2942. }
  2943. BABYLON.serializeAsTexture = serializeAsTexture;
  2944. function serializeAsColor3(sourceName) {
  2945. return generateSerializableMember(2, sourceName); // color3 member
  2946. }
  2947. BABYLON.serializeAsColor3 = serializeAsColor3;
  2948. function serializeAsFresnelParameters(sourceName) {
  2949. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2950. }
  2951. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2952. function serializeAsVector2(sourceName) {
  2953. return generateSerializableMember(4, sourceName); // vector2 member
  2954. }
  2955. BABYLON.serializeAsVector2 = serializeAsVector2;
  2956. function serializeAsVector3(sourceName) {
  2957. return generateSerializableMember(5, sourceName); // vector3 member
  2958. }
  2959. BABYLON.serializeAsVector3 = serializeAsVector3;
  2960. function serializeAsMeshReference(sourceName) {
  2961. return generateSerializableMember(6, sourceName); // mesh reference member
  2962. }
  2963. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2964. var SerializationHelper = (function () {
  2965. function SerializationHelper() {
  2966. }
  2967. SerializationHelper.Serialize = function (entity, serializationObject) {
  2968. if (!serializationObject) {
  2969. serializationObject = {};
  2970. }
  2971. // Tags
  2972. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2973. // Properties
  2974. for (var property in entity.__serializableMembers) {
  2975. var propertyDescriptor = entity.__serializableMembers[property];
  2976. var targetPropertyName = propertyDescriptor.sourceName || property;
  2977. var propertyType = propertyDescriptor.type;
  2978. var sourceProperty = entity[property];
  2979. if (sourceProperty !== undefined && sourceProperty !== null) {
  2980. switch (propertyType) {
  2981. case 0:
  2982. serializationObject[targetPropertyName] = sourceProperty;
  2983. break;
  2984. case 1:
  2985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2986. break;
  2987. case 2:
  2988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2989. break;
  2990. case 3:
  2991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2992. break;
  2993. case 4:
  2994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2995. break;
  2996. case 5:
  2997. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2998. break;
  2999. case 6:
  3000. serializationObject[targetPropertyName] = sourceProperty.id;
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. return serializationObject;
  3006. };
  3007. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3008. var destination = creationFunction();
  3009. // Tags
  3010. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3011. // Properties
  3012. for (var property in destination.__serializableMembers) {
  3013. var propertyDescriptor = destination.__serializableMembers[property];
  3014. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3015. var propertyType = propertyDescriptor.type;
  3016. if (sourceProperty !== undefined && sourceProperty !== null) {
  3017. switch (propertyType) {
  3018. case 0:
  3019. destination[property] = sourceProperty;
  3020. break;
  3021. case 1:
  3022. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3023. break;
  3024. case 2:
  3025. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3026. break;
  3027. case 3:
  3028. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3029. break;
  3030. case 4:
  3031. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3032. break;
  3033. case 5:
  3034. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3035. break;
  3036. case 6:
  3037. destination[property] = scene.getLastMeshByID(sourceProperty);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. return destination;
  3043. };
  3044. SerializationHelper.Clone = function (creationFunction, source) {
  3045. var destination = creationFunction();
  3046. // Tags
  3047. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3048. // Properties
  3049. for (var property in destination.__serializableMembers) {
  3050. var propertyDescriptor = destination.__serializableMembers[property];
  3051. var sourceProperty = source[property];
  3052. var propertyType = propertyDescriptor.type;
  3053. if (sourceProperty !== undefined && sourceProperty !== null) {
  3054. switch (propertyType) {
  3055. case 0: // Value
  3056. case 6:
  3057. destination[property] = sourceProperty;
  3058. break;
  3059. case 1: // Texture
  3060. case 2: // Color3
  3061. case 3: // FresnelParameters
  3062. case 4: // Vector2
  3063. case 5:
  3064. destination[property] = sourceProperty.clone();
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return destination;
  3070. };
  3071. return SerializationHelper;
  3072. }());
  3073. BABYLON.SerializationHelper = SerializationHelper;
  3074. })(BABYLON || (BABYLON = {}));
  3075. var BABYLON;
  3076. (function (BABYLON) {
  3077. /**
  3078. * A class serves as a medium between the observable and its observers
  3079. */
  3080. var EventState = (function () {
  3081. /**
  3082. * If the callback of a given Observer set skipNextObervers to true the following observers will be ignored
  3083. */
  3084. function EventState(skipNextObervers) {
  3085. if (skipNextObervers === void 0) { skipNextObervers = false; }
  3086. this.skipNextObervers = skipNextObervers;
  3087. }
  3088. return EventState;
  3089. }());
  3090. BABYLON.EventState = EventState;
  3091. var Observer = (function () {
  3092. function Observer(callback) {
  3093. this.callback = callback;
  3094. }
  3095. return Observer;
  3096. }());
  3097. BABYLON.Observer = Observer;
  3098. var Observable = (function () {
  3099. function Observable() {
  3100. this._observers = new Array();
  3101. }
  3102. /**
  3103. * Create a new Observer with the specified callback
  3104. * @param callback the callback that will be executed for that Observer
  3105. * @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.
  3106. */
  3107. Observable.prototype.add = function (callback, insertFirst) {
  3108. if (insertFirst === void 0) { insertFirst = false; }
  3109. if (!callback) {
  3110. return null;
  3111. }
  3112. var observer = new Observer(callback);
  3113. if (insertFirst) {
  3114. this._observers.unshift(observer);
  3115. }
  3116. else {
  3117. this._observers.push(observer);
  3118. }
  3119. return observer;
  3120. };
  3121. /**
  3122. * Remove an Observer from the Observable object
  3123. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3124. */
  3125. Observable.prototype.remove = function (observer) {
  3126. var index = this._observers.indexOf(observer);
  3127. if (index !== -1) {
  3128. this._observers.splice(index, 1);
  3129. return true;
  3130. }
  3131. return false;
  3132. };
  3133. /**
  3134. * Remove a callback from the Observable object
  3135. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3136. */
  3137. Observable.prototype.removeCallback = function (callback) {
  3138. for (var index = 0; index < this._observers.length; index++) {
  3139. if (this._observers[index].callback === callback) {
  3140. this._observers.splice(index, 1);
  3141. return true;
  3142. }
  3143. }
  3144. return false;
  3145. };
  3146. /**
  3147. * Notify all Observers by calling their respective callback with the given data
  3148. * @param eventData
  3149. */
  3150. Observable.prototype.notifyObservers = function (eventData) {
  3151. var state = new EventState();
  3152. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3153. var obs = _a[_i];
  3154. obs.callback(eventData, state);
  3155. if (state.skipNextObervers) {
  3156. break;
  3157. }
  3158. }
  3159. };
  3160. /**
  3161. * return true is the Observable has at least one Observer registered
  3162. */
  3163. Observable.prototype.hasObservers = function () {
  3164. return this._observers.length > 0;
  3165. };
  3166. /**
  3167. * Clear the list of observers
  3168. */
  3169. Observable.prototype.clear = function () {
  3170. this._observers = new Array();
  3171. };
  3172. /**
  3173. * Clone the current observable
  3174. */
  3175. Observable.prototype.clone = function () {
  3176. var result = new Observable();
  3177. result._observers = this._observers.slice(0);
  3178. return result;
  3179. };
  3180. return Observable;
  3181. }());
  3182. BABYLON.Observable = Observable;
  3183. })(BABYLON || (BABYLON = {}));
  3184. var BABYLON;
  3185. (function (BABYLON) {
  3186. var Database = (function () {
  3187. function Database(urlToScene, callbackManifestChecked) {
  3188. // Handling various flavors of prefixed version of IndexedDB
  3189. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3190. this.callbackManifestChecked = callbackManifestChecked;
  3191. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3192. this.db = null;
  3193. this.enableSceneOffline = false;
  3194. this.enableTexturesOffline = false;
  3195. this.manifestVersionFound = 0;
  3196. this.mustUpdateRessources = false;
  3197. this.hasReachedQuota = false;
  3198. if (!Database.IDBStorageEnabled) {
  3199. this.callbackManifestChecked(true);
  3200. }
  3201. else {
  3202. this.checkManifestFile();
  3203. }
  3204. }
  3205. Database.prototype.checkManifestFile = function () {
  3206. var _this = this;
  3207. function noManifestFile() {
  3208. that.enableSceneOffline = false;
  3209. that.enableTexturesOffline = false;
  3210. that.callbackManifestChecked(false);
  3211. }
  3212. var that = this;
  3213. var timeStampUsed = false;
  3214. var manifestURL = this.currentSceneUrl + ".manifest";
  3215. var xhr = new XMLHttpRequest();
  3216. if (navigator.onLine) {
  3217. // Adding a timestamp to by-pass browsers' cache
  3218. timeStampUsed = true;
  3219. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3220. }
  3221. xhr.open("GET", manifestURL, true);
  3222. xhr.addEventListener("load", function () {
  3223. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3224. try {
  3225. var manifestFile = JSON.parse(xhr.response);
  3226. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3227. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3228. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3229. _this.manifestVersionFound = manifestFile.version;
  3230. }
  3231. if (_this.callbackManifestChecked) {
  3232. _this.callbackManifestChecked(true);
  3233. }
  3234. }
  3235. catch (ex) {
  3236. noManifestFile();
  3237. }
  3238. }
  3239. else {
  3240. noManifestFile();
  3241. }
  3242. }, false);
  3243. xhr.addEventListener("error", function (event) {
  3244. if (timeStampUsed) {
  3245. timeStampUsed = false;
  3246. // Let's retry without the timeStamp
  3247. // It could fail when coupled with HTML5 Offline API
  3248. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3249. xhr.open("GET", retryManifestURL, true);
  3250. xhr.send();
  3251. }
  3252. else {
  3253. noManifestFile();
  3254. }
  3255. }, false);
  3256. try {
  3257. xhr.send();
  3258. }
  3259. catch (ex) {
  3260. BABYLON.Tools.Error("Error on XHR send request.");
  3261. that.callbackManifestChecked(false);
  3262. }
  3263. };
  3264. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3265. var _this = this;
  3266. function handleError() {
  3267. that.isSupported = false;
  3268. if (errorCallback)
  3269. errorCallback();
  3270. }
  3271. var that = this;
  3272. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3273. // Your browser doesn't support IndexedDB
  3274. this.isSupported = false;
  3275. if (errorCallback)
  3276. errorCallback();
  3277. }
  3278. else {
  3279. // If the DB hasn't been opened or created yet
  3280. if (!this.db) {
  3281. this.hasReachedQuota = false;
  3282. this.isSupported = true;
  3283. var request = this.idbFactory.open("babylonjs", 1);
  3284. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3285. request.onerror = function (event) {
  3286. handleError();
  3287. };
  3288. // executes when a version change transaction cannot complete due to other active transactions
  3289. request.onblocked = function (event) {
  3290. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3291. handleError();
  3292. };
  3293. // DB has been opened successfully
  3294. request.onsuccess = function (event) {
  3295. _this.db = request.result;
  3296. successCallback();
  3297. };
  3298. // Initialization of the DB. Creating Scenes & Textures stores
  3299. request.onupgradeneeded = function (event) {
  3300. _this.db = (event.target).result;
  3301. try {
  3302. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3303. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3304. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3305. }
  3306. catch (ex) {
  3307. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3308. handleError();
  3309. }
  3310. };
  3311. }
  3312. else {
  3313. if (successCallback)
  3314. successCallback();
  3315. }
  3316. }
  3317. };
  3318. Database.prototype.loadImageFromDB = function (url, image) {
  3319. var _this = this;
  3320. var completeURL = Database.ReturnFullUrlLocation(url);
  3321. var saveAndLoadImage = function () {
  3322. if (!_this.hasReachedQuota && _this.db !== null) {
  3323. // the texture is not yet in the DB, let's try to save it
  3324. _this._saveImageIntoDBAsync(completeURL, image);
  3325. }
  3326. else {
  3327. image.src = url;
  3328. }
  3329. };
  3330. if (!this.mustUpdateRessources) {
  3331. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3332. }
  3333. else {
  3334. saveAndLoadImage();
  3335. }
  3336. };
  3337. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3338. if (this.isSupported && this.db !== null) {
  3339. var texture;
  3340. var transaction = this.db.transaction(["textures"]);
  3341. transaction.onabort = function (event) {
  3342. image.src = url;
  3343. };
  3344. transaction.oncomplete = function (event) {
  3345. var blobTextureURL;
  3346. if (texture) {
  3347. var URL = window.URL || window.webkitURL;
  3348. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3349. image.onerror = function () {
  3350. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3351. image.src = url;
  3352. };
  3353. image.src = blobTextureURL;
  3354. }
  3355. else {
  3356. notInDBCallback();
  3357. }
  3358. };
  3359. var getRequest = transaction.objectStore("textures").get(url);
  3360. getRequest.onsuccess = function (event) {
  3361. texture = (event.target).result;
  3362. };
  3363. getRequest.onerror = function (event) {
  3364. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3365. image.src = url;
  3366. };
  3367. }
  3368. else {
  3369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3370. image.src = url;
  3371. }
  3372. };
  3373. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3374. var _this = this;
  3375. if (this.isSupported) {
  3376. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3377. var generateBlobUrl = function () {
  3378. var blobTextureURL;
  3379. if (blob) {
  3380. var URL = window.URL || window.webkitURL;
  3381. try {
  3382. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3383. }
  3384. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3385. catch (ex) {
  3386. blobTextureURL = URL.createObjectURL(blob);
  3387. }
  3388. }
  3389. image.src = blobTextureURL;
  3390. };
  3391. if (Database.IsUASupportingBlobStorage) {
  3392. var xhr = new XMLHttpRequest(), blob;
  3393. xhr.open("GET", url, true);
  3394. xhr.responseType = "blob";
  3395. xhr.addEventListener("load", function () {
  3396. if (xhr.status === 200) {
  3397. // Blob as response (XHR2)
  3398. blob = xhr.response;
  3399. var transaction = _this.db.transaction(["textures"], "readwrite");
  3400. // the transaction could abort because of a QuotaExceededError error
  3401. transaction.onabort = function (event) {
  3402. try {
  3403. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3404. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3405. this.hasReachedQuota = true;
  3406. }
  3407. }
  3408. catch (ex) { }
  3409. generateBlobUrl();
  3410. };
  3411. transaction.oncomplete = function (event) {
  3412. generateBlobUrl();
  3413. };
  3414. var newTexture = { textureUrl: url, data: blob };
  3415. try {
  3416. // Put the blob into the dabase
  3417. var addRequest = transaction.objectStore("textures").put(newTexture);
  3418. addRequest.onsuccess = function (event) {
  3419. };
  3420. addRequest.onerror = function (event) {
  3421. generateBlobUrl();
  3422. };
  3423. }
  3424. catch (ex) {
  3425. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3426. if (ex.code === 25) {
  3427. Database.IsUASupportingBlobStorage = false;
  3428. }
  3429. image.src = url;
  3430. }
  3431. }
  3432. else {
  3433. image.src = url;
  3434. }
  3435. }, false);
  3436. xhr.addEventListener("error", function (event) {
  3437. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3438. image.src = url;
  3439. }, false);
  3440. xhr.send();
  3441. }
  3442. else {
  3443. image.src = url;
  3444. }
  3445. }
  3446. else {
  3447. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3448. image.src = url;
  3449. }
  3450. };
  3451. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3452. var _this = this;
  3453. var updateVersion = function (event) {
  3454. // the version is not yet in the DB or we need to update it
  3455. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3456. };
  3457. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3458. };
  3459. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3460. var _this = this;
  3461. if (this.isSupported) {
  3462. var version;
  3463. try {
  3464. var transaction = this.db.transaction(["versions"]);
  3465. transaction.oncomplete = function (event) {
  3466. if (version) {
  3467. // If the version in the JSON file is > than the version in DB
  3468. if (_this.manifestVersionFound > version.data) {
  3469. _this.mustUpdateRessources = true;
  3470. updateInDBCallback();
  3471. }
  3472. else {
  3473. callback(version.data);
  3474. }
  3475. }
  3476. else {
  3477. _this.mustUpdateRessources = true;
  3478. updateInDBCallback();
  3479. }
  3480. };
  3481. transaction.onabort = function (event) {
  3482. callback(-1);
  3483. };
  3484. var getRequest = transaction.objectStore("versions").get(url);
  3485. getRequest.onsuccess = function (event) {
  3486. version = (event.target).result;
  3487. };
  3488. getRequest.onerror = function (event) {
  3489. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3490. callback(-1);
  3491. };
  3492. }
  3493. catch (ex) {
  3494. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3495. callback(-1);
  3496. }
  3497. }
  3498. else {
  3499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3500. callback(-1);
  3501. }
  3502. };
  3503. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3504. var _this = this;
  3505. if (this.isSupported && !this.hasReachedQuota) {
  3506. try {
  3507. // Open a transaction to the database
  3508. var transaction = this.db.transaction(["versions"], "readwrite");
  3509. // the transaction could abort because of a QuotaExceededError error
  3510. transaction.onabort = function (event) {
  3511. try {
  3512. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3513. _this.hasReachedQuota = true;
  3514. }
  3515. }
  3516. catch (ex) { }
  3517. callback(-1);
  3518. };
  3519. transaction.oncomplete = function (event) {
  3520. callback(_this.manifestVersionFound);
  3521. };
  3522. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3523. // Put the scene into the database
  3524. var addRequest = transaction.objectStore("versions").put(newVersion);
  3525. addRequest.onsuccess = function (event) {
  3526. };
  3527. addRequest.onerror = function (event) {
  3528. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3529. };
  3530. }
  3531. catch (ex) {
  3532. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3533. callback(-1);
  3534. }
  3535. }
  3536. else {
  3537. callback(-1);
  3538. }
  3539. };
  3540. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3541. var _this = this;
  3542. var completeUrl = Database.ReturnFullUrlLocation(url);
  3543. var saveAndLoadFile = function (event) {
  3544. // the scene is not yet in the DB, let's try to save it
  3545. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3546. };
  3547. this._checkVersionFromDB(completeUrl, function (version) {
  3548. if (version !== -1) {
  3549. if (!_this.mustUpdateRessources) {
  3550. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3551. }
  3552. else {
  3553. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3554. }
  3555. }
  3556. else {
  3557. errorCallback();
  3558. }
  3559. });
  3560. };
  3561. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3562. if (this.isSupported) {
  3563. var targetStore;
  3564. if (url.indexOf(".babylon") !== -1) {
  3565. targetStore = "scenes";
  3566. }
  3567. else {
  3568. targetStore = "textures";
  3569. }
  3570. var file;
  3571. var transaction = this.db.transaction([targetStore]);
  3572. transaction.oncomplete = function (event) {
  3573. if (file) {
  3574. callback(file.data);
  3575. }
  3576. else {
  3577. notInDBCallback();
  3578. }
  3579. };
  3580. transaction.onabort = function (event) {
  3581. notInDBCallback();
  3582. };
  3583. var getRequest = transaction.objectStore(targetStore).get(url);
  3584. getRequest.onsuccess = function (event) {
  3585. file = (event.target).result;
  3586. };
  3587. getRequest.onerror = function (event) {
  3588. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3589. notInDBCallback();
  3590. };
  3591. }
  3592. else {
  3593. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3594. callback();
  3595. }
  3596. };
  3597. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3598. var _this = this;
  3599. if (this.isSupported) {
  3600. var targetStore;
  3601. if (url.indexOf(".babylon") !== -1) {
  3602. targetStore = "scenes";
  3603. }
  3604. else {
  3605. targetStore = "textures";
  3606. }
  3607. // Create XHR
  3608. var xhr = new XMLHttpRequest(), fileData;
  3609. xhr.open("GET", url, true);
  3610. if (useArrayBuffer) {
  3611. xhr.responseType = "arraybuffer";
  3612. }
  3613. xhr.onprogress = progressCallback;
  3614. xhr.addEventListener("load", function () {
  3615. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3616. // Blob as response (XHR2)
  3617. //fileData = xhr.responseText;
  3618. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3619. if (!_this.hasReachedQuota) {
  3620. // Open a transaction to the database
  3621. var transaction = _this.db.transaction([targetStore], "readwrite");
  3622. // the transaction could abort because of a QuotaExceededError error
  3623. transaction.onabort = function (event) {
  3624. try {
  3625. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3626. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3627. this.hasReachedQuota = true;
  3628. }
  3629. }
  3630. catch (ex) { }
  3631. callback(fileData);
  3632. };
  3633. transaction.oncomplete = function (event) {
  3634. callback(fileData);
  3635. };
  3636. var newFile;
  3637. if (targetStore === "scenes") {
  3638. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3639. }
  3640. else {
  3641. newFile = { textureUrl: url, data: fileData };
  3642. }
  3643. try {
  3644. // Put the scene into the database
  3645. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3646. addRequest.onsuccess = function (event) {
  3647. };
  3648. addRequest.onerror = function (event) {
  3649. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3650. };
  3651. }
  3652. catch (ex) {
  3653. callback(fileData);
  3654. }
  3655. }
  3656. else {
  3657. callback(fileData);
  3658. }
  3659. }
  3660. else {
  3661. callback();
  3662. }
  3663. }, false);
  3664. xhr.addEventListener("error", function (event) {
  3665. BABYLON.Tools.Error("error on XHR request.");
  3666. callback();
  3667. }, false);
  3668. xhr.send();
  3669. }
  3670. else {
  3671. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3672. callback();
  3673. }
  3674. };
  3675. Database.IsUASupportingBlobStorage = true;
  3676. Database.IDBStorageEnabled = true;
  3677. Database.parseURL = function (url) {
  3678. var a = document.createElement('a');
  3679. a.href = url;
  3680. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3681. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3682. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3683. return absLocation;
  3684. };
  3685. Database.ReturnFullUrlLocation = function (url) {
  3686. if (url.indexOf("http:/") === -1) {
  3687. return (Database.parseURL(window.location.href) + url);
  3688. }
  3689. else {
  3690. return url;
  3691. }
  3692. };
  3693. return Database;
  3694. }());
  3695. BABYLON.Database = Database;
  3696. })(BABYLON || (BABYLON = {}));
  3697. var BABYLON;
  3698. (function (BABYLON) {
  3699. var Internals;
  3700. (function (Internals) {
  3701. /*
  3702. * Based on jsTGALoader - Javascript loader for TGA file
  3703. * By Vincent Thibault
  3704. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3705. */
  3706. var TGATools = (function () {
  3707. function TGATools() {
  3708. }
  3709. TGATools.GetTGAHeader = function (data) {
  3710. var offset = 0;
  3711. var header = {
  3712. id_length: data[offset++],
  3713. colormap_type: data[offset++],
  3714. image_type: data[offset++],
  3715. colormap_index: data[offset++] | data[offset++] << 8,
  3716. colormap_length: data[offset++] | data[offset++] << 8,
  3717. colormap_size: data[offset++],
  3718. origin: [
  3719. data[offset++] | data[offset++] << 8,
  3720. data[offset++] | data[offset++] << 8
  3721. ],
  3722. width: data[offset++] | data[offset++] << 8,
  3723. height: data[offset++] | data[offset++] << 8,
  3724. pixel_size: data[offset++],
  3725. flags: data[offset++]
  3726. };
  3727. return header;
  3728. };
  3729. TGATools.UploadContent = function (gl, data) {
  3730. // Not enough data to contain header ?
  3731. if (data.length < 19) {
  3732. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3733. return;
  3734. }
  3735. // Read Header
  3736. var offset = 18;
  3737. var header = TGATools.GetTGAHeader(data);
  3738. // Assume it's a valid Targa file.
  3739. if (header.id_length + offset > data.length) {
  3740. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3741. return;
  3742. }
  3743. // Skip not needed data
  3744. offset += header.id_length;
  3745. var use_rle = false;
  3746. var use_pal = false;
  3747. var use_rgb = false;
  3748. var use_grey = false;
  3749. // Get some informations.
  3750. switch (header.image_type) {
  3751. case TGATools._TYPE_RLE_INDEXED:
  3752. use_rle = true;
  3753. case TGATools._TYPE_INDEXED:
  3754. use_pal = true;
  3755. break;
  3756. case TGATools._TYPE_RLE_RGB:
  3757. use_rle = true;
  3758. case TGATools._TYPE_RGB:
  3759. use_rgb = true;
  3760. break;
  3761. case TGATools._TYPE_RLE_GREY:
  3762. use_rle = true;
  3763. case TGATools._TYPE_GREY:
  3764. use_grey = true;
  3765. break;
  3766. }
  3767. var pixel_data;
  3768. var numAlphaBits = header.flags & 0xf;
  3769. var pixel_size = header.pixel_size >> 3;
  3770. var pixel_total = header.width * header.height * pixel_size;
  3771. // Read palettes
  3772. var palettes;
  3773. if (use_pal) {
  3774. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3775. }
  3776. // Read LRE
  3777. if (use_rle) {
  3778. pixel_data = new Uint8Array(pixel_total);
  3779. var c, count, i;
  3780. var localOffset = 0;
  3781. var pixels = new Uint8Array(pixel_size);
  3782. while (offset < pixel_total && localOffset < pixel_total) {
  3783. c = data[offset++];
  3784. count = (c & 0x7f) + 1;
  3785. // RLE pixels
  3786. if (c & 0x80) {
  3787. // Bind pixel tmp array
  3788. for (i = 0; i < pixel_size; ++i) {
  3789. pixels[i] = data[offset++];
  3790. }
  3791. // Copy pixel array
  3792. for (i = 0; i < count; ++i) {
  3793. pixel_data.set(pixels, localOffset + i * pixel_size);
  3794. }
  3795. localOffset += pixel_size * count;
  3796. }
  3797. else {
  3798. count *= pixel_size;
  3799. for (i = 0; i < count; ++i) {
  3800. pixel_data[localOffset + i] = data[offset++];
  3801. }
  3802. localOffset += count;
  3803. }
  3804. }
  3805. }
  3806. else {
  3807. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3808. }
  3809. // Load to texture
  3810. var x_start, y_start, x_step, y_step, y_end, x_end;
  3811. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3812. default:
  3813. case TGATools._ORIGIN_UL:
  3814. x_start = 0;
  3815. x_step = 1;
  3816. x_end = header.width;
  3817. y_start = 0;
  3818. y_step = 1;
  3819. y_end = header.height;
  3820. break;
  3821. case TGATools._ORIGIN_BL:
  3822. x_start = 0;
  3823. x_step = 1;
  3824. x_end = header.width;
  3825. y_start = header.height - 1;
  3826. y_step = -1;
  3827. y_end = -1;
  3828. break;
  3829. case TGATools._ORIGIN_UR:
  3830. x_start = header.width - 1;
  3831. x_step = -1;
  3832. x_end = -1;
  3833. y_start = 0;
  3834. y_step = 1;
  3835. y_end = header.height;
  3836. break;
  3837. case TGATools._ORIGIN_BR:
  3838. x_start = header.width - 1;
  3839. x_step = -1;
  3840. x_end = -1;
  3841. y_start = header.height - 1;
  3842. y_step = -1;
  3843. y_end = -1;
  3844. break;
  3845. }
  3846. // Load the specify method
  3847. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3848. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3849. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3850. };
  3851. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3852. var image = pixel_data, colormap = palettes;
  3853. var width = header.width, height = header.height;
  3854. var color, i = 0, x, y;
  3855. var imageData = new Uint8Array(width * height * 4);
  3856. for (y = y_start; y !== y_end; y += y_step) {
  3857. for (x = x_start; x !== x_end; x += x_step, i++) {
  3858. color = image[i];
  3859. imageData[(x + width * y) * 4 + 3] = 255;
  3860. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3861. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3862. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3863. }
  3864. }
  3865. return imageData;
  3866. };
  3867. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3868. var image = pixel_data;
  3869. var width = header.width, height = header.height;
  3870. var color, i = 0, x, y;
  3871. var imageData = new Uint8Array(width * height * 4);
  3872. for (y = y_start; y !== y_end; y += y_step) {
  3873. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3874. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3875. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3876. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3877. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3878. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3879. }
  3880. }
  3881. return imageData;
  3882. };
  3883. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3884. var image = pixel_data;
  3885. var width = header.width, height = header.height;
  3886. var i = 0, x, y;
  3887. var imageData = new Uint8Array(width * height * 4);
  3888. for (y = y_start; y !== y_end; y += y_step) {
  3889. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3890. imageData[(x + width * y) * 4 + 3] = 255;
  3891. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3892. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3893. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3905. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3906. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3907. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3908. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3909. }
  3910. }
  3911. return imageData;
  3912. };
  3913. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3914. var image = pixel_data;
  3915. var width = header.width, height = header.height;
  3916. var color, i = 0, x, y;
  3917. var imageData = new Uint8Array(width * height * 4);
  3918. for (y = y_start; y !== y_end; y += y_step) {
  3919. for (x = x_start; x !== x_end; x += x_step, i++) {
  3920. color = image[i];
  3921. imageData[(x + width * y) * 4 + 0] = color;
  3922. imageData[(x + width * y) * 4 + 1] = color;
  3923. imageData[(x + width * y) * 4 + 2] = color;
  3924. imageData[(x + width * y) * 4 + 3] = 255;
  3925. }
  3926. }
  3927. return imageData;
  3928. };
  3929. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3930. var image = pixel_data;
  3931. var width = header.width, height = header.height;
  3932. var i = 0, x, y;
  3933. var imageData = new Uint8Array(width * height * 4);
  3934. for (y = y_start; y !== y_end; y += y_step) {
  3935. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3936. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3937. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3938. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3939. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._TYPE_NO_DATA = 0;
  3945. TGATools._TYPE_INDEXED = 1;
  3946. TGATools._TYPE_RGB = 2;
  3947. TGATools._TYPE_GREY = 3;
  3948. TGATools._TYPE_RLE_INDEXED = 9;
  3949. TGATools._TYPE_RLE_RGB = 10;
  3950. TGATools._TYPE_RLE_GREY = 11;
  3951. TGATools._ORIGIN_MASK = 0x30;
  3952. TGATools._ORIGIN_SHIFT = 0x04;
  3953. TGATools._ORIGIN_BL = 0x00;
  3954. TGATools._ORIGIN_BR = 0x01;
  3955. TGATools._ORIGIN_UL = 0x02;
  3956. TGATools._ORIGIN_UR = 0x03;
  3957. return TGATools;
  3958. }());
  3959. Internals.TGATools = TGATools;
  3960. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3961. })(BABYLON || (BABYLON = {}));
  3962. var BABYLON;
  3963. (function (BABYLON) {
  3964. var SmartArray = (function () {
  3965. function SmartArray(capacity) {
  3966. this.length = 0;
  3967. this._duplicateId = 0;
  3968. this.data = new Array(capacity);
  3969. this._id = SmartArray._GlobalId++;
  3970. }
  3971. SmartArray.prototype.push = function (value) {
  3972. this.data[this.length++] = value;
  3973. if (this.length > this.data.length) {
  3974. this.data.length *= 2;
  3975. }
  3976. if (!value.__smartArrayFlags) {
  3977. value.__smartArrayFlags = {};
  3978. }
  3979. value.__smartArrayFlags[this._id] = this._duplicateId;
  3980. };
  3981. SmartArray.prototype.pushNoDuplicate = function (value) {
  3982. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3983. return;
  3984. }
  3985. this.push(value);
  3986. };
  3987. SmartArray.prototype.sort = function (compareFn) {
  3988. this.data.sort(compareFn);
  3989. };
  3990. SmartArray.prototype.reset = function () {
  3991. this.length = 0;
  3992. this._duplicateId++;
  3993. };
  3994. SmartArray.prototype.concat = function (array) {
  3995. if (array.length === 0) {
  3996. return;
  3997. }
  3998. if (this.length + array.length > this.data.length) {
  3999. this.data.length = (this.length + array.length) * 2;
  4000. }
  4001. for (var index = 0; index < array.length; index++) {
  4002. this.data[this.length++] = (array.data || array)[index];
  4003. }
  4004. };
  4005. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4006. if (array.length === 0) {
  4007. return;
  4008. }
  4009. if (this.length + array.length > this.data.length) {
  4010. this.data.length = (this.length + array.length) * 2;
  4011. }
  4012. for (var index = 0; index < array.length; index++) {
  4013. var item = (array.data || array)[index];
  4014. this.pushNoDuplicate(item);
  4015. }
  4016. };
  4017. SmartArray.prototype.indexOf = function (value) {
  4018. var position = this.data.indexOf(value);
  4019. if (position >= this.length) {
  4020. return -1;
  4021. }
  4022. return position;
  4023. };
  4024. // Statics
  4025. SmartArray._GlobalId = 0;
  4026. return SmartArray;
  4027. }());
  4028. BABYLON.SmartArray = SmartArray;
  4029. })(BABYLON || (BABYLON = {}));
  4030. var BABYLON;
  4031. (function (BABYLON) {
  4032. var SmartCollection = (function () {
  4033. function SmartCollection(capacity) {
  4034. if (capacity === void 0) { capacity = 10; }
  4035. this.count = 0;
  4036. this._initialCapacity = capacity;
  4037. this.items = {};
  4038. this._keys = new Array(this._initialCapacity);
  4039. }
  4040. SmartCollection.prototype.add = function (key, item) {
  4041. if (this.items[key] != undefined) {
  4042. return -1;
  4043. }
  4044. this.items[key] = item;
  4045. //literal keys are always strings, but we keep source type of key in _keys array
  4046. this._keys[this.count++] = key;
  4047. if (this.count > this._keys.length) {
  4048. this._keys.length *= 2;
  4049. }
  4050. return this.count;
  4051. };
  4052. SmartCollection.prototype.remove = function (key) {
  4053. if (this.items[key] == undefined) {
  4054. return -1;
  4055. }
  4056. return this.removeItemOfIndex(this.indexOf(key));
  4057. };
  4058. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4059. if (index < this.count && index > -1) {
  4060. delete this.items[this._keys[index]];
  4061. //here, shifting by hand is better optimised than .splice
  4062. while (index < this.count) {
  4063. this._keys[index] = this._keys[index + 1];
  4064. index++;
  4065. }
  4066. }
  4067. else {
  4068. return -1;
  4069. }
  4070. return --this.count;
  4071. };
  4072. SmartCollection.prototype.indexOf = function (key) {
  4073. for (var i = 0; i !== this.count; i++) {
  4074. if (this._keys[i] === key) {
  4075. return i;
  4076. }
  4077. }
  4078. return -1;
  4079. };
  4080. SmartCollection.prototype.item = function (key) {
  4081. return this.items[key];
  4082. };
  4083. SmartCollection.prototype.getAllKeys = function () {
  4084. if (this.count > 0) {
  4085. var keys = new Array(this.count);
  4086. for (var i = 0; i < this.count; i++) {
  4087. keys[i] = this._keys[i];
  4088. }
  4089. return keys;
  4090. }
  4091. else {
  4092. return undefined;
  4093. }
  4094. };
  4095. SmartCollection.prototype.getKeyByIndex = function (index) {
  4096. if (index < this.count && index > -1) {
  4097. return this._keys[index];
  4098. }
  4099. else {
  4100. return undefined;
  4101. }
  4102. };
  4103. SmartCollection.prototype.getItemByIndex = function (index) {
  4104. if (index < this.count && index > -1) {
  4105. return this.items[this._keys[index]];
  4106. }
  4107. else {
  4108. return undefined;
  4109. }
  4110. };
  4111. SmartCollection.prototype.empty = function () {
  4112. if (this.count > 0) {
  4113. this.count = 0;
  4114. this.items = {};
  4115. this._keys = new Array(this._initialCapacity);
  4116. }
  4117. };
  4118. SmartCollection.prototype.forEach = function (block) {
  4119. var key;
  4120. for (key in this.items) {
  4121. if (this.items.hasOwnProperty(key)) {
  4122. block(this.items[key]);
  4123. }
  4124. }
  4125. };
  4126. return SmartCollection;
  4127. }());
  4128. BABYLON.SmartCollection = SmartCollection;
  4129. })(BABYLON || (BABYLON = {}));
  4130. var BABYLON;
  4131. (function (BABYLON) {
  4132. // Screenshots
  4133. var screenshotCanvas;
  4134. var cloneValue = function (source, destinationObject) {
  4135. if (!source)
  4136. return null;
  4137. if (source instanceof BABYLON.Mesh) {
  4138. return null;
  4139. }
  4140. if (source instanceof BABYLON.SubMesh) {
  4141. return source.clone(destinationObject);
  4142. }
  4143. else if (source.clone) {
  4144. return source.clone();
  4145. }
  4146. return null;
  4147. };
  4148. var Tools = (function () {
  4149. function Tools() {
  4150. }
  4151. Tools.Instantiate = function (className) {
  4152. var arr = className.split(".");
  4153. var fn = (window || this);
  4154. for (var i = 0, len = arr.length; i < len; i++) {
  4155. fn = fn[arr[i]];
  4156. }
  4157. if (typeof fn !== "function") {
  4158. return null;
  4159. }
  4160. return fn;
  4161. };
  4162. Tools.SetImmediate = function (action) {
  4163. if (window.setImmediate) {
  4164. window.setImmediate(action);
  4165. }
  4166. else {
  4167. setTimeout(action, 1);
  4168. }
  4169. };
  4170. Tools.IsExponentOfTwo = function (value) {
  4171. var count = 1;
  4172. do {
  4173. count *= 2;
  4174. } while (count < value);
  4175. return count === value;
  4176. };
  4177. Tools.GetExponentOfTwo = function (value, max) {
  4178. var count = 1;
  4179. do {
  4180. count *= 2;
  4181. } while (count < value);
  4182. if (count > max)
  4183. count = max;
  4184. return count;
  4185. };
  4186. Tools.GetFilename = function (path) {
  4187. var index = path.lastIndexOf("/");
  4188. if (index < 0)
  4189. return path;
  4190. return path.substring(index + 1);
  4191. };
  4192. Tools.GetDOMTextContent = function (element) {
  4193. var result = "";
  4194. var child = element.firstChild;
  4195. while (child) {
  4196. if (child.nodeType === 3) {
  4197. result += child.textContent;
  4198. }
  4199. child = child.nextSibling;
  4200. }
  4201. return result;
  4202. };
  4203. Tools.ToDegrees = function (angle) {
  4204. return angle * 180 / Math.PI;
  4205. };
  4206. Tools.ToRadians = function (angle) {
  4207. return angle * Math.PI / 180;
  4208. };
  4209. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4210. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4211. var output = "";
  4212. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4213. var i = 0;
  4214. var bytes = new Uint8Array(buffer);
  4215. while (i < bytes.length) {
  4216. chr1 = bytes[i++];
  4217. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4218. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4219. enc1 = chr1 >> 2;
  4220. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4221. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4222. enc4 = chr3 & 63;
  4223. if (isNaN(chr2)) {
  4224. enc3 = enc4 = 64;
  4225. }
  4226. else if (isNaN(chr3)) {
  4227. enc4 = 64;
  4228. }
  4229. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4230. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4231. }
  4232. return "data:image/png;base64," + output;
  4233. };
  4234. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4235. if (bias === void 0) { bias = null; }
  4236. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4237. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4238. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4239. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4240. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4241. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4242. }
  4243. if (bias) {
  4244. minimum.x -= minimum.x * bias.x + bias.y;
  4245. minimum.y -= minimum.y * bias.x + bias.y;
  4246. minimum.z -= minimum.z * bias.x + bias.y;
  4247. maximum.x += maximum.x * bias.x + bias.y;
  4248. maximum.y += maximum.y * bias.x + bias.y;
  4249. maximum.z += maximum.z * bias.x + bias.y;
  4250. }
  4251. return {
  4252. minimum: minimum,
  4253. maximum: maximum
  4254. };
  4255. };
  4256. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4257. if (bias === void 0) { bias = null; }
  4258. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4259. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4260. for (var index = start; index < start + count; index++) {
  4261. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4262. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4263. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4264. }
  4265. if (bias) {
  4266. minimum.x -= minimum.x * bias.x + bias.y;
  4267. minimum.y -= minimum.y * bias.x + bias.y;
  4268. minimum.z -= minimum.z * bias.x + bias.y;
  4269. maximum.x += maximum.x * bias.x + bias.y;
  4270. maximum.y += maximum.y * bias.x + bias.y;
  4271. maximum.z += maximum.z * bias.x + bias.y;
  4272. }
  4273. return {
  4274. minimum: minimum,
  4275. maximum: maximum
  4276. };
  4277. };
  4278. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4279. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4280. return undefined;
  4281. return Array.isArray(obj) ? obj : [obj];
  4282. };
  4283. // Misc.
  4284. Tools.GetPointerPrefix = function () {
  4285. var eventPrefix = "pointer";
  4286. // Check if pointer events are supported
  4287. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4288. eventPrefix = "mouse";
  4289. }
  4290. return eventPrefix;
  4291. };
  4292. Tools.QueueNewFrame = function (func) {
  4293. if (window.requestAnimationFrame)
  4294. window.requestAnimationFrame(func);
  4295. else if (window.msRequestAnimationFrame)
  4296. window.msRequestAnimationFrame(func);
  4297. else if (window.webkitRequestAnimationFrame)
  4298. window.webkitRequestAnimationFrame(func);
  4299. else if (window.mozRequestAnimationFrame)
  4300. window.mozRequestAnimationFrame(func);
  4301. else if (window.oRequestAnimationFrame)
  4302. window.oRequestAnimationFrame(func);
  4303. else {
  4304. window.setTimeout(func, 16);
  4305. }
  4306. };
  4307. Tools.RequestFullscreen = function (element) {
  4308. if (element.requestFullscreen)
  4309. element.requestFullscreen();
  4310. else if (element.msRequestFullscreen)
  4311. element.msRequestFullscreen();
  4312. else if (element.webkitRequestFullscreen)
  4313. element.webkitRequestFullscreen();
  4314. else if (element.mozRequestFullScreen)
  4315. element.mozRequestFullScreen();
  4316. };
  4317. Tools.ExitFullscreen = function () {
  4318. if (document.exitFullscreen) {
  4319. document.exitFullscreen();
  4320. }
  4321. else if (document.mozCancelFullScreen) {
  4322. document.mozCancelFullScreen();
  4323. }
  4324. else if (document.webkitCancelFullScreen) {
  4325. document.webkitCancelFullScreen();
  4326. }
  4327. else if (document.msCancelFullScreen) {
  4328. document.msCancelFullScreen();
  4329. }
  4330. };
  4331. // External files
  4332. Tools.CleanUrl = function (url) {
  4333. url = url.replace(/#/mg, "%23");
  4334. return url;
  4335. };
  4336. Tools.LoadImage = function (url, onload, onerror, database) {
  4337. if (url instanceof ArrayBuffer) {
  4338. url = Tools.EncodeArrayBufferTobase64(url);
  4339. }
  4340. url = Tools.CleanUrl(url);
  4341. var img = new Image();
  4342. if (url.substr(0, 5) !== "data:") {
  4343. if (Tools.CorsBehavior) {
  4344. switch (typeof (Tools.CorsBehavior)) {
  4345. case "function":
  4346. var result = Tools.CorsBehavior(url);
  4347. if (result) {
  4348. img.crossOrigin = result;
  4349. }
  4350. break;
  4351. case "string":
  4352. default:
  4353. img.crossOrigin = Tools.CorsBehavior;
  4354. break;
  4355. }
  4356. }
  4357. }
  4358. img.onload = function () {
  4359. onload(img);
  4360. };
  4361. img.onerror = function (err) {
  4362. Tools.Error("Error while trying to load texture: " + url);
  4363. if (Tools.UseFallbackTexture) {
  4364. 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";
  4365. onload(img);
  4366. }
  4367. else {
  4368. onerror();
  4369. }
  4370. };
  4371. var noIndexedDB = function () {
  4372. img.src = url;
  4373. };
  4374. var loadFromIndexedDB = function () {
  4375. database.loadImageFromDB(url, img);
  4376. };
  4377. //ANY database to do!
  4378. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4379. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4380. }
  4381. else {
  4382. if (url.indexOf("file:") === -1) {
  4383. noIndexedDB();
  4384. }
  4385. else {
  4386. try {
  4387. var textureName = url.substring(5);
  4388. var blobURL;
  4389. try {
  4390. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4391. }
  4392. catch (ex) {
  4393. // Chrome doesn't support oneTimeOnly parameter
  4394. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4395. }
  4396. img.src = blobURL;
  4397. }
  4398. catch (e) {
  4399. img.src = null;
  4400. }
  4401. }
  4402. }
  4403. return img;
  4404. };
  4405. //ANY
  4406. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4407. url = Tools.CleanUrl(url);
  4408. var noIndexedDB = function () {
  4409. var request = new XMLHttpRequest();
  4410. var loadUrl = Tools.BaseUrl + url;
  4411. request.open('GET', loadUrl, true);
  4412. if (useArrayBuffer) {
  4413. request.responseType = "arraybuffer";
  4414. }
  4415. request.onprogress = progressCallBack;
  4416. request.onreadystatechange = function () {
  4417. if (request.readyState === 4) {
  4418. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4419. callback(!useArrayBuffer ? request.responseText : request.response);
  4420. }
  4421. else {
  4422. if (onError) {
  4423. onError();
  4424. }
  4425. else {
  4426. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4427. }
  4428. }
  4429. }
  4430. };
  4431. request.send(null);
  4432. };
  4433. var loadFromIndexedDB = function () {
  4434. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4435. };
  4436. if (url.indexOf("file:") !== -1) {
  4437. var fileName = url.substring(5).toLowerCase();
  4438. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4439. }
  4440. else {
  4441. // Caching all files
  4442. if (database && database.enableSceneOffline) {
  4443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4444. }
  4445. else {
  4446. noIndexedDB();
  4447. }
  4448. }
  4449. };
  4450. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4451. var reader = new FileReader();
  4452. reader.onload = function (e) {
  4453. //target doesn't have result from ts 1.3
  4454. callback(e.target['result']);
  4455. };
  4456. reader.onprogress = progressCallback;
  4457. reader.readAsDataURL(fileToLoad);
  4458. };
  4459. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4460. var reader = new FileReader();
  4461. reader.onerror = function (e) {
  4462. Tools.Log("Error while reading file: " + fileToLoad.name);
  4463. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4464. };
  4465. reader.onload = function (e) {
  4466. //target doesn't have result from ts 1.3
  4467. callback(e.target['result']);
  4468. };
  4469. reader.onprogress = progressCallBack;
  4470. if (!useArrayBuffer) {
  4471. // Asynchronous read
  4472. reader.readAsText(fileToLoad);
  4473. }
  4474. else {
  4475. reader.readAsArrayBuffer(fileToLoad);
  4476. }
  4477. };
  4478. //returns a downloadable url to a file content.
  4479. Tools.FileAsURL = function (content) {
  4480. var fileBlob = new Blob([content]);
  4481. var url = window.URL || window.webkitURL;
  4482. var link = url.createObjectURL(fileBlob);
  4483. return link;
  4484. };
  4485. // Misc.
  4486. Tools.Format = function (value, decimals) {
  4487. if (decimals === void 0) { decimals = 2; }
  4488. return value.toFixed(decimals);
  4489. };
  4490. Tools.CheckExtends = function (v, min, max) {
  4491. if (v.x < min.x)
  4492. min.x = v.x;
  4493. if (v.y < min.y)
  4494. min.y = v.y;
  4495. if (v.z < min.z)
  4496. min.z = v.z;
  4497. if (v.x > max.x)
  4498. max.x = v.x;
  4499. if (v.y > max.y)
  4500. max.y = v.y;
  4501. if (v.z > max.z)
  4502. max.z = v.z;
  4503. };
  4504. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4505. for (var prop in source) {
  4506. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4507. continue;
  4508. }
  4509. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4510. continue;
  4511. }
  4512. var sourceValue = source[prop];
  4513. var typeOfSourceValue = typeof sourceValue;
  4514. if (typeOfSourceValue === "function") {
  4515. continue;
  4516. }
  4517. if (typeOfSourceValue === "object") {
  4518. if (sourceValue instanceof Array) {
  4519. destination[prop] = [];
  4520. if (sourceValue.length > 0) {
  4521. if (typeof sourceValue[0] == "object") {
  4522. for (var index = 0; index < sourceValue.length; index++) {
  4523. var clonedValue = cloneValue(sourceValue[index], destination);
  4524. if (destination[prop].indexOf(clonedValue) === -1) {
  4525. destination[prop].push(clonedValue);
  4526. }
  4527. }
  4528. }
  4529. else {
  4530. destination[prop] = sourceValue.slice(0);
  4531. }
  4532. }
  4533. }
  4534. else {
  4535. destination[prop] = cloneValue(sourceValue, destination);
  4536. }
  4537. }
  4538. else {
  4539. destination[prop] = sourceValue;
  4540. }
  4541. }
  4542. };
  4543. Tools.IsEmpty = function (obj) {
  4544. for (var i in obj) {
  4545. return false;
  4546. }
  4547. return true;
  4548. };
  4549. Tools.RegisterTopRootEvents = function (events) {
  4550. for (var index = 0; index < events.length; index++) {
  4551. var event = events[index];
  4552. window.addEventListener(event.name, event.handler, false);
  4553. try {
  4554. if (window.parent) {
  4555. window.parent.addEventListener(event.name, event.handler, false);
  4556. }
  4557. }
  4558. catch (e) {
  4559. }
  4560. }
  4561. };
  4562. Tools.UnregisterTopRootEvents = function (events) {
  4563. for (var index = 0; index < events.length; index++) {
  4564. var event = events[index];
  4565. window.removeEventListener(event.name, event.handler);
  4566. try {
  4567. if (window.parent) {
  4568. window.parent.removeEventListener(event.name, event.handler);
  4569. }
  4570. }
  4571. catch (e) {
  4572. }
  4573. }
  4574. };
  4575. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4576. // Read the contents of the framebuffer
  4577. var numberOfChannelsByLine = width * 4;
  4578. var halfHeight = height / 2;
  4579. //Reading datas from WebGL
  4580. var data = engine.readPixels(0, 0, width, height);
  4581. //To flip image on Y axis.
  4582. for (var i = 0; i < halfHeight; i++) {
  4583. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4584. var currentCell = j + i * numberOfChannelsByLine;
  4585. var targetLine = height - i - 1;
  4586. var targetCell = j + targetLine * numberOfChannelsByLine;
  4587. var temp = data[currentCell];
  4588. data[currentCell] = data[targetCell];
  4589. data[targetCell] = temp;
  4590. }
  4591. }
  4592. // Create a 2D canvas to store the result
  4593. if (!screenshotCanvas) {
  4594. screenshotCanvas = document.createElement('canvas');
  4595. }
  4596. screenshotCanvas.width = width;
  4597. screenshotCanvas.height = height;
  4598. var context = screenshotCanvas.getContext('2d');
  4599. // Copy the pixels to a 2D canvas
  4600. var imageData = context.createImageData(width, height);
  4601. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4602. var castData = imageData.data;
  4603. castData.set(data);
  4604. context.putImageData(imageData, 0, 0);
  4605. var base64Image = screenshotCanvas.toDataURL();
  4606. if (successCallback) {
  4607. successCallback(base64Image);
  4608. }
  4609. else {
  4610. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4611. if (("download" in document.createElement("a"))) {
  4612. var a = window.document.createElement("a");
  4613. a.href = base64Image;
  4614. var date = new Date();
  4615. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4616. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4617. window.document.body.appendChild(a);
  4618. a.addEventListener("click", function () {
  4619. a.parentElement.removeChild(a);
  4620. });
  4621. a.click();
  4622. }
  4623. else {
  4624. var newWindow = window.open("");
  4625. var img = newWindow.document.createElement("img");
  4626. img.src = base64Image;
  4627. newWindow.document.body.appendChild(img);
  4628. }
  4629. }
  4630. };
  4631. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4632. var width;
  4633. var height;
  4634. //If a precision value is specified
  4635. if (size.precision) {
  4636. width = Math.round(engine.getRenderWidth() * size.precision);
  4637. height = Math.round(width / engine.getAspectRatio(camera));
  4638. size = { width: width, height: height };
  4639. }
  4640. else if (size.width && size.height) {
  4641. width = size.width;
  4642. height = size.height;
  4643. }
  4644. else if (size.width && !size.height) {
  4645. width = size.width;
  4646. height = Math.round(width / engine.getAspectRatio(camera));
  4647. size = { width: width, height: height };
  4648. }
  4649. else if (size.height && !size.width) {
  4650. height = size.height;
  4651. width = Math.round(height * engine.getAspectRatio(camera));
  4652. size = { width: width, height: height };
  4653. }
  4654. else if (!isNaN(size)) {
  4655. height = size;
  4656. width = size;
  4657. }
  4658. else {
  4659. Tools.Error("Invalid 'size' parameter !");
  4660. return;
  4661. }
  4662. var scene = camera.getScene();
  4663. var previousCamera = null;
  4664. if (scene.activeCamera !== camera) {
  4665. previousCamera = scene.activeCamera;
  4666. scene.activeCamera = camera;
  4667. }
  4668. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4669. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4670. texture.renderList = scene.meshes;
  4671. texture.onAfterRender = function () {
  4672. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4673. };
  4674. scene.incrementRenderId();
  4675. texture.render(true);
  4676. texture.dispose();
  4677. if (previousCamera) {
  4678. scene.activeCamera = previousCamera;
  4679. }
  4680. camera.getProjectionMatrix(true); // Force cache refresh;
  4681. };
  4682. // XHR response validator for local file scenario
  4683. Tools.ValidateXHRData = function (xhr, dataType) {
  4684. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4685. if (dataType === void 0) { dataType = 7; }
  4686. try {
  4687. if (dataType & 1) {
  4688. if (xhr.responseText && xhr.responseText.length > 0) {
  4689. return true;
  4690. }
  4691. else if (dataType === 1) {
  4692. return false;
  4693. }
  4694. }
  4695. if (dataType & 2) {
  4696. // Check header width and height since there is no "TGA" magic number
  4697. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4698. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4699. return true;
  4700. }
  4701. else if (dataType === 2) {
  4702. return false;
  4703. }
  4704. }
  4705. if (dataType & 4) {
  4706. // Check for the "DDS" magic number
  4707. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4708. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4709. return true;
  4710. }
  4711. else {
  4712. return false;
  4713. }
  4714. }
  4715. }
  4716. catch (e) {
  4717. }
  4718. return false;
  4719. };
  4720. Object.defineProperty(Tools, "NoneLogLevel", {
  4721. get: function () {
  4722. return Tools._NoneLogLevel;
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. Object.defineProperty(Tools, "MessageLogLevel", {
  4728. get: function () {
  4729. return Tools._MessageLogLevel;
  4730. },
  4731. enumerable: true,
  4732. configurable: true
  4733. });
  4734. Object.defineProperty(Tools, "WarningLogLevel", {
  4735. get: function () {
  4736. return Tools._WarningLogLevel;
  4737. },
  4738. enumerable: true,
  4739. configurable: true
  4740. });
  4741. Object.defineProperty(Tools, "ErrorLogLevel", {
  4742. get: function () {
  4743. return Tools._ErrorLogLevel;
  4744. },
  4745. enumerable: true,
  4746. configurable: true
  4747. });
  4748. Object.defineProperty(Tools, "AllLogLevel", {
  4749. get: function () {
  4750. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4751. },
  4752. enumerable: true,
  4753. configurable: true
  4754. });
  4755. Tools._AddLogEntry = function (entry) {
  4756. Tools._LogCache = entry + Tools._LogCache;
  4757. if (Tools.OnNewCacheEntry) {
  4758. Tools.OnNewCacheEntry(entry);
  4759. }
  4760. };
  4761. Tools._FormatMessage = function (message) {
  4762. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4763. var date = new Date();
  4764. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4765. };
  4766. Tools._LogDisabled = function (message) {
  4767. // nothing to do
  4768. };
  4769. Tools._LogEnabled = function (message) {
  4770. var formattedMessage = Tools._FormatMessage(message);
  4771. console.log("BJS - " + formattedMessage);
  4772. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4773. Tools._AddLogEntry(entry);
  4774. };
  4775. Tools._WarnDisabled = function (message) {
  4776. // nothing to do
  4777. };
  4778. Tools._WarnEnabled = function (message) {
  4779. var formattedMessage = Tools._FormatMessage(message);
  4780. console.warn("BJS - " + formattedMessage);
  4781. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4782. Tools._AddLogEntry(entry);
  4783. };
  4784. Tools._ErrorDisabled = function (message) {
  4785. // nothing to do
  4786. };
  4787. Tools._ErrorEnabled = function (message) {
  4788. Tools.errorsCount++;
  4789. var formattedMessage = Tools._FormatMessage(message);
  4790. console.error("BJS - " + formattedMessage);
  4791. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4792. Tools._AddLogEntry(entry);
  4793. };
  4794. Object.defineProperty(Tools, "LogCache", {
  4795. get: function () {
  4796. return Tools._LogCache;
  4797. },
  4798. enumerable: true,
  4799. configurable: true
  4800. });
  4801. Tools.ClearLogCache = function () {
  4802. Tools._LogCache = "";
  4803. Tools.errorsCount = 0;
  4804. };
  4805. Object.defineProperty(Tools, "LogLevels", {
  4806. set: function (level) {
  4807. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4808. Tools.Log = Tools._LogEnabled;
  4809. }
  4810. else {
  4811. Tools.Log = Tools._LogDisabled;
  4812. }
  4813. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4814. Tools.Warn = Tools._WarnEnabled;
  4815. }
  4816. else {
  4817. Tools.Warn = Tools._WarnDisabled;
  4818. }
  4819. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4820. Tools.Error = Tools._ErrorEnabled;
  4821. }
  4822. else {
  4823. Tools.Error = Tools._ErrorDisabled;
  4824. }
  4825. },
  4826. enumerable: true,
  4827. configurable: true
  4828. });
  4829. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4830. get: function () {
  4831. return Tools._PerformanceNoneLogLevel;
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4837. get: function () {
  4838. return Tools._PerformanceUserMarkLogLevel;
  4839. },
  4840. enumerable: true,
  4841. configurable: true
  4842. });
  4843. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4844. get: function () {
  4845. return Tools._PerformanceConsoleLogLevel;
  4846. },
  4847. enumerable: true,
  4848. configurable: true
  4849. });
  4850. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4851. set: function (level) {
  4852. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4853. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4854. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4855. return;
  4856. }
  4857. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4858. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4859. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4860. return;
  4861. }
  4862. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4863. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4864. },
  4865. enumerable: true,
  4866. configurable: true
  4867. });
  4868. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4869. };
  4870. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4871. };
  4872. Tools._StartUserMark = function (counterName, condition) {
  4873. if (condition === void 0) { condition = true; }
  4874. if (!condition || !Tools._performance.mark) {
  4875. return;
  4876. }
  4877. Tools._performance.mark(counterName + "-Begin");
  4878. };
  4879. Tools._EndUserMark = function (counterName, condition) {
  4880. if (condition === void 0) { condition = true; }
  4881. if (!condition || !Tools._performance.mark) {
  4882. return;
  4883. }
  4884. Tools._performance.mark(counterName + "-End");
  4885. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4886. };
  4887. Tools._StartPerformanceConsole = function (counterName, condition) {
  4888. if (condition === void 0) { condition = true; }
  4889. if (!condition) {
  4890. return;
  4891. }
  4892. Tools._StartUserMark(counterName, condition);
  4893. if (console.time) {
  4894. console.time(counterName);
  4895. }
  4896. };
  4897. Tools._EndPerformanceConsole = function (counterName, condition) {
  4898. if (condition === void 0) { condition = true; }
  4899. if (!condition) {
  4900. return;
  4901. }
  4902. Tools._EndUserMark(counterName, condition);
  4903. if (console.time) {
  4904. console.timeEnd(counterName);
  4905. }
  4906. };
  4907. Object.defineProperty(Tools, "Now", {
  4908. get: function () {
  4909. if (window.performance && window.performance.now) {
  4910. return window.performance.now();
  4911. }
  4912. return new Date().getTime();
  4913. },
  4914. enumerable: true,
  4915. configurable: true
  4916. });
  4917. Tools.BaseUrl = "";
  4918. Tools.CorsBehavior = "anonymous";
  4919. Tools.UseFallbackTexture = true;
  4920. // Logs
  4921. Tools._NoneLogLevel = 0;
  4922. Tools._MessageLogLevel = 1;
  4923. Tools._WarningLogLevel = 2;
  4924. Tools._ErrorLogLevel = 4;
  4925. Tools._LogCache = "";
  4926. Tools.errorsCount = 0;
  4927. Tools.Log = Tools._LogEnabled;
  4928. Tools.Warn = Tools._WarnEnabled;
  4929. Tools.Error = Tools._ErrorEnabled;
  4930. // Performances
  4931. Tools._PerformanceNoneLogLevel = 0;
  4932. Tools._PerformanceUserMarkLogLevel = 1;
  4933. Tools._PerformanceConsoleLogLevel = 2;
  4934. Tools._performance = window.performance;
  4935. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4936. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4937. return Tools;
  4938. }());
  4939. BABYLON.Tools = Tools;
  4940. /**
  4941. * An implementation of a loop for asynchronous functions.
  4942. */
  4943. var AsyncLoop = (function () {
  4944. /**
  4945. * Constroctor.
  4946. * @param iterations the number of iterations.
  4947. * @param _fn the function to run each iteration
  4948. * @param _successCallback the callback that will be called upon succesful execution
  4949. * @param offset starting offset.
  4950. */
  4951. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4952. if (offset === void 0) { offset = 0; }
  4953. this.iterations = iterations;
  4954. this._fn = _fn;
  4955. this._successCallback = _successCallback;
  4956. this.index = offset - 1;
  4957. this._done = false;
  4958. }
  4959. /**
  4960. * Execute the next iteration. Must be called after the last iteration was finished.
  4961. */
  4962. AsyncLoop.prototype.executeNext = function () {
  4963. if (!this._done) {
  4964. if (this.index + 1 < this.iterations) {
  4965. ++this.index;
  4966. this._fn(this);
  4967. }
  4968. else {
  4969. this.breakLoop();
  4970. }
  4971. }
  4972. };
  4973. /**
  4974. * Break the loop and run the success callback.
  4975. */
  4976. AsyncLoop.prototype.breakLoop = function () {
  4977. this._done = true;
  4978. this._successCallback();
  4979. };
  4980. /**
  4981. * Helper function
  4982. */
  4983. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4984. if (offset === void 0) { offset = 0; }
  4985. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4986. loop.executeNext();
  4987. return loop;
  4988. };
  4989. /**
  4990. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4991. * @param iterations total number of iterations
  4992. * @param syncedIterations number of synchronous iterations in each async iteration.
  4993. * @param fn the function to call each iteration.
  4994. * @param callback a success call back that will be called when iterating stops.
  4995. * @param breakFunction a break condition (optional)
  4996. * @param timeout timeout settings for the setTimeout function. default - 0.
  4997. * @constructor
  4998. */
  4999. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5000. if (timeout === void 0) { timeout = 0; }
  5001. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5002. if (breakFunction && breakFunction())
  5003. loop.breakLoop();
  5004. else {
  5005. setTimeout(function () {
  5006. for (var i = 0; i < syncedIterations; ++i) {
  5007. var iteration = (loop.index * syncedIterations) + i;
  5008. if (iteration >= iterations)
  5009. break;
  5010. fn(iteration);
  5011. if (breakFunction && breakFunction()) {
  5012. loop.breakLoop();
  5013. break;
  5014. }
  5015. }
  5016. loop.executeNext();
  5017. }, timeout);
  5018. }
  5019. }, callback);
  5020. };
  5021. return AsyncLoop;
  5022. }());
  5023. BABYLON.AsyncLoop = AsyncLoop;
  5024. })(BABYLON || (BABYLON = {}));
  5025. var BABYLON;
  5026. (function (BABYLON) {
  5027. var Internals;
  5028. (function (Internals) {
  5029. var _AlphaState = (function () {
  5030. function _AlphaState() {
  5031. this._isAlphaBlendDirty = false;
  5032. this._isBlendFunctionParametersDirty = false;
  5033. this._alphaBlend = false;
  5034. this._blendFunctionParameters = new Array(4);
  5035. }
  5036. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5037. get: function () {
  5038. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5039. },
  5040. enumerable: true,
  5041. configurable: true
  5042. });
  5043. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5044. get: function () {
  5045. return this._alphaBlend;
  5046. },
  5047. set: function (value) {
  5048. if (this._alphaBlend === value) {
  5049. return;
  5050. }
  5051. this._alphaBlend = value;
  5052. this._isAlphaBlendDirty = true;
  5053. },
  5054. enumerable: true,
  5055. configurable: true
  5056. });
  5057. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5058. if (this._blendFunctionParameters[0] === value0 &&
  5059. this._blendFunctionParameters[1] === value1 &&
  5060. this._blendFunctionParameters[2] === value2 &&
  5061. this._blendFunctionParameters[3] === value3) {
  5062. return;
  5063. }
  5064. this._blendFunctionParameters[0] = value0;
  5065. this._blendFunctionParameters[1] = value1;
  5066. this._blendFunctionParameters[2] = value2;
  5067. this._blendFunctionParameters[3] = value3;
  5068. this._isBlendFunctionParametersDirty = true;
  5069. };
  5070. _AlphaState.prototype.reset = function () {
  5071. this._alphaBlend = false;
  5072. this._blendFunctionParameters[0] = null;
  5073. this._blendFunctionParameters[1] = null;
  5074. this._blendFunctionParameters[2] = null;
  5075. this._blendFunctionParameters[3] = null;
  5076. this._isAlphaBlendDirty = true;
  5077. this._isBlendFunctionParametersDirty = false;
  5078. };
  5079. _AlphaState.prototype.apply = function (gl) {
  5080. if (!this.isDirty) {
  5081. return;
  5082. }
  5083. // Alpha blend
  5084. if (this._isAlphaBlendDirty) {
  5085. if (this._alphaBlend) {
  5086. gl.enable(gl.BLEND);
  5087. }
  5088. else {
  5089. gl.disable(gl.BLEND);
  5090. }
  5091. this._isAlphaBlendDirty = false;
  5092. }
  5093. // Alpha function
  5094. if (this._isBlendFunctionParametersDirty) {
  5095. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5096. this._isBlendFunctionParametersDirty = false;
  5097. }
  5098. };
  5099. return _AlphaState;
  5100. }());
  5101. Internals._AlphaState = _AlphaState;
  5102. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5103. })(BABYLON || (BABYLON = {}));
  5104. var BABYLON;
  5105. (function (BABYLON) {
  5106. var Internals;
  5107. (function (Internals) {
  5108. var _DepthCullingState = (function () {
  5109. function _DepthCullingState() {
  5110. this._isDepthTestDirty = false;
  5111. this._isDepthMaskDirty = false;
  5112. this._isDepthFuncDirty = false;
  5113. this._isCullFaceDirty = false;
  5114. this._isCullDirty = false;
  5115. this._isZOffsetDirty = false;
  5116. }
  5117. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5118. get: function () {
  5119. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5120. },
  5121. enumerable: true,
  5122. configurable: true
  5123. });
  5124. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5125. get: function () {
  5126. return this._zOffset;
  5127. },
  5128. set: function (value) {
  5129. if (this._zOffset === value) {
  5130. return;
  5131. }
  5132. this._zOffset = value;
  5133. this._isZOffsetDirty = true;
  5134. },
  5135. enumerable: true,
  5136. configurable: true
  5137. });
  5138. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5139. get: function () {
  5140. return this._cullFace;
  5141. },
  5142. set: function (value) {
  5143. if (this._cullFace === value) {
  5144. return;
  5145. }
  5146. this._cullFace = value;
  5147. this._isCullFaceDirty = true;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5153. get: function () {
  5154. return this._cull;
  5155. },
  5156. set: function (value) {
  5157. if (this._cull === value) {
  5158. return;
  5159. }
  5160. this._cull = value;
  5161. this._isCullDirty = true;
  5162. },
  5163. enumerable: true,
  5164. configurable: true
  5165. });
  5166. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5167. get: function () {
  5168. return this._depthFunc;
  5169. },
  5170. set: function (value) {
  5171. if (this._depthFunc === value) {
  5172. return;
  5173. }
  5174. this._depthFunc = value;
  5175. this._isDepthFuncDirty = true;
  5176. },
  5177. enumerable: true,
  5178. configurable: true
  5179. });
  5180. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5181. get: function () {
  5182. return this._depthMask;
  5183. },
  5184. set: function (value) {
  5185. if (this._depthMask === value) {
  5186. return;
  5187. }
  5188. this._depthMask = value;
  5189. this._isDepthMaskDirty = true;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5195. get: function () {
  5196. return this._depthTest;
  5197. },
  5198. set: function (value) {
  5199. if (this._depthTest === value) {
  5200. return;
  5201. }
  5202. this._depthTest = value;
  5203. this._isDepthTestDirty = true;
  5204. },
  5205. enumerable: true,
  5206. configurable: true
  5207. });
  5208. _DepthCullingState.prototype.reset = function () {
  5209. this._depthMask = true;
  5210. this._depthTest = true;
  5211. this._depthFunc = null;
  5212. this._cull = null;
  5213. this._cullFace = null;
  5214. this._zOffset = 0;
  5215. this._isDepthTestDirty = true;
  5216. this._isDepthMaskDirty = true;
  5217. this._isDepthFuncDirty = false;
  5218. this._isCullFaceDirty = false;
  5219. this._isCullDirty = false;
  5220. this._isZOffsetDirty = false;
  5221. };
  5222. _DepthCullingState.prototype.apply = function (gl) {
  5223. if (!this.isDirty) {
  5224. return;
  5225. }
  5226. // Cull
  5227. if (this._isCullDirty) {
  5228. if (this.cull) {
  5229. gl.enable(gl.CULL_FACE);
  5230. }
  5231. else {
  5232. gl.disable(gl.CULL_FACE);
  5233. }
  5234. this._isCullDirty = false;
  5235. }
  5236. // Cull face
  5237. if (this._isCullFaceDirty) {
  5238. gl.cullFace(this.cullFace);
  5239. this._isCullFaceDirty = false;
  5240. }
  5241. // Depth mask
  5242. if (this._isDepthMaskDirty) {
  5243. gl.depthMask(this.depthMask);
  5244. this._isDepthMaskDirty = false;
  5245. }
  5246. // Depth test
  5247. if (this._isDepthTestDirty) {
  5248. if (this.depthTest) {
  5249. gl.enable(gl.DEPTH_TEST);
  5250. }
  5251. else {
  5252. gl.disable(gl.DEPTH_TEST);
  5253. }
  5254. this._isDepthTestDirty = false;
  5255. }
  5256. // Depth func
  5257. if (this._isDepthFuncDirty) {
  5258. gl.depthFunc(this.depthFunc);
  5259. this._isDepthFuncDirty = false;
  5260. }
  5261. // zOffset
  5262. if (this._isZOffsetDirty) {
  5263. if (this.zOffset) {
  5264. gl.enable(gl.POLYGON_OFFSET_FILL);
  5265. gl.polygonOffset(this.zOffset, 0);
  5266. }
  5267. else {
  5268. gl.disable(gl.POLYGON_OFFSET_FILL);
  5269. }
  5270. this._isZOffsetDirty = false;
  5271. }
  5272. };
  5273. return _DepthCullingState;
  5274. }());
  5275. Internals._DepthCullingState = _DepthCullingState;
  5276. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5277. })(BABYLON || (BABYLON = {}));
  5278. var BABYLON;
  5279. (function (BABYLON) {
  5280. var compileShader = function (gl, source, type, defines) {
  5281. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5282. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5283. gl.compileShader(shader);
  5284. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5285. throw new Error(gl.getShaderInfoLog(shader));
  5286. }
  5287. return shader;
  5288. };
  5289. var getWebGLTextureType = function (gl, type) {
  5290. var textureType = gl.UNSIGNED_BYTE;
  5291. if (type === Engine.TEXTURETYPE_FLOAT)
  5292. textureType = gl.FLOAT;
  5293. return textureType;
  5294. };
  5295. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5296. var magFilter = gl.NEAREST;
  5297. var minFilter = gl.NEAREST;
  5298. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5299. magFilter = gl.LINEAR;
  5300. if (generateMipMaps) {
  5301. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5302. }
  5303. else {
  5304. minFilter = gl.LINEAR;
  5305. }
  5306. }
  5307. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5308. magFilter = gl.LINEAR;
  5309. if (generateMipMaps) {
  5310. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5311. }
  5312. else {
  5313. minFilter = gl.LINEAR;
  5314. }
  5315. }
  5316. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5317. magFilter = gl.NEAREST;
  5318. if (generateMipMaps) {
  5319. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5320. }
  5321. else {
  5322. minFilter = gl.NEAREST;
  5323. }
  5324. }
  5325. return {
  5326. min: minFilter,
  5327. mag: magFilter
  5328. };
  5329. };
  5330. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5332. var engine = scene.getEngine();
  5333. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5334. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5335. gl.bindTexture(gl.TEXTURE_2D, texture);
  5336. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5337. texture._baseWidth = width;
  5338. texture._baseHeight = height;
  5339. texture._width = potWidth;
  5340. texture._height = potHeight;
  5341. texture.isReady = true;
  5342. processFunction(potWidth, potHeight);
  5343. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5344. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5346. if (!noMipmap && !isCompressed) {
  5347. gl.generateMipmap(gl.TEXTURE_2D);
  5348. }
  5349. gl.bindTexture(gl.TEXTURE_2D, null);
  5350. engine.resetTextureCache();
  5351. scene._removePendingData(texture);
  5352. if (onLoad) {
  5353. onLoad();
  5354. }
  5355. };
  5356. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5357. var img;
  5358. var onload = function () {
  5359. loadedImages[index] = img;
  5360. loadedImages._internalCount++;
  5361. scene._removePendingData(img);
  5362. if (loadedImages._internalCount === 6) {
  5363. onfinish(loadedImages);
  5364. }
  5365. };
  5366. var onerror = function () {
  5367. scene._removePendingData(img);
  5368. };
  5369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5370. scene._addPendingData(img);
  5371. };
  5372. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5373. var loadedImages = [];
  5374. loadedImages._internalCount = 0;
  5375. for (var index = 0; index < 6; index++) {
  5376. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5377. }
  5378. };
  5379. var EngineCapabilities = (function () {
  5380. function EngineCapabilities() {
  5381. }
  5382. return EngineCapabilities;
  5383. }());
  5384. BABYLON.EngineCapabilities = EngineCapabilities;
  5385. /**
  5386. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5387. */
  5388. var Engine = (function () {
  5389. /**
  5390. * @constructor
  5391. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5392. * @param {boolean} [antialias] - enable antialias
  5393. * @param options - further options to be sent to the getContext function
  5394. */
  5395. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5396. var _this = this;
  5397. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5398. // Public members
  5399. this.isFullscreen = false;
  5400. this.isPointerLock = false;
  5401. this.cullBackFaces = true;
  5402. this.renderEvenInBackground = true;
  5403. // To enable/disable IDB support and avoid XHR on .manifest
  5404. this.enableOfflineSupport = true;
  5405. this.scenes = new Array();
  5406. this._windowIsBackground = false;
  5407. this._webGLVersion = "1.0";
  5408. this._drawCalls = 0;
  5409. this._renderingQueueLaunched = false;
  5410. this._activeRenderLoops = [];
  5411. // FPS
  5412. this.fpsRange = 60;
  5413. this.previousFramesDuration = [];
  5414. this.fps = 60;
  5415. this.deltaTime = 0;
  5416. // States
  5417. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5418. this._alphaState = new BABYLON.Internals._AlphaState();
  5419. this._alphaMode = Engine.ALPHA_DISABLE;
  5420. // Cache
  5421. this._loadedTexturesCache = new Array();
  5422. this._maxTextureChannels = 16;
  5423. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5424. this._compiledEffects = {};
  5425. this._uintIndicesCurrentlySet = false;
  5426. this._renderingCanvas = canvas;
  5427. options = options || {};
  5428. options.antialias = antialias;
  5429. if (options.preserveDrawingBuffer === undefined) {
  5430. options.preserveDrawingBuffer = false;
  5431. }
  5432. // GL
  5433. //try {
  5434. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5435. // if (this._gl) {
  5436. // this._webGLVersion = "2.0";
  5437. // }
  5438. //} catch (e) {
  5439. // // Do nothing
  5440. //}
  5441. if (!this._gl) {
  5442. try {
  5443. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5444. }
  5445. catch (e) {
  5446. throw new Error("WebGL not supported");
  5447. }
  5448. }
  5449. if (!this._gl) {
  5450. throw new Error("WebGL not supported");
  5451. }
  5452. this._onBlur = function () {
  5453. _this._windowIsBackground = true;
  5454. };
  5455. this._onFocus = function () {
  5456. _this._windowIsBackground = false;
  5457. };
  5458. window.addEventListener("blur", this._onBlur);
  5459. window.addEventListener("focus", this._onFocus);
  5460. // Viewport
  5461. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5462. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5463. this.resize();
  5464. // Caps
  5465. this._caps = new EngineCapabilities();
  5466. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5467. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5468. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5469. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5470. // Infos
  5471. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5472. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5473. if (rendererInfo != null) {
  5474. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5475. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5476. }
  5477. if (!this._glVendor) {
  5478. this._glVendor = "Unknown vendor";
  5479. }
  5480. if (!this._glRenderer) {
  5481. this._glRenderer = "Unknown renderer";
  5482. }
  5483. // Extensions
  5484. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5485. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5486. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5487. 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');
  5488. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5489. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5490. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5491. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5492. this._caps.highPrecisionShaderSupported = true;
  5493. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5494. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5495. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5496. if (this._gl.getShaderPrecisionFormat) {
  5497. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5498. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5499. }
  5500. // Depth buffer
  5501. this.setDepthBuffer(true);
  5502. this.setDepthFunctionToLessOrEqual();
  5503. this.setDepthWrite(true);
  5504. // Fullscreen
  5505. this._onFullscreenChange = function () {
  5506. if (document.fullscreen !== undefined) {
  5507. _this.isFullscreen = document.fullscreen;
  5508. }
  5509. else if (document.mozFullScreen !== undefined) {
  5510. _this.isFullscreen = document.mozFullScreen;
  5511. }
  5512. else if (document.webkitIsFullScreen !== undefined) {
  5513. _this.isFullscreen = document.webkitIsFullScreen;
  5514. }
  5515. else if (document.msIsFullScreen !== undefined) {
  5516. _this.isFullscreen = document.msIsFullScreen;
  5517. }
  5518. // Pointer lock
  5519. if (_this.isFullscreen && _this._pointerLockRequested) {
  5520. canvas.requestPointerLock = canvas.requestPointerLock ||
  5521. canvas.msRequestPointerLock ||
  5522. canvas.mozRequestPointerLock ||
  5523. canvas.webkitRequestPointerLock;
  5524. if (canvas.requestPointerLock) {
  5525. canvas.requestPointerLock();
  5526. }
  5527. }
  5528. };
  5529. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5530. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5531. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5532. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5533. // Pointer lock
  5534. this._onPointerLockChange = function () {
  5535. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5536. document.webkitPointerLockElement === canvas ||
  5537. document.msPointerLockElement === canvas ||
  5538. document.pointerLockElement === canvas);
  5539. };
  5540. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5541. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5542. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5543. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5544. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5545. Engine.audioEngine = new BABYLON.AudioEngine();
  5546. }
  5547. //default loading screen
  5548. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5549. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5550. }
  5551. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5552. get: function () {
  5553. return Engine._ALPHA_DISABLE;
  5554. },
  5555. enumerable: true,
  5556. configurable: true
  5557. });
  5558. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5559. get: function () {
  5560. return Engine._ALPHA_ONEONE;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. Object.defineProperty(Engine, "ALPHA_ADD", {
  5566. get: function () {
  5567. return Engine._ALPHA_ADD;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5573. get: function () {
  5574. return Engine._ALPHA_COMBINE;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5580. get: function () {
  5581. return Engine._ALPHA_SUBTRACT;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5587. get: function () {
  5588. return Engine._ALPHA_MULTIPLY;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5594. get: function () {
  5595. return Engine._ALPHA_MAXIMIZED;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5601. get: function () {
  5602. return Engine._DELAYLOADSTATE_NONE;
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5608. get: function () {
  5609. return Engine._DELAYLOADSTATE_LOADED;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5615. get: function () {
  5616. return Engine._DELAYLOADSTATE_LOADING;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5622. get: function () {
  5623. return Engine._DELAYLOADSTATE_NOTLOADED;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5629. get: function () {
  5630. return Engine._TEXTUREFORMAT_ALPHA;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5636. get: function () {
  5637. return Engine._TEXTUREFORMAT_LUMINANCE;
  5638. },
  5639. enumerable: true,
  5640. configurable: true
  5641. });
  5642. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5643. get: function () {
  5644. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5650. get: function () {
  5651. return Engine._TEXTUREFORMAT_RGB;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5657. get: function () {
  5658. return Engine._TEXTUREFORMAT_RGBA;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5664. get: function () {
  5665. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5671. get: function () {
  5672. return Engine._TEXTURETYPE_FLOAT;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(Engine, "Version", {
  5678. get: function () {
  5679. return "2.4.0-alpha";
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5685. get: function () {
  5686. return this._webGLVersion;
  5687. },
  5688. enumerable: true,
  5689. configurable: true
  5690. });
  5691. Engine.prototype._prepareWorkingCanvas = function () {
  5692. if (this._workingCanvas) {
  5693. return;
  5694. }
  5695. this._workingCanvas = document.createElement("canvas");
  5696. this._workingContext = this._workingCanvas.getContext("2d");
  5697. };
  5698. Engine.prototype.resetTextureCache = function () {
  5699. for (var index = 0; index < this._maxTextureChannels; index++) {
  5700. this._activeTexturesCache[index] = null;
  5701. }
  5702. };
  5703. Engine.prototype.getGlInfo = function () {
  5704. return {
  5705. vendor: this._glVendor,
  5706. renderer: this._glRenderer,
  5707. version: this._glVersion
  5708. };
  5709. };
  5710. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5711. if (useScreen === void 0) { useScreen = false; }
  5712. var viewport = camera.viewport;
  5713. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5714. };
  5715. Engine.prototype.getRenderWidth = function (useScreen) {
  5716. if (useScreen === void 0) { useScreen = false; }
  5717. if (!useScreen && this._currentRenderTarget) {
  5718. return this._currentRenderTarget._width;
  5719. }
  5720. return this._renderingCanvas.width;
  5721. };
  5722. Engine.prototype.getRenderHeight = function (useScreen) {
  5723. if (useScreen === void 0) { useScreen = false; }
  5724. if (!useScreen && this._currentRenderTarget) {
  5725. return this._currentRenderTarget._height;
  5726. }
  5727. return this._renderingCanvas.height;
  5728. };
  5729. Engine.prototype.getRenderingCanvas = function () {
  5730. return this._renderingCanvas;
  5731. };
  5732. Engine.prototype.getRenderingCanvasClientRect = function () {
  5733. return this._renderingCanvas.getBoundingClientRect();
  5734. };
  5735. Engine.prototype.setHardwareScalingLevel = function (level) {
  5736. this._hardwareScalingLevel = level;
  5737. this.resize();
  5738. };
  5739. Engine.prototype.getHardwareScalingLevel = function () {
  5740. return this._hardwareScalingLevel;
  5741. };
  5742. Engine.prototype.getLoadedTexturesCache = function () {
  5743. return this._loadedTexturesCache;
  5744. };
  5745. Engine.prototype.getCaps = function () {
  5746. return this._caps;
  5747. };
  5748. Object.defineProperty(Engine.prototype, "drawCalls", {
  5749. get: function () {
  5750. return this._drawCalls;
  5751. },
  5752. enumerable: true,
  5753. configurable: true
  5754. });
  5755. // Methods
  5756. Engine.prototype.resetDrawCalls = function () {
  5757. this._drawCalls = 0;
  5758. };
  5759. Engine.prototype.setDepthFunctionToGreater = function () {
  5760. this._depthCullingState.depthFunc = this._gl.GREATER;
  5761. };
  5762. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5763. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5764. };
  5765. Engine.prototype.setDepthFunctionToLess = function () {
  5766. this._depthCullingState.depthFunc = this._gl.LESS;
  5767. };
  5768. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5769. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5770. };
  5771. /**
  5772. * stop executing a render loop function and remove it from the execution array
  5773. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5774. */
  5775. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5776. if (!renderFunction) {
  5777. this._activeRenderLoops = [];
  5778. return;
  5779. }
  5780. var index = this._activeRenderLoops.indexOf(renderFunction);
  5781. if (index >= 0) {
  5782. this._activeRenderLoops.splice(index, 1);
  5783. }
  5784. };
  5785. Engine.prototype._renderLoop = function () {
  5786. var shouldRender = true;
  5787. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5788. shouldRender = false;
  5789. }
  5790. if (shouldRender) {
  5791. // Start new frame
  5792. this.beginFrame();
  5793. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5794. var renderFunction = this._activeRenderLoops[index];
  5795. renderFunction();
  5796. }
  5797. // Present
  5798. this.endFrame();
  5799. }
  5800. if (this._activeRenderLoops.length > 0) {
  5801. // Register new frame
  5802. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5803. }
  5804. else {
  5805. this._renderingQueueLaunched = false;
  5806. }
  5807. };
  5808. /**
  5809. * Register and execute a render loop. The engine can have more than one render function.
  5810. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5811. * @example
  5812. * engine.runRenderLoop(function () {
  5813. * scene.render()
  5814. * })
  5815. */
  5816. Engine.prototype.runRenderLoop = function (renderFunction) {
  5817. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5818. return;
  5819. }
  5820. this._activeRenderLoops.push(renderFunction);
  5821. if (!this._renderingQueueLaunched) {
  5822. this._renderingQueueLaunched = true;
  5823. this._bindedRenderFunction = this._renderLoop.bind(this);
  5824. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5825. }
  5826. };
  5827. /**
  5828. * Toggle full screen mode.
  5829. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5830. */
  5831. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5832. if (this.isFullscreen) {
  5833. BABYLON.Tools.ExitFullscreen();
  5834. }
  5835. else {
  5836. this._pointerLockRequested = requestPointerLock;
  5837. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5838. }
  5839. };
  5840. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5841. this.applyStates();
  5842. if (backBuffer) {
  5843. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5844. }
  5845. if (depthStencil && this._depthCullingState.depthMask) {
  5846. this._gl.clearDepth(1.0);
  5847. }
  5848. var mode = 0;
  5849. if (backBuffer) {
  5850. mode |= this._gl.COLOR_BUFFER_BIT;
  5851. }
  5852. if (depthStencil && this._depthCullingState.depthMask) {
  5853. mode |= this._gl.DEPTH_BUFFER_BIT;
  5854. }
  5855. this._gl.clear(mode);
  5856. };
  5857. /**
  5858. * Set the WebGL's viewport
  5859. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5860. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5861. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5862. */
  5863. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5864. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5865. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5866. var x = viewport.x || 0;
  5867. var y = viewport.y || 0;
  5868. this._cachedViewport = viewport;
  5869. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5870. };
  5871. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5872. this._cachedViewport = null;
  5873. this._gl.viewport(x, y, width, height);
  5874. };
  5875. Engine.prototype.beginFrame = function () {
  5876. this._measureFps();
  5877. };
  5878. Engine.prototype.endFrame = function () {
  5879. //this.flushFramebuffer();
  5880. };
  5881. /**
  5882. * resize the view according to the canvas' size.
  5883. * @example
  5884. * window.addEventListener("resize", function () {
  5885. * engine.resize();
  5886. * });
  5887. */
  5888. Engine.prototype.resize = function () {
  5889. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5890. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5891. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5892. for (var index = 0; index < this.scenes.length; index++) {
  5893. var scene = this.scenes[index];
  5894. if (scene.debugLayer.isVisible()) {
  5895. scene.debugLayer._syncPositions();
  5896. }
  5897. }
  5898. };
  5899. /**
  5900. * force a specific size of the canvas
  5901. * @param {number} width - the new canvas' width
  5902. * @param {number} height - the new canvas' height
  5903. */
  5904. Engine.prototype.setSize = function (width, height) {
  5905. this._renderingCanvas.width = width;
  5906. this._renderingCanvas.height = height;
  5907. for (var index = 0; index < this.scenes.length; index++) {
  5908. var scene = this.scenes[index];
  5909. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5910. var cam = scene.cameras[camIndex];
  5911. cam._currentRenderId = 0;
  5912. }
  5913. }
  5914. };
  5915. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5916. this._currentRenderTarget = texture;
  5917. var gl = this._gl;
  5918. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5919. if (texture.isCube) {
  5920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5921. }
  5922. else {
  5923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5924. }
  5925. this._gl.viewport(0, 0, texture._width, texture._height);
  5926. this.wipeCaches();
  5927. };
  5928. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5929. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5930. this._currentRenderTarget = null;
  5931. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5932. var gl = this._gl;
  5933. gl.bindTexture(gl.TEXTURE_2D, texture);
  5934. gl.generateMipmap(gl.TEXTURE_2D);
  5935. gl.bindTexture(gl.TEXTURE_2D, null);
  5936. }
  5937. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5938. };
  5939. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5940. if (texture.generateMipMaps) {
  5941. var gl = this._gl;
  5942. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5943. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5944. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5945. }
  5946. };
  5947. Engine.prototype.flushFramebuffer = function () {
  5948. this._gl.flush();
  5949. };
  5950. Engine.prototype.restoreDefaultFramebuffer = function () {
  5951. this._currentRenderTarget = null;
  5952. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5953. this.setViewport(this._cachedViewport);
  5954. this.wipeCaches();
  5955. };
  5956. // VBOs
  5957. Engine.prototype._resetVertexBufferBinding = function () {
  5958. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5959. this._cachedVertexBuffers = null;
  5960. };
  5961. Engine.prototype.createVertexBuffer = function (vertices) {
  5962. var vbo = this._gl.createBuffer();
  5963. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5964. if (vertices instanceof Float32Array) {
  5965. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5966. }
  5967. else {
  5968. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5969. }
  5970. this._resetVertexBufferBinding();
  5971. vbo.references = 1;
  5972. return vbo;
  5973. };
  5974. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5975. var vbo = this._gl.createBuffer();
  5976. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5977. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5978. this._resetVertexBufferBinding();
  5979. vbo.references = 1;
  5980. return vbo;
  5981. };
  5982. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5984. if (offset === undefined) {
  5985. offset = 0;
  5986. }
  5987. if (vertices instanceof Float32Array) {
  5988. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5989. }
  5990. else {
  5991. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5992. }
  5993. this._resetVertexBufferBinding();
  5994. };
  5995. Engine.prototype._resetIndexBufferBinding = function () {
  5996. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5997. this._cachedIndexBuffer = null;
  5998. };
  5999. Engine.prototype.createIndexBuffer = function (indices) {
  6000. var vbo = this._gl.createBuffer();
  6001. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6002. // Check for 32 bits indices
  6003. var arrayBuffer;
  6004. var need32Bits = false;
  6005. if (this._caps.uintIndices) {
  6006. for (var index = 0; index < indices.length; index++) {
  6007. if (indices[index] > 65535) {
  6008. need32Bits = true;
  6009. break;
  6010. }
  6011. }
  6012. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6013. }
  6014. else {
  6015. arrayBuffer = new Uint16Array(indices);
  6016. }
  6017. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6018. this._resetIndexBufferBinding();
  6019. vbo.references = 1;
  6020. vbo.is32Bits = need32Bits;
  6021. return vbo;
  6022. };
  6023. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6024. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6025. this._cachedVertexBuffers = vertexBuffer;
  6026. this._cachedEffectForVertexBuffers = effect;
  6027. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6028. var offset = 0;
  6029. for (var index = 0; index < vertexDeclaration.length; index++) {
  6030. var order = effect.getAttributeLocation(index);
  6031. if (order >= 0) {
  6032. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6033. }
  6034. offset += vertexDeclaration[index] * 4;
  6035. }
  6036. }
  6037. if (this._cachedIndexBuffer !== indexBuffer) {
  6038. this._cachedIndexBuffer = indexBuffer;
  6039. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6040. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6041. }
  6042. };
  6043. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6044. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6045. this._cachedVertexBuffers = vertexBuffers;
  6046. this._cachedEffectForVertexBuffers = effect;
  6047. var attributes = effect.getAttributesNames();
  6048. for (var index = 0; index < attributes.length; index++) {
  6049. var order = effect.getAttributeLocation(index);
  6050. if (order >= 0) {
  6051. var vertexBuffer = vertexBuffers[attributes[index]];
  6052. if (!vertexBuffer) {
  6053. continue;
  6054. }
  6055. var stride = vertexBuffer.getStrideSize();
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6057. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6058. }
  6059. }
  6060. }
  6061. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6062. this._cachedIndexBuffer = indexBuffer;
  6063. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6064. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6065. }
  6066. };
  6067. Engine.prototype._releaseBuffer = function (buffer) {
  6068. buffer.references--;
  6069. if (buffer.references === 0) {
  6070. this._gl.deleteBuffer(buffer);
  6071. return true;
  6072. }
  6073. return false;
  6074. };
  6075. Engine.prototype.createInstancesBuffer = function (capacity) {
  6076. var buffer = this._gl.createBuffer();
  6077. buffer.capacity = capacity;
  6078. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6079. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6080. return buffer;
  6081. };
  6082. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6083. this._gl.deleteBuffer(buffer);
  6084. };
  6085. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6086. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6088. for (var index = 0; index < 4; index++) {
  6089. var offsetLocation = offsetLocations[index];
  6090. this._gl.enableVertexAttribArray(offsetLocation);
  6091. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6092. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6093. }
  6094. };
  6095. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6096. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6097. for (var index = 0; index < 4; index++) {
  6098. var offsetLocation = offsetLocations[index];
  6099. this._gl.disableVertexAttribArray(offsetLocation);
  6100. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6101. }
  6102. };
  6103. Engine.prototype.applyStates = function () {
  6104. this._depthCullingState.apply(this._gl);
  6105. this._alphaState.apply(this._gl);
  6106. };
  6107. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6108. // Apply states
  6109. this.applyStates();
  6110. this._drawCalls++;
  6111. // Render
  6112. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6113. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6114. if (instancesCount) {
  6115. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6116. return;
  6117. }
  6118. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6119. };
  6120. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6121. // Apply states
  6122. this.applyStates();
  6123. this._drawCalls++;
  6124. if (instancesCount) {
  6125. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6126. return;
  6127. }
  6128. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6129. };
  6130. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6131. // Apply states
  6132. this.applyStates();
  6133. this._drawCalls++;
  6134. if (instancesCount) {
  6135. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6136. return;
  6137. }
  6138. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6139. };
  6140. // Shaders
  6141. Engine.prototype._releaseEffect = function (effect) {
  6142. if (this._compiledEffects[effect._key]) {
  6143. delete this._compiledEffects[effect._key];
  6144. if (effect.getProgram()) {
  6145. this._gl.deleteProgram(effect.getProgram());
  6146. }
  6147. }
  6148. };
  6149. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6150. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6151. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6152. var name = vertex + "+" + fragment + "@" + defines;
  6153. if (this._compiledEffects[name]) {
  6154. return this._compiledEffects[name];
  6155. }
  6156. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6157. effect._key = name;
  6158. this._compiledEffects[name] = effect;
  6159. return effect;
  6160. };
  6161. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6162. if (uniformsNames === void 0) { uniformsNames = []; }
  6163. if (samplers === void 0) { samplers = []; }
  6164. if (defines === void 0) { defines = ""; }
  6165. return this.createEffect({
  6166. vertex: "particles",
  6167. fragmentElement: fragmentName
  6168. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6169. };
  6170. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6171. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6172. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6173. var shaderProgram = this._gl.createProgram();
  6174. this._gl.attachShader(shaderProgram, vertexShader);
  6175. this._gl.attachShader(shaderProgram, fragmentShader);
  6176. this._gl.linkProgram(shaderProgram);
  6177. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6178. if (!linked) {
  6179. var error = this._gl.getProgramInfoLog(shaderProgram);
  6180. if (error) {
  6181. throw new Error(error);
  6182. }
  6183. }
  6184. this._gl.deleteShader(vertexShader);
  6185. this._gl.deleteShader(fragmentShader);
  6186. return shaderProgram;
  6187. };
  6188. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6189. var results = [];
  6190. for (var index = 0; index < uniformsNames.length; index++) {
  6191. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6192. }
  6193. return results;
  6194. };
  6195. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6196. var results = [];
  6197. for (var index = 0; index < attributesNames.length; index++) {
  6198. try {
  6199. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6200. }
  6201. catch (e) {
  6202. results.push(-1);
  6203. }
  6204. }
  6205. return results;
  6206. };
  6207. Engine.prototype.enableEffect = function (effect) {
  6208. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6209. if (effect && effect.onBind) {
  6210. effect.onBind(effect);
  6211. }
  6212. return;
  6213. }
  6214. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6215. // Use program
  6216. this._gl.useProgram(effect.getProgram());
  6217. for (var i in this._vertexAttribArrays) {
  6218. //make sure this is a number)
  6219. var iAsNumber = +i;
  6220. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6221. continue;
  6222. }
  6223. this._vertexAttribArrays[iAsNumber] = false;
  6224. this._gl.disableVertexAttribArray(iAsNumber);
  6225. }
  6226. var attributesCount = effect.getAttributesCount();
  6227. for (var index = 0; index < attributesCount; index++) {
  6228. // Attributes
  6229. var order = effect.getAttributeLocation(index);
  6230. if (order >= 0) {
  6231. this._vertexAttribArrays[order] = true;
  6232. this._gl.enableVertexAttribArray(order);
  6233. }
  6234. }
  6235. this._currentEffect = effect;
  6236. if (effect.onBind) {
  6237. effect.onBind(effect);
  6238. }
  6239. };
  6240. Engine.prototype.setArray = function (uniform, array) {
  6241. if (!uniform)
  6242. return;
  6243. this._gl.uniform1fv(uniform, array);
  6244. };
  6245. Engine.prototype.setArray2 = function (uniform, array) {
  6246. if (!uniform || array.length % 2 !== 0)
  6247. return;
  6248. this._gl.uniform2fv(uniform, array);
  6249. };
  6250. Engine.prototype.setArray3 = function (uniform, array) {
  6251. if (!uniform || array.length % 3 !== 0)
  6252. return;
  6253. this._gl.uniform3fv(uniform, array);
  6254. };
  6255. Engine.prototype.setArray4 = function (uniform, array) {
  6256. if (!uniform || array.length % 4 !== 0)
  6257. return;
  6258. this._gl.uniform4fv(uniform, array);
  6259. };
  6260. Engine.prototype.setMatrices = function (uniform, matrices) {
  6261. if (!uniform)
  6262. return;
  6263. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6264. };
  6265. Engine.prototype.setMatrix = function (uniform, matrix) {
  6266. if (!uniform)
  6267. return;
  6268. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6269. };
  6270. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6271. if (!uniform)
  6272. return;
  6273. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6274. };
  6275. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6276. if (!uniform)
  6277. return;
  6278. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6279. };
  6280. Engine.prototype.setFloat = function (uniform, value) {
  6281. if (!uniform)
  6282. return;
  6283. this._gl.uniform1f(uniform, value);
  6284. };
  6285. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6286. if (!uniform)
  6287. return;
  6288. this._gl.uniform2f(uniform, x, y);
  6289. };
  6290. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6291. if (!uniform)
  6292. return;
  6293. this._gl.uniform3f(uniform, x, y, z);
  6294. };
  6295. Engine.prototype.setBool = function (uniform, bool) {
  6296. if (!uniform)
  6297. return;
  6298. this._gl.uniform1i(uniform, bool);
  6299. };
  6300. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6301. if (!uniform)
  6302. return;
  6303. this._gl.uniform4f(uniform, x, y, z, w);
  6304. };
  6305. Engine.prototype.setColor3 = function (uniform, color3) {
  6306. if (!uniform)
  6307. return;
  6308. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6309. };
  6310. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6311. if (!uniform)
  6312. return;
  6313. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6314. };
  6315. // States
  6316. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6317. if (zOffset === void 0) { zOffset = 0; }
  6318. if (reverseSide === void 0) { reverseSide = false; }
  6319. // Culling
  6320. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6321. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6322. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6323. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6324. if (culling) {
  6325. this._depthCullingState.cullFace = cullFace;
  6326. this._depthCullingState.cull = true;
  6327. }
  6328. else {
  6329. this._depthCullingState.cull = false;
  6330. }
  6331. }
  6332. // Z offset
  6333. this._depthCullingState.zOffset = zOffset;
  6334. };
  6335. Engine.prototype.setDepthBuffer = function (enable) {
  6336. this._depthCullingState.depthTest = enable;
  6337. };
  6338. Engine.prototype.getDepthWrite = function () {
  6339. return this._depthCullingState.depthMask;
  6340. };
  6341. Engine.prototype.setDepthWrite = function (enable) {
  6342. this._depthCullingState.depthMask = enable;
  6343. };
  6344. Engine.prototype.setColorWrite = function (enable) {
  6345. this._gl.colorMask(enable, enable, enable, enable);
  6346. };
  6347. Engine.prototype.setAlphaMode = function (mode) {
  6348. if (this._alphaMode === mode) {
  6349. return;
  6350. }
  6351. switch (mode) {
  6352. case Engine.ALPHA_DISABLE:
  6353. this.setDepthWrite(true);
  6354. this._alphaState.alphaBlend = false;
  6355. break;
  6356. case Engine.ALPHA_COMBINE:
  6357. this.setDepthWrite(false);
  6358. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6359. this._alphaState.alphaBlend = true;
  6360. break;
  6361. case Engine.ALPHA_ONEONE:
  6362. this.setDepthWrite(false);
  6363. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6364. this._alphaState.alphaBlend = true;
  6365. break;
  6366. case Engine.ALPHA_ADD:
  6367. this.setDepthWrite(false);
  6368. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6369. this._alphaState.alphaBlend = true;
  6370. break;
  6371. case Engine.ALPHA_SUBTRACT:
  6372. this.setDepthWrite(false);
  6373. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6374. this._alphaState.alphaBlend = true;
  6375. break;
  6376. case Engine.ALPHA_MULTIPLY:
  6377. this.setDepthWrite(false);
  6378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6379. this._alphaState.alphaBlend = true;
  6380. break;
  6381. case Engine.ALPHA_MAXIMIZED:
  6382. this.setDepthWrite(false);
  6383. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6384. this._alphaState.alphaBlend = true;
  6385. break;
  6386. }
  6387. this._alphaMode = mode;
  6388. };
  6389. Engine.prototype.getAlphaMode = function () {
  6390. return this._alphaMode;
  6391. };
  6392. Engine.prototype.setAlphaTesting = function (enable) {
  6393. this._alphaTest = enable;
  6394. };
  6395. Engine.prototype.getAlphaTesting = function () {
  6396. return this._alphaTest;
  6397. };
  6398. // Textures
  6399. Engine.prototype.wipeCaches = function () {
  6400. this.resetTextureCache();
  6401. this._currentEffect = null;
  6402. this._depthCullingState.reset();
  6403. this._alphaState.reset();
  6404. this._cachedVertexBuffers = null;
  6405. this._cachedIndexBuffer = null;
  6406. this._cachedEffectForVertexBuffers = null;
  6407. };
  6408. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6409. var gl = this._gl;
  6410. gl.bindTexture(gl.TEXTURE_2D, texture);
  6411. var magFilter = gl.NEAREST;
  6412. var minFilter = gl.NEAREST;
  6413. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6414. magFilter = gl.LINEAR;
  6415. minFilter = gl.LINEAR;
  6416. }
  6417. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6418. magFilter = gl.LINEAR;
  6419. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6420. }
  6421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6423. gl.bindTexture(gl.TEXTURE_2D, null);
  6424. texture.samplingMode = samplingMode;
  6425. };
  6426. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6427. var _this = this;
  6428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6429. if (onLoad === void 0) { onLoad = null; }
  6430. if (onError === void 0) { onError = null; }
  6431. if (buffer === void 0) { buffer = null; }
  6432. var texture = this._gl.createTexture();
  6433. var extension;
  6434. var fromData = false;
  6435. if (url.substr(0, 5) === "data:") {
  6436. fromData = true;
  6437. }
  6438. if (!fromData)
  6439. extension = url.substr(url.length - 4, 4).toLowerCase();
  6440. else {
  6441. var oldUrl = url;
  6442. fromData = oldUrl.split(':');
  6443. url = oldUrl;
  6444. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6445. }
  6446. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6447. var isTGA = (extension === ".tga");
  6448. scene._addPendingData(texture);
  6449. texture.url = url;
  6450. texture.noMipmap = noMipmap;
  6451. texture.references = 1;
  6452. texture.samplingMode = samplingMode;
  6453. this._loadedTexturesCache.push(texture);
  6454. var onerror = function () {
  6455. scene._removePendingData(texture);
  6456. if (onError) {
  6457. onError();
  6458. }
  6459. };
  6460. var callback;
  6461. if (isTGA) {
  6462. callback = function (arrayBuffer) {
  6463. var data = new Uint8Array(arrayBuffer);
  6464. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6465. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6466. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6467. }, onLoad, samplingMode);
  6468. };
  6469. if (!(fromData instanceof Array))
  6470. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6471. callback(arrayBuffer);
  6472. }, onerror, scene.database, true);
  6473. else
  6474. callback(buffer);
  6475. }
  6476. else if (isDDS) {
  6477. callback = function (data) {
  6478. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6479. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6480. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6481. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6482. }, onLoad, samplingMode);
  6483. };
  6484. if (!(fromData instanceof Array))
  6485. BABYLON.Tools.LoadFile(url, function (data) {
  6486. callback(data);
  6487. }, onerror, scene.database, true);
  6488. else
  6489. callback(buffer);
  6490. }
  6491. else {
  6492. var onload = function (img) {
  6493. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6494. var isPot = (img.width === potWidth && img.height === potHeight);
  6495. if (!isPot) {
  6496. _this._prepareWorkingCanvas();
  6497. _this._workingCanvas.width = potWidth;
  6498. _this._workingCanvas.height = potHeight;
  6499. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6500. _this._workingContext.imageSmoothingEnabled = false;
  6501. _this._workingContext.mozImageSmoothingEnabled = false;
  6502. _this._workingContext.oImageSmoothingEnabled = false;
  6503. _this._workingContext.webkitImageSmoothingEnabled = false;
  6504. _this._workingContext.msImageSmoothingEnabled = false;
  6505. }
  6506. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6507. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6508. _this._workingContext.imageSmoothingEnabled = true;
  6509. _this._workingContext.mozImageSmoothingEnabled = true;
  6510. _this._workingContext.oImageSmoothingEnabled = true;
  6511. _this._workingContext.webkitImageSmoothingEnabled = true;
  6512. _this._workingContext.msImageSmoothingEnabled = true;
  6513. }
  6514. }
  6515. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6516. }, onLoad, samplingMode);
  6517. };
  6518. if (!(fromData instanceof Array))
  6519. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6520. else
  6521. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6522. }
  6523. return texture;
  6524. };
  6525. Engine.prototype._getInternalFormat = function (format) {
  6526. var internalFormat = this._gl.RGBA;
  6527. switch (format) {
  6528. case Engine.TEXTUREFORMAT_ALPHA:
  6529. internalFormat = this._gl.ALPHA;
  6530. break;
  6531. case Engine.TEXTUREFORMAT_LUMINANCE:
  6532. internalFormat = this._gl.LUMINANCE;
  6533. break;
  6534. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6535. internalFormat = this._gl.LUMINANCE_ALPHA;
  6536. break;
  6537. case Engine.TEXTUREFORMAT_RGB:
  6538. internalFormat = this._gl.RGB;
  6539. break;
  6540. case Engine.TEXTUREFORMAT_RGBA:
  6541. internalFormat = this._gl.RGBA;
  6542. break;
  6543. }
  6544. return internalFormat;
  6545. };
  6546. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6547. if (compression === void 0) { compression = null; }
  6548. var internalFormat = this._getInternalFormat(format);
  6549. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6550. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6551. if (compression) {
  6552. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6553. }
  6554. else {
  6555. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6556. }
  6557. if (texture.generateMipMaps) {
  6558. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6559. }
  6560. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6561. this.resetTextureCache();
  6562. texture.isReady = true;
  6563. };
  6564. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6565. if (compression === void 0) { compression = null; }
  6566. var texture = this._gl.createTexture();
  6567. texture._baseWidth = width;
  6568. texture._baseHeight = height;
  6569. texture._width = width;
  6570. texture._height = height;
  6571. texture.references = 1;
  6572. this.updateRawTexture(texture, data, format, invertY, compression);
  6573. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6574. // Filters
  6575. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6576. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6577. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6578. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6579. texture.samplingMode = samplingMode;
  6580. this._loadedTexturesCache.push(texture);
  6581. return texture;
  6582. };
  6583. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6584. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6585. var texture = this._gl.createTexture();
  6586. texture._baseWidth = width;
  6587. texture._baseHeight = height;
  6588. if (forceExponantOfTwo) {
  6589. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6590. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6591. }
  6592. this.resetTextureCache();
  6593. texture._width = width;
  6594. texture._height = height;
  6595. texture.isReady = false;
  6596. texture.generateMipMaps = generateMipMaps;
  6597. texture.references = 1;
  6598. texture.samplingMode = samplingMode;
  6599. this.updateTextureSamplingMode(samplingMode, texture);
  6600. this._loadedTexturesCache.push(texture);
  6601. return texture;
  6602. };
  6603. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6604. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6605. if (texture.isCube) {
  6606. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6607. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6608. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6609. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6610. }
  6611. else {
  6612. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6614. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6615. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6616. }
  6617. };
  6618. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6619. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6620. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6621. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6622. if (texture.generateMipMaps) {
  6623. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6624. }
  6625. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6626. this.resetTextureCache();
  6627. texture.isReady = true;
  6628. };
  6629. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6630. if (texture._isDisabled) {
  6631. return;
  6632. }
  6633. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6634. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6635. try {
  6636. // Testing video texture support
  6637. if (this._videoTextureSupported === undefined) {
  6638. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6639. if (this._gl.getError() !== 0) {
  6640. this._videoTextureSupported = false;
  6641. }
  6642. else {
  6643. this._videoTextureSupported = true;
  6644. }
  6645. }
  6646. // Copy video through the current working canvas if video texture is not supported
  6647. if (!this._videoTextureSupported) {
  6648. if (!texture._workingCanvas) {
  6649. texture._workingCanvas = document.createElement("canvas");
  6650. texture._workingContext = texture._workingCanvas.getContext("2d");
  6651. texture._workingCanvas.width = texture._width;
  6652. texture._workingCanvas.height = texture._height;
  6653. }
  6654. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6655. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6656. }
  6657. else {
  6658. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6659. }
  6660. if (texture.generateMipMaps) {
  6661. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6662. }
  6663. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6664. this.resetTextureCache();
  6665. texture.isReady = true;
  6666. }
  6667. catch (ex) {
  6668. // Something unexpected
  6669. // Let's disable the texture
  6670. texture._isDisabled = true;
  6671. }
  6672. };
  6673. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6674. // old version had a "generateMipMaps" arg instead of options.
  6675. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6676. // in the same way, generateDepthBuffer is defaulted to true
  6677. var generateMipMaps = false;
  6678. var generateDepthBuffer = true;
  6679. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6680. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6681. if (options !== undefined) {
  6682. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6683. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6684. type = options.type === undefined ? type : options.type;
  6685. if (options.samplingMode !== undefined) {
  6686. samplingMode = options.samplingMode;
  6687. }
  6688. if (type === Engine.TEXTURETYPE_FLOAT) {
  6689. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6690. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6691. }
  6692. }
  6693. var gl = this._gl;
  6694. var texture = gl.createTexture();
  6695. gl.bindTexture(gl.TEXTURE_2D, texture);
  6696. var width = size.width || size;
  6697. var height = size.height || size;
  6698. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6699. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6700. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6701. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6702. }
  6703. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6704. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6705. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6706. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6707. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6708. var depthBuffer;
  6709. // Create the depth buffer
  6710. if (generateDepthBuffer) {
  6711. depthBuffer = gl.createRenderbuffer();
  6712. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6713. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6714. }
  6715. // Create the framebuffer
  6716. var framebuffer = gl.createFramebuffer();
  6717. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6718. if (generateDepthBuffer) {
  6719. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6720. }
  6721. if (generateMipMaps) {
  6722. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6723. }
  6724. // Unbind
  6725. gl.bindTexture(gl.TEXTURE_2D, null);
  6726. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6727. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6728. texture._framebuffer = framebuffer;
  6729. if (generateDepthBuffer) {
  6730. texture._depthBuffer = depthBuffer;
  6731. }
  6732. texture._width = width;
  6733. texture._height = height;
  6734. texture.isReady = true;
  6735. texture.generateMipMaps = generateMipMaps;
  6736. texture.references = 1;
  6737. texture.samplingMode = samplingMode;
  6738. this.resetTextureCache();
  6739. this._loadedTexturesCache.push(texture);
  6740. return texture;
  6741. };
  6742. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6743. var gl = this._gl;
  6744. var texture = gl.createTexture();
  6745. var generateMipMaps = true;
  6746. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6747. if (options !== undefined) {
  6748. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6749. if (options.samplingMode !== undefined) {
  6750. samplingMode = options.samplingMode;
  6751. }
  6752. }
  6753. texture.isCube = true;
  6754. texture.references = 1;
  6755. texture.generateMipMaps = generateMipMaps;
  6756. texture.references = 1;
  6757. texture.samplingMode = samplingMode;
  6758. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6759. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6760. for (var face = 0; face < 6; face++) {
  6761. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6762. }
  6763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6767. // Create the depth buffer
  6768. var depthBuffer = gl.createRenderbuffer();
  6769. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6770. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6771. // Create the framebuffer
  6772. var framebuffer = gl.createFramebuffer();
  6773. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6774. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6775. // Mipmaps
  6776. if (texture.generateMipMaps) {
  6777. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6778. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6779. }
  6780. // Unbind
  6781. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6782. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6783. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6784. texture._framebuffer = framebuffer;
  6785. texture._depthBuffer = depthBuffer;
  6786. this.resetTextureCache();
  6787. texture._width = size;
  6788. texture._height = size;
  6789. texture.isReady = true;
  6790. return texture;
  6791. };
  6792. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6793. var _this = this;
  6794. var gl = this._gl;
  6795. var texture = gl.createTexture();
  6796. texture.isCube = true;
  6797. texture.url = rootUrl;
  6798. texture.references = 1;
  6799. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6800. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6801. if (isDDS) {
  6802. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6803. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6804. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6805. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6806. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6807. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6808. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6809. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6810. }
  6811. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6813. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6815. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6816. _this.resetTextureCache();
  6817. texture._width = info.width;
  6818. texture._height = info.height;
  6819. texture.isReady = true;
  6820. }, null, null, true);
  6821. }
  6822. else {
  6823. cascadeLoad(rootUrl, scene, function (imgs) {
  6824. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6825. var height = width;
  6826. _this._prepareWorkingCanvas();
  6827. _this._workingCanvas.width = width;
  6828. _this._workingCanvas.height = height;
  6829. var faces = [
  6830. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6831. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6832. ];
  6833. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6834. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6835. for (var index = 0; index < faces.length; index++) {
  6836. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6837. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6838. }
  6839. if (!noMipmap) {
  6840. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6841. }
  6842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6846. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6847. _this.resetTextureCache();
  6848. texture._width = width;
  6849. texture._height = height;
  6850. texture.isReady = true;
  6851. }, files);
  6852. }
  6853. return texture;
  6854. };
  6855. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6856. var _this = this;
  6857. var gl = this._gl;
  6858. var texture = gl.createTexture();
  6859. scene._addPendingData(texture);
  6860. texture.isCube = true;
  6861. texture.references = 1;
  6862. texture.url = url;
  6863. var internalFormat = this._getInternalFormat(format);
  6864. var textureType = gl.UNSIGNED_BYTE;
  6865. if (type === Engine.TEXTURETYPE_FLOAT) {
  6866. textureType = gl.FLOAT;
  6867. }
  6868. var width = size;
  6869. var height = width;
  6870. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6871. texture._width = width;
  6872. texture._height = height;
  6873. var onerror = function () {
  6874. scene._removePendingData(texture);
  6875. };
  6876. var internalCallback = function (data) {
  6877. var rgbeDataArrays = callback(data);
  6878. var facesIndex = [
  6879. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6880. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6881. ];
  6882. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6883. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6884. if (!noMipmap && isPot) {
  6885. if (mipmmapGenerator) {
  6886. var arrayTemp = [];
  6887. // Data are known to be in +X +Y +Z -X -Y -Z
  6888. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6889. arrayTemp.push(rgbeDataArrays[0]); // +X
  6890. arrayTemp.push(rgbeDataArrays[3]); // -X
  6891. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6892. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6893. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6894. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6895. var mipData = mipmmapGenerator(arrayTemp);
  6896. for (var level = 0; level < mipData.length; level++) {
  6897. var mipSize = width >> level;
  6898. // mipData is order in +X -X +Y -Y +Z -Z
  6899. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6900. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6901. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6902. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6903. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6904. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6905. }
  6906. }
  6907. else {
  6908. // Data are known to be in +X +Y +Z -X -Y -Z
  6909. for (var index = 0; index < facesIndex.length; index++) {
  6910. var faceData = rgbeDataArrays[index];
  6911. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6912. }
  6913. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6914. }
  6915. }
  6916. else {
  6917. noMipmap = true;
  6918. }
  6919. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6922. }
  6923. else {
  6924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6926. }
  6927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6929. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6930. texture.isReady = true;
  6931. _this.resetTextureCache();
  6932. scene._removePendingData(texture);
  6933. };
  6934. BABYLON.Tools.LoadFile(url, function (data) {
  6935. internalCallback(data);
  6936. }, onerror, scene.database, true);
  6937. return texture;
  6938. };
  6939. ;
  6940. Engine.prototype._releaseTexture = function (texture) {
  6941. var gl = this._gl;
  6942. if (texture._framebuffer) {
  6943. gl.deleteFramebuffer(texture._framebuffer);
  6944. }
  6945. if (texture._depthBuffer) {
  6946. gl.deleteRenderbuffer(texture._depthBuffer);
  6947. }
  6948. gl.deleteTexture(texture);
  6949. // Unbind channels
  6950. this.unbindAllTextures();
  6951. var index = this._loadedTexturesCache.indexOf(texture);
  6952. if (index !== -1) {
  6953. this._loadedTexturesCache.splice(index, 1);
  6954. }
  6955. };
  6956. Engine.prototype.bindSamplers = function (effect) {
  6957. this._gl.useProgram(effect.getProgram());
  6958. var samplers = effect.getSamplers();
  6959. for (var index = 0; index < samplers.length; index++) {
  6960. var uniform = effect.getUniform(samplers[index]);
  6961. this._gl.uniform1i(uniform, index);
  6962. }
  6963. this._currentEffect = null;
  6964. };
  6965. Engine.prototype._bindTexture = function (channel, texture) {
  6966. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6967. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6968. this._activeTexturesCache[channel] = null;
  6969. };
  6970. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6971. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6972. };
  6973. Engine.prototype.unbindAllTextures = function () {
  6974. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6975. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6976. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6977. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6978. this._activeTexturesCache[channel] = null;
  6979. }
  6980. };
  6981. Engine.prototype.setTexture = function (channel, texture) {
  6982. if (channel < 0) {
  6983. return;
  6984. }
  6985. // Not ready?
  6986. if (!texture || !texture.isReady()) {
  6987. if (this._activeTexturesCache[channel] != null) {
  6988. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6989. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6990. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6991. this._activeTexturesCache[channel] = null;
  6992. }
  6993. return;
  6994. }
  6995. // Video
  6996. var alreadyActivated = false;
  6997. if (texture instanceof BABYLON.VideoTexture) {
  6998. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6999. alreadyActivated = true;
  7000. texture.update();
  7001. }
  7002. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7003. texture.delayLoad();
  7004. return;
  7005. }
  7006. if (this._activeTexturesCache[channel] === texture) {
  7007. return;
  7008. }
  7009. this._activeTexturesCache[channel] = texture;
  7010. var internalTexture = texture.getInternalTexture();
  7011. if (!alreadyActivated) {
  7012. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7013. }
  7014. if (internalTexture.isCube) {
  7015. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7016. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7017. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7018. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7019. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7020. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7021. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7022. }
  7023. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7024. }
  7025. else {
  7026. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7027. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7028. internalTexture._cachedWrapU = texture.wrapU;
  7029. switch (texture.wrapU) {
  7030. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7032. break;
  7033. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7034. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7035. break;
  7036. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7037. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7038. break;
  7039. }
  7040. }
  7041. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7042. internalTexture._cachedWrapV = texture.wrapV;
  7043. switch (texture.wrapV) {
  7044. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7045. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7046. break;
  7047. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7048. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7049. break;
  7050. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7051. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7052. break;
  7053. }
  7054. }
  7055. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7056. }
  7057. };
  7058. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7059. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7060. var value = texture.anisotropicFilteringLevel;
  7061. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7062. value = 1;
  7063. }
  7064. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7065. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7066. texture._cachedAnisotropicFilteringLevel = value;
  7067. }
  7068. };
  7069. Engine.prototype.readPixels = function (x, y, width, height) {
  7070. var data = new Uint8Array(height * width * 4);
  7071. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7072. return data;
  7073. };
  7074. Engine.prototype.releaseInternalTexture = function (texture) {
  7075. if (!texture) {
  7076. return;
  7077. }
  7078. texture.references--;
  7079. // Final reference ?
  7080. if (texture.references === 0) {
  7081. var texturesCache = this.getLoadedTexturesCache();
  7082. var index = texturesCache.indexOf(texture);
  7083. if (index > -1) {
  7084. texturesCache.splice(index, 1);
  7085. }
  7086. this._releaseTexture(texture);
  7087. }
  7088. };
  7089. // Dispose
  7090. Engine.prototype.dispose = function () {
  7091. this.hideLoadingUI();
  7092. this.stopRenderLoop();
  7093. // Release scenes
  7094. while (this.scenes.length) {
  7095. this.scenes[0].dispose();
  7096. }
  7097. // Release audio engine
  7098. Engine.audioEngine.dispose();
  7099. // Release effects
  7100. for (var name in this._compiledEffects) {
  7101. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7102. }
  7103. // Unbind
  7104. for (var i in this._vertexAttribArrays) {
  7105. //making sure this is a string
  7106. var iAsNumber = +i;
  7107. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7108. continue;
  7109. }
  7110. this._gl.disableVertexAttribArray(iAsNumber);
  7111. }
  7112. this._gl = null;
  7113. // Events
  7114. window.removeEventListener("blur", this._onBlur);
  7115. window.removeEventListener("focus", this._onFocus);
  7116. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7117. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7118. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7119. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7120. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7121. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7122. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7123. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7124. };
  7125. // Loading screen
  7126. Engine.prototype.displayLoadingUI = function () {
  7127. this._loadingScreen.displayLoadingUI();
  7128. };
  7129. Engine.prototype.hideLoadingUI = function () {
  7130. this._loadingScreen.hideLoadingUI();
  7131. };
  7132. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7133. get: function () {
  7134. return this._loadingScreen;
  7135. },
  7136. set: function (loadingScreen) {
  7137. this._loadingScreen = loadingScreen;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7143. set: function (text) {
  7144. this._loadingScreen.loadingUIText = text;
  7145. },
  7146. enumerable: true,
  7147. configurable: true
  7148. });
  7149. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7150. set: function (color) {
  7151. this._loadingScreen.loadingUIBackgroundColor = color;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. // FPS
  7157. Engine.prototype.getFps = function () {
  7158. return this.fps;
  7159. };
  7160. Engine.prototype.getDeltaTime = function () {
  7161. return this.deltaTime;
  7162. };
  7163. Engine.prototype._measureFps = function () {
  7164. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7165. var length = this.previousFramesDuration.length;
  7166. if (length >= 2) {
  7167. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7168. }
  7169. if (length >= this.fpsRange) {
  7170. if (length > this.fpsRange) {
  7171. this.previousFramesDuration.splice(0, 1);
  7172. length = this.previousFramesDuration.length;
  7173. }
  7174. var sum = 0;
  7175. for (var id = 0; id < length - 1; id++) {
  7176. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7177. }
  7178. this.fps = 1000.0 / (sum / (length - 1));
  7179. }
  7180. };
  7181. // Statics
  7182. Engine.isSupported = function () {
  7183. try {
  7184. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7185. if (navigator.isCocoonJS) {
  7186. return true;
  7187. }
  7188. var tempcanvas = document.createElement("canvas");
  7189. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7190. return gl != null && !!window.WebGLRenderingContext;
  7191. }
  7192. catch (e) {
  7193. return false;
  7194. }
  7195. };
  7196. // Const statics
  7197. Engine._ALPHA_DISABLE = 0;
  7198. Engine._ALPHA_ADD = 1;
  7199. Engine._ALPHA_COMBINE = 2;
  7200. Engine._ALPHA_SUBTRACT = 3;
  7201. Engine._ALPHA_MULTIPLY = 4;
  7202. Engine._ALPHA_MAXIMIZED = 5;
  7203. Engine._ALPHA_ONEONE = 6;
  7204. Engine._DELAYLOADSTATE_NONE = 0;
  7205. Engine._DELAYLOADSTATE_LOADED = 1;
  7206. Engine._DELAYLOADSTATE_LOADING = 2;
  7207. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7208. Engine._TEXTUREFORMAT_ALPHA = 0;
  7209. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7210. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7211. Engine._TEXTUREFORMAT_RGB = 4;
  7212. Engine._TEXTUREFORMAT_RGBA = 5;
  7213. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7214. Engine._TEXTURETYPE_FLOAT = 1;
  7215. // Updatable statics so stick with vars here
  7216. Engine.CollisionsEpsilon = 0.001;
  7217. Engine.CodeRepository = "src/";
  7218. Engine.ShadersRepository = "src/Shaders/";
  7219. return Engine;
  7220. }());
  7221. BABYLON.Engine = Engine;
  7222. })(BABYLON || (BABYLON = {}));
  7223. var BABYLON;
  7224. (function (BABYLON) {
  7225. /**
  7226. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7227. */
  7228. var Node = (function () {
  7229. /**
  7230. * @constructor
  7231. * @param {string} name - the name and id to be given to this node
  7232. * @param {BABYLON.Scene} the scene this node will be added to
  7233. */
  7234. function Node(name, scene) {
  7235. this.state = "";
  7236. this.animations = new Array();
  7237. this._ranges = {};
  7238. this._childrenFlag = -1;
  7239. this._isEnabled = true;
  7240. this._isReady = true;
  7241. this._currentRenderId = -1;
  7242. this._parentRenderId = -1;
  7243. this.name = name;
  7244. this.id = name;
  7245. this._scene = scene;
  7246. this._initCache();
  7247. }
  7248. Object.defineProperty(Node.prototype, "parent", {
  7249. get: function () {
  7250. return this._parentNode;
  7251. },
  7252. set: function (parent) {
  7253. if (this._parentNode === parent) {
  7254. return;
  7255. }
  7256. if (this._parentNode) {
  7257. var index = this._parentNode._children.indexOf(this);
  7258. if (index !== -1) {
  7259. this._parentNode._children.splice(index, 1);
  7260. }
  7261. }
  7262. this._parentNode = parent;
  7263. if (this._parentNode) {
  7264. if (!this._parentNode._children) {
  7265. this._parentNode._children = new Array();
  7266. }
  7267. this._parentNode._children.push(this);
  7268. }
  7269. },
  7270. enumerable: true,
  7271. configurable: true
  7272. });
  7273. Node.prototype.getScene = function () {
  7274. return this._scene;
  7275. };
  7276. Node.prototype.getEngine = function () {
  7277. return this._scene.getEngine();
  7278. };
  7279. // override it in derived class
  7280. Node.prototype.getWorldMatrix = function () {
  7281. return BABYLON.Matrix.Identity();
  7282. };
  7283. // override it in derived class if you add new variables to the cache
  7284. // and call the parent class method
  7285. Node.prototype._initCache = function () {
  7286. this._cache = {};
  7287. this._cache.parent = undefined;
  7288. };
  7289. Node.prototype.updateCache = function (force) {
  7290. if (!force && this.isSynchronized())
  7291. return;
  7292. this._cache.parent = this.parent;
  7293. this._updateCache();
  7294. };
  7295. // override it in derived class if you add new variables to the cache
  7296. // and call the parent class method if !ignoreParentClass
  7297. Node.prototype._updateCache = function (ignoreParentClass) {
  7298. };
  7299. // override it in derived class if you add new variables to the cache
  7300. Node.prototype._isSynchronized = function () {
  7301. return true;
  7302. };
  7303. Node.prototype._markSyncedWithParent = function () {
  7304. this._parentRenderId = this.parent._currentRenderId;
  7305. };
  7306. Node.prototype.isSynchronizedWithParent = function () {
  7307. if (!this.parent) {
  7308. return true;
  7309. }
  7310. if (this._parentRenderId !== this.parent._currentRenderId) {
  7311. return false;
  7312. }
  7313. return this.parent.isSynchronized();
  7314. };
  7315. Node.prototype.isSynchronized = function (updateCache) {
  7316. var check = this.hasNewParent();
  7317. check = check || !this.isSynchronizedWithParent();
  7318. check = check || !this._isSynchronized();
  7319. if (updateCache)
  7320. this.updateCache(true);
  7321. return !check;
  7322. };
  7323. Node.prototype.hasNewParent = function (update) {
  7324. if (this._cache.parent === this.parent)
  7325. return false;
  7326. if (update)
  7327. this._cache.parent = this.parent;
  7328. return true;
  7329. };
  7330. /**
  7331. * Is this node ready to be used/rendered
  7332. * @return {boolean} is it ready
  7333. */
  7334. Node.prototype.isReady = function () {
  7335. return this._isReady;
  7336. };
  7337. /**
  7338. * Is this node enabled.
  7339. * If the node has a parent and is enabled, the parent will be inspected as well.
  7340. * @return {boolean} whether this node (and its parent) is enabled.
  7341. * @see setEnabled
  7342. */
  7343. Node.prototype.isEnabled = function () {
  7344. if (!this._isEnabled) {
  7345. return false;
  7346. }
  7347. if (this.parent) {
  7348. return this.parent.isEnabled();
  7349. }
  7350. return true;
  7351. };
  7352. /**
  7353. * Set the enabled state of this node.
  7354. * @param {boolean} value - the new enabled state
  7355. * @see isEnabled
  7356. */
  7357. Node.prototype.setEnabled = function (value) {
  7358. this._isEnabled = value;
  7359. };
  7360. /**
  7361. * Is this node a descendant of the given node.
  7362. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7363. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7364. * @see parent
  7365. */
  7366. Node.prototype.isDescendantOf = function (ancestor) {
  7367. if (this.parent) {
  7368. if (this.parent === ancestor) {
  7369. return true;
  7370. }
  7371. return this.parent.isDescendantOf(ancestor);
  7372. }
  7373. return false;
  7374. };
  7375. /**
  7376. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7377. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7378. * @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.
  7379. * @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.
  7380. */
  7381. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7382. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7383. if (!this._children) {
  7384. return;
  7385. }
  7386. for (var index = 0; index < this._children.length; index++) {
  7387. var item = this._children[index];
  7388. if (!predicate || predicate(item)) {
  7389. results.push(item);
  7390. }
  7391. if (!directDescendantsOnly) {
  7392. item._getDescendants(results, false, predicate);
  7393. }
  7394. }
  7395. };
  7396. /**
  7397. * Will return all nodes that have this node as ascendant.
  7398. * @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.
  7399. * @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.
  7400. * @return {BABYLON.Node[]} all children nodes of all types.
  7401. */
  7402. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7403. var results = [];
  7404. this._getDescendants(results, directDescendantsOnly, predicate);
  7405. return results;
  7406. };
  7407. /**
  7408. * @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.
  7409. * @Deprecated, legacy support.
  7410. * use getDecendants instead.
  7411. */
  7412. Node.prototype.getChildren = function (predicate) {
  7413. return this.getDescendants(true, predicate);
  7414. };
  7415. /**
  7416. * Get all child-meshes of this node.
  7417. */
  7418. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7419. var results = [];
  7420. this._getDescendants(results, directDecendantsOnly, function (node) {
  7421. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7422. });
  7423. return results;
  7424. };
  7425. Node.prototype._setReady = function (state) {
  7426. if (state === this._isReady) {
  7427. return;
  7428. }
  7429. if (!state) {
  7430. this._isReady = false;
  7431. return;
  7432. }
  7433. this._isReady = true;
  7434. if (this.onReady) {
  7435. this.onReady(this);
  7436. }
  7437. };
  7438. Node.prototype.getAnimationByName = function (name) {
  7439. for (var i = 0; i < this.animations.length; i++) {
  7440. var animation = this.animations[i];
  7441. if (animation.name === name) {
  7442. return animation;
  7443. }
  7444. }
  7445. return null;
  7446. };
  7447. Node.prototype.createAnimationRange = function (name, from, to) {
  7448. // check name not already in use
  7449. if (!this._ranges[name]) {
  7450. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7451. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7452. if (this.animations[i]) {
  7453. this.animations[i].createRange(name, from, to);
  7454. }
  7455. }
  7456. }
  7457. };
  7458. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7459. if (deleteFrames === void 0) { deleteFrames = true; }
  7460. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7461. if (this.animations[i]) {
  7462. this.animations[i].deleteRange(name, deleteFrames);
  7463. }
  7464. }
  7465. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7466. };
  7467. Node.prototype.getAnimationRange = function (name) {
  7468. return this._ranges[name];
  7469. };
  7470. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7471. var range = this.getAnimationRange(name);
  7472. if (!range) {
  7473. return null;
  7474. }
  7475. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7476. };
  7477. Node.prototype.serializeAnimationRanges = function () {
  7478. var serializationRanges = [];
  7479. for (var name in this._ranges) {
  7480. var range = {};
  7481. range.name = name;
  7482. range.from = this._ranges[name].from;
  7483. range.to = this._ranges[name].to;
  7484. serializationRanges.push(range);
  7485. }
  7486. return serializationRanges;
  7487. };
  7488. Node.prototype.dispose = function () {
  7489. this.parent = null;
  7490. };
  7491. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7492. if (parsedNode.ranges) {
  7493. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7494. var data = parsedNode.ranges[index];
  7495. node.createAnimationRange(data.name, data.from, data.to);
  7496. }
  7497. }
  7498. };
  7499. __decorate([
  7500. BABYLON.serialize()
  7501. ], Node.prototype, "name", void 0);
  7502. __decorate([
  7503. BABYLON.serialize()
  7504. ], Node.prototype, "id", void 0);
  7505. __decorate([
  7506. BABYLON.serialize()
  7507. ], Node.prototype, "uniqueId", void 0);
  7508. __decorate([
  7509. BABYLON.serialize()
  7510. ], Node.prototype, "state", void 0);
  7511. return Node;
  7512. }());
  7513. BABYLON.Node = Node;
  7514. })(BABYLON || (BABYLON = {}));
  7515. var BABYLON;
  7516. (function (BABYLON) {
  7517. var FilesInput = (function () {
  7518. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7519. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7520. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7521. this._engine = p_engine;
  7522. this._canvas = p_canvas;
  7523. this._currentScene = p_scene;
  7524. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7525. this._progressCallback = p_progressCallback;
  7526. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7527. this._textureLoadingCallback = p_textureLoadingCallback;
  7528. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7529. }
  7530. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7531. var _this = this;
  7532. if (p_elementToMonitor) {
  7533. this._elementToMonitor = p_elementToMonitor;
  7534. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7535. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7536. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7537. }
  7538. };
  7539. FilesInput.prototype.renderFunction = function () {
  7540. if (this._additionnalRenderLoopLogicCallback) {
  7541. this._additionnalRenderLoopLogicCallback();
  7542. }
  7543. if (this._currentScene) {
  7544. if (this._textureLoadingCallback) {
  7545. var remaining = this._currentScene.getWaitingItemsCount();
  7546. if (remaining > 0) {
  7547. this._textureLoadingCallback(remaining);
  7548. }
  7549. }
  7550. this._currentScene.render();
  7551. }
  7552. };
  7553. FilesInput.prototype.drag = function (e) {
  7554. e.stopPropagation();
  7555. e.preventDefault();
  7556. };
  7557. FilesInput.prototype.drop = function (eventDrop) {
  7558. eventDrop.stopPropagation();
  7559. eventDrop.preventDefault();
  7560. this.loadFiles(eventDrop);
  7561. };
  7562. FilesInput.prototype.loadFiles = function (event) {
  7563. if (this._startingProcessingFilesCallback)
  7564. this._startingProcessingFilesCallback();
  7565. // Handling data transfer via drag'n'drop
  7566. if (event && event.dataTransfer && event.dataTransfer.files) {
  7567. this._filesToLoad = event.dataTransfer.files;
  7568. }
  7569. // Handling files from input files
  7570. if (event && event.target && event.target.files) {
  7571. this._filesToLoad = event.target.files;
  7572. }
  7573. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7574. for (var i = 0; i < this._filesToLoad.length; i++) {
  7575. switch (this._filesToLoad[i].type) {
  7576. case "image/jpeg":
  7577. case "image/png":
  7578. case "image/bmp":
  7579. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7580. break;
  7581. case "image/targa":
  7582. case "image/vnd.ms-dds":
  7583. case "audio/wav":
  7584. case "audio/x-wav":
  7585. case "audio/mp3":
  7586. case "audio/mpeg":
  7587. case "audio/mpeg3":
  7588. case "audio/x-mpeg-3":
  7589. case "audio/ogg":
  7590. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7591. break;
  7592. default:
  7593. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7594. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7595. }
  7596. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7597. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7598. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7599. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7600. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7601. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7602. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7603. this._sceneFileToLoad = this._filesToLoad[i];
  7604. }
  7605. break;
  7606. }
  7607. }
  7608. this.reload();
  7609. }
  7610. };
  7611. FilesInput.prototype.reload = function () {
  7612. var _this = this;
  7613. var that = this;
  7614. // If a ".babylon" file has been provided
  7615. if (this._sceneFileToLoad) {
  7616. if (this._currentScene) {
  7617. if (BABYLON.Tools.errorsCount > 0) {
  7618. BABYLON.Tools.ClearLogCache();
  7619. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7620. }
  7621. this._engine.stopRenderLoop();
  7622. this._currentScene.dispose();
  7623. }
  7624. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7625. that._currentScene = newScene;
  7626. // Wait for textures and shaders to be ready
  7627. that._currentScene.executeWhenReady(function () {
  7628. // Attach camera to canvas inputs
  7629. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7630. that._currentScene.createDefaultCameraOrLight();
  7631. }
  7632. that._currentScene.activeCamera.attachControl(that._canvas);
  7633. if (that._sceneLoadedCallback) {
  7634. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7635. }
  7636. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7637. });
  7638. }, function (progress) {
  7639. if (_this._progressCallback) {
  7640. _this._progressCallback(progress);
  7641. }
  7642. });
  7643. }
  7644. else {
  7645. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7646. }
  7647. };
  7648. FilesInput.FilesTextures = new Array();
  7649. FilesInput.FilesToLoad = new Array();
  7650. return FilesInput;
  7651. }());
  7652. BABYLON.FilesInput = FilesInput;
  7653. })(BABYLON || (BABYLON = {}));
  7654. var BABYLON;
  7655. (function (BABYLON) {
  7656. var IntersectionInfo = (function () {
  7657. function IntersectionInfo(bu, bv, distance) {
  7658. this.bu = bu;
  7659. this.bv = bv;
  7660. this.distance = distance;
  7661. this.faceId = 0;
  7662. this.subMeshId = 0;
  7663. }
  7664. return IntersectionInfo;
  7665. }());
  7666. BABYLON.IntersectionInfo = IntersectionInfo;
  7667. var PickingInfo = (function () {
  7668. function PickingInfo() {
  7669. this.hit = false;
  7670. this.distance = 0;
  7671. this.pickedPoint = null;
  7672. this.pickedMesh = null;
  7673. this.bu = 0;
  7674. this.bv = 0;
  7675. this.faceId = -1;
  7676. this.subMeshId = 0;
  7677. this.pickedSprite = null;
  7678. }
  7679. // Methods
  7680. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7681. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7682. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7683. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7684. return null;
  7685. }
  7686. var indices = this.pickedMesh.getIndices();
  7687. var result;
  7688. if (useVerticesNormals) {
  7689. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7690. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7691. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7692. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7693. normal0 = normal0.scale(this.bu);
  7694. normal1 = normal1.scale(this.bv);
  7695. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7696. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7697. }
  7698. else {
  7699. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7700. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7701. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7702. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7703. var p1p2 = vertex1.subtract(vertex2);
  7704. var p3p2 = vertex3.subtract(vertex2);
  7705. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7706. }
  7707. if (useWorldCoordinates) {
  7708. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7709. }
  7710. return BABYLON.Vector3.Normalize(result);
  7711. };
  7712. PickingInfo.prototype.getTextureCoordinates = function () {
  7713. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7714. return null;
  7715. }
  7716. var indices = this.pickedMesh.getIndices();
  7717. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7718. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7719. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7720. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7721. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7722. uv1 = uv1.scale(this.bu);
  7723. uv2 = uv2.scale(this.bv);
  7724. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7725. };
  7726. return PickingInfo;
  7727. }());
  7728. BABYLON.PickingInfo = PickingInfo;
  7729. })(BABYLON || (BABYLON = {}));
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. var BoundingSphere = (function () {
  7733. function BoundingSphere(minimum, maximum) {
  7734. this.minimum = minimum;
  7735. this.maximum = maximum;
  7736. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7737. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7738. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7739. this.radius = distance * 0.5;
  7740. this.centerWorld = BABYLON.Vector3.Zero();
  7741. this._update(BABYLON.Matrix.Identity());
  7742. }
  7743. // Methods
  7744. BoundingSphere.prototype._update = function (world) {
  7745. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7746. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7747. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7748. };
  7749. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7750. for (var i = 0; i < 6; i++) {
  7751. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7752. return false;
  7753. }
  7754. return true;
  7755. };
  7756. BoundingSphere.prototype.intersectsPoint = function (point) {
  7757. var x = this.centerWorld.x - point.x;
  7758. var y = this.centerWorld.y - point.y;
  7759. var z = this.centerWorld.z - point.z;
  7760. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7761. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7762. return false;
  7763. return true;
  7764. };
  7765. // Statics
  7766. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7767. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7768. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7769. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7770. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7771. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7772. return false;
  7773. return true;
  7774. };
  7775. return BoundingSphere;
  7776. }());
  7777. BABYLON.BoundingSphere = BoundingSphere;
  7778. })(BABYLON || (BABYLON = {}));
  7779. var BABYLON;
  7780. (function (BABYLON) {
  7781. var BoundingBox = (function () {
  7782. function BoundingBox(minimum, maximum) {
  7783. this.minimum = minimum;
  7784. this.maximum = maximum;
  7785. this.vectors = new Array();
  7786. this.vectorsWorld = new Array();
  7787. // Bounding vectors
  7788. this.vectors.push(this.minimum.clone());
  7789. this.vectors.push(this.maximum.clone());
  7790. this.vectors.push(this.minimum.clone());
  7791. this.vectors[2].x = this.maximum.x;
  7792. this.vectors.push(this.minimum.clone());
  7793. this.vectors[3].y = this.maximum.y;
  7794. this.vectors.push(this.minimum.clone());
  7795. this.vectors[4].z = this.maximum.z;
  7796. this.vectors.push(this.maximum.clone());
  7797. this.vectors[5].z = this.minimum.z;
  7798. this.vectors.push(this.maximum.clone());
  7799. this.vectors[6].x = this.minimum.x;
  7800. this.vectors.push(this.maximum.clone());
  7801. this.vectors[7].y = this.minimum.y;
  7802. // OBB
  7803. this.center = this.maximum.add(this.minimum).scale(0.5);
  7804. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7805. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7806. // World
  7807. for (var index = 0; index < this.vectors.length; index++) {
  7808. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7809. }
  7810. this.minimumWorld = BABYLON.Vector3.Zero();
  7811. this.maximumWorld = BABYLON.Vector3.Zero();
  7812. this._update(BABYLON.Matrix.Identity());
  7813. }
  7814. // Methods
  7815. BoundingBox.prototype.getWorldMatrix = function () {
  7816. return this._worldMatrix;
  7817. };
  7818. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7819. this._worldMatrix.copyFrom(matrix);
  7820. return this;
  7821. };
  7822. BoundingBox.prototype._update = function (world) {
  7823. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7824. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7825. for (var index = 0; index < this.vectors.length; index++) {
  7826. var v = this.vectorsWorld[index];
  7827. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7828. if (v.x < this.minimumWorld.x)
  7829. this.minimumWorld.x = v.x;
  7830. if (v.y < this.minimumWorld.y)
  7831. this.minimumWorld.y = v.y;
  7832. if (v.z < this.minimumWorld.z)
  7833. this.minimumWorld.z = v.z;
  7834. if (v.x > this.maximumWorld.x)
  7835. this.maximumWorld.x = v.x;
  7836. if (v.y > this.maximumWorld.y)
  7837. this.maximumWorld.y = v.y;
  7838. if (v.z > this.maximumWorld.z)
  7839. this.maximumWorld.z = v.z;
  7840. }
  7841. // OBB
  7842. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7843. this.center.scaleInPlace(0.5);
  7844. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7845. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7846. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7847. this._worldMatrix = world;
  7848. };
  7849. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7850. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7851. };
  7852. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7853. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7854. };
  7855. BoundingBox.prototype.intersectsPoint = function (point) {
  7856. var delta = -BABYLON.Epsilon;
  7857. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7858. return false;
  7859. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7860. return false;
  7861. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7862. return false;
  7863. return true;
  7864. };
  7865. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7866. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7867. };
  7868. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7869. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7870. return false;
  7871. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7872. return false;
  7873. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7874. return false;
  7875. return true;
  7876. };
  7877. // Statics
  7878. BoundingBox.Intersects = function (box0, box1) {
  7879. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7880. return false;
  7881. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7882. return false;
  7883. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7884. return false;
  7885. return true;
  7886. };
  7887. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7888. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7889. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7890. return (num <= (sphereRadius * sphereRadius));
  7891. };
  7892. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7893. for (var p = 0; p < 6; p++) {
  7894. for (var i = 0; i < 8; i++) {
  7895. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7896. return false;
  7897. }
  7898. }
  7899. }
  7900. return true;
  7901. };
  7902. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7903. for (var p = 0; p < 6; p++) {
  7904. var inCount = 8;
  7905. for (var i = 0; i < 8; i++) {
  7906. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7907. --inCount;
  7908. }
  7909. else {
  7910. break;
  7911. }
  7912. }
  7913. if (inCount === 0)
  7914. return false;
  7915. }
  7916. return true;
  7917. };
  7918. return BoundingBox;
  7919. }());
  7920. BABYLON.BoundingBox = BoundingBox;
  7921. })(BABYLON || (BABYLON = {}));
  7922. var BABYLON;
  7923. (function (BABYLON) {
  7924. var computeBoxExtents = function (axis, box) {
  7925. var p = BABYLON.Vector3.Dot(box.center, axis);
  7926. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7927. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7928. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7929. var r = r0 + r1 + r2;
  7930. return {
  7931. min: p - r,
  7932. max: p + r
  7933. };
  7934. };
  7935. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7936. var axisOverlap = function (axis, box0, box1) {
  7937. var result0 = computeBoxExtents(axis, box0);
  7938. var result1 = computeBoxExtents(axis, box1);
  7939. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7940. };
  7941. var BoundingInfo = (function () {
  7942. function BoundingInfo(minimum, maximum) {
  7943. this.minimum = minimum;
  7944. this.maximum = maximum;
  7945. this._isLocked = false;
  7946. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7947. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7948. }
  7949. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7950. get: function () {
  7951. return this._isLocked;
  7952. },
  7953. set: function (value) {
  7954. this._isLocked = value;
  7955. },
  7956. enumerable: true,
  7957. configurable: true
  7958. });
  7959. // Methods
  7960. BoundingInfo.prototype.update = function (world) {
  7961. if (this._isLocked) {
  7962. return;
  7963. }
  7964. this.boundingBox._update(world);
  7965. this.boundingSphere._update(world);
  7966. };
  7967. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7968. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7969. return false;
  7970. return this.boundingBox.isInFrustum(frustumPlanes);
  7971. };
  7972. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7973. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7974. };
  7975. BoundingInfo.prototype._checkCollision = function (collider) {
  7976. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7977. };
  7978. BoundingInfo.prototype.intersectsPoint = function (point) {
  7979. if (!this.boundingSphere.centerWorld) {
  7980. return false;
  7981. }
  7982. if (!this.boundingSphere.intersectsPoint(point)) {
  7983. return false;
  7984. }
  7985. if (!this.boundingBox.intersectsPoint(point)) {
  7986. return false;
  7987. }
  7988. return true;
  7989. };
  7990. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7991. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7992. return false;
  7993. }
  7994. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7995. return false;
  7996. }
  7997. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7998. return false;
  7999. }
  8000. if (!precise) {
  8001. return true;
  8002. }
  8003. var box0 = this.boundingBox;
  8004. var box1 = boundingInfo.boundingBox;
  8005. if (!axisOverlap(box0.directions[0], box0, box1))
  8006. return false;
  8007. if (!axisOverlap(box0.directions[1], box0, box1))
  8008. return false;
  8009. if (!axisOverlap(box0.directions[2], box0, box1))
  8010. return false;
  8011. if (!axisOverlap(box1.directions[0], box0, box1))
  8012. return false;
  8013. if (!axisOverlap(box1.directions[1], box0, box1))
  8014. return false;
  8015. if (!axisOverlap(box1.directions[2], box0, box1))
  8016. return false;
  8017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8018. return false;
  8019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8020. return false;
  8021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8022. return false;
  8023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8024. return false;
  8025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8026. return false;
  8027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8028. return false;
  8029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8030. return false;
  8031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8032. return false;
  8033. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8034. return false;
  8035. return true;
  8036. };
  8037. return BoundingInfo;
  8038. }());
  8039. BABYLON.BoundingInfo = BoundingInfo;
  8040. })(BABYLON || (BABYLON = {}));
  8041. var BABYLON;
  8042. (function (BABYLON) {
  8043. var Ray = (function () {
  8044. function Ray(origin, direction, length) {
  8045. if (length === void 0) { length = Number.MAX_VALUE; }
  8046. this.origin = origin;
  8047. this.direction = direction;
  8048. this.length = length;
  8049. }
  8050. // Methods
  8051. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8052. var d = 0.0;
  8053. var maxValue = Number.MAX_VALUE;
  8054. var inv;
  8055. var min;
  8056. var max;
  8057. var temp;
  8058. if (Math.abs(this.direction.x) < 0.0000001) {
  8059. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8060. return false;
  8061. }
  8062. }
  8063. else {
  8064. inv = 1.0 / this.direction.x;
  8065. min = (minimum.x - this.origin.x) * inv;
  8066. max = (maximum.x - this.origin.x) * inv;
  8067. if (max === -Infinity) {
  8068. max = Infinity;
  8069. }
  8070. if (min > max) {
  8071. temp = min;
  8072. min = max;
  8073. max = temp;
  8074. }
  8075. d = Math.max(min, d);
  8076. maxValue = Math.min(max, maxValue);
  8077. if (d > maxValue) {
  8078. return false;
  8079. }
  8080. }
  8081. if (Math.abs(this.direction.y) < 0.0000001) {
  8082. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8083. return false;
  8084. }
  8085. }
  8086. else {
  8087. inv = 1.0 / this.direction.y;
  8088. min = (minimum.y - this.origin.y) * inv;
  8089. max = (maximum.y - this.origin.y) * inv;
  8090. if (max === -Infinity) {
  8091. max = Infinity;
  8092. }
  8093. if (min > max) {
  8094. temp = min;
  8095. min = max;
  8096. max = temp;
  8097. }
  8098. d = Math.max(min, d);
  8099. maxValue = Math.min(max, maxValue);
  8100. if (d > maxValue) {
  8101. return false;
  8102. }
  8103. }
  8104. if (Math.abs(this.direction.z) < 0.0000001) {
  8105. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8106. return false;
  8107. }
  8108. }
  8109. else {
  8110. inv = 1.0 / this.direction.z;
  8111. min = (minimum.z - this.origin.z) * inv;
  8112. max = (maximum.z - this.origin.z) * inv;
  8113. if (max === -Infinity) {
  8114. max = Infinity;
  8115. }
  8116. if (min > max) {
  8117. temp = min;
  8118. min = max;
  8119. max = temp;
  8120. }
  8121. d = Math.max(min, d);
  8122. maxValue = Math.min(max, maxValue);
  8123. if (d > maxValue) {
  8124. return false;
  8125. }
  8126. }
  8127. return true;
  8128. };
  8129. Ray.prototype.intersectsBox = function (box) {
  8130. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8131. };
  8132. Ray.prototype.intersectsSphere = function (sphere) {
  8133. var x = sphere.center.x - this.origin.x;
  8134. var y = sphere.center.y - this.origin.y;
  8135. var z = sphere.center.z - this.origin.z;
  8136. var pyth = (x * x) + (y * y) + (z * z);
  8137. var rr = sphere.radius * sphere.radius;
  8138. if (pyth <= rr) {
  8139. return true;
  8140. }
  8141. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8142. if (dot < 0.0) {
  8143. return false;
  8144. }
  8145. var temp = pyth - (dot * dot);
  8146. return temp <= rr;
  8147. };
  8148. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8149. if (!this._edge1) {
  8150. this._edge1 = BABYLON.Vector3.Zero();
  8151. this._edge2 = BABYLON.Vector3.Zero();
  8152. this._pvec = BABYLON.Vector3.Zero();
  8153. this._tvec = BABYLON.Vector3.Zero();
  8154. this._qvec = BABYLON.Vector3.Zero();
  8155. }
  8156. vertex1.subtractToRef(vertex0, this._edge1);
  8157. vertex2.subtractToRef(vertex0, this._edge2);
  8158. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8159. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8160. if (det === 0) {
  8161. return null;
  8162. }
  8163. var invdet = 1 / det;
  8164. this.origin.subtractToRef(vertex0, this._tvec);
  8165. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8166. if (bu < 0 || bu > 1.0) {
  8167. return null;
  8168. }
  8169. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8170. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8171. if (bv < 0 || bu + bv > 1.0) {
  8172. return null;
  8173. }
  8174. //check if the distance is longer than the predefined length.
  8175. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8176. if (distance > this.length) {
  8177. return null;
  8178. }
  8179. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8180. };
  8181. Ray.prototype.intersectsPlane = function (plane) {
  8182. var distance;
  8183. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8184. if (Math.abs(result1) < 9.99999997475243E-07) {
  8185. return null;
  8186. }
  8187. else {
  8188. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8189. distance = (-plane.d - result2) / result1;
  8190. if (distance < 0.0) {
  8191. if (distance < -9.99999997475243E-07) {
  8192. return null;
  8193. }
  8194. else {
  8195. return 0;
  8196. }
  8197. }
  8198. return distance;
  8199. }
  8200. };
  8201. /**
  8202. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8203. * @param sega the first point of the segment to test the intersection against
  8204. * @param segb the second point of the segment to test the intersection against
  8205. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8206. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8207. */
  8208. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8209. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8210. var u = segb.subtract(sega);
  8211. var v = rsegb.subtract(this.origin);
  8212. var w = sega.subtract(this.origin);
  8213. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8214. var b = BABYLON.Vector3.Dot(u, v);
  8215. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8216. var d = BABYLON.Vector3.Dot(u, w);
  8217. var e = BABYLON.Vector3.Dot(v, w);
  8218. var D = a * c - b * b; // always >= 0
  8219. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8220. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8221. // compute the line parameters of the two closest points
  8222. if (D < Ray.smallnum) {
  8223. sN = 0.0; // force using point P0 on segment S1
  8224. sD = 1.0; // to prevent possible division by 0.0 later
  8225. tN = e;
  8226. tD = c;
  8227. }
  8228. else {
  8229. sN = (b * e - c * d);
  8230. tN = (a * e - b * d);
  8231. if (sN < 0.0) {
  8232. sN = 0.0;
  8233. tN = e;
  8234. tD = c;
  8235. }
  8236. else if (sN > sD) {
  8237. sN = sD;
  8238. tN = e + b;
  8239. tD = c;
  8240. }
  8241. }
  8242. if (tN < 0.0) {
  8243. tN = 0.0;
  8244. // recompute sc for this edge
  8245. if (-d < 0.0) {
  8246. sN = 0.0;
  8247. }
  8248. else if (-d > a)
  8249. sN = sD;
  8250. else {
  8251. sN = -d;
  8252. sD = a;
  8253. }
  8254. }
  8255. else if (tN > tD) {
  8256. tN = tD;
  8257. // recompute sc for this edge
  8258. if ((-d + b) < 0.0) {
  8259. sN = 0;
  8260. }
  8261. else if ((-d + b) > a) {
  8262. sN = sD;
  8263. }
  8264. else {
  8265. sN = (-d + b);
  8266. sD = a;
  8267. }
  8268. }
  8269. // finally do the division to get sc and tc
  8270. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8271. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8272. // get the difference of the two closest points
  8273. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(v.multiplyByFloats(tc, tc, tc)); // = S1(sc) - S2(tc)
  8274. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8275. if (isIntersected) {
  8276. return tc;
  8277. }
  8278. return -1;
  8279. };
  8280. // Statics
  8281. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8282. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8283. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8284. var direction = end.subtract(start);
  8285. direction.normalize();
  8286. return new Ray(start, direction);
  8287. };
  8288. /**
  8289. * 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
  8290. * transformed to the given world matrix.
  8291. * @param origin The origin point
  8292. * @param end The end point
  8293. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8294. */
  8295. Ray.CreateNewFromTo = function (origin, end, world) {
  8296. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8297. var direction = end.subtract(origin);
  8298. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8299. direction.normalize();
  8300. return Ray.Transform(new Ray(origin, direction, length), world);
  8301. };
  8302. Ray.Transform = function (ray, matrix) {
  8303. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8304. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8305. newDirection.normalize();
  8306. return new Ray(newOrigin, newDirection, ray.length);
  8307. };
  8308. Ray.smallnum = 0.00000001;
  8309. Ray.rayl = 10e8;
  8310. return Ray;
  8311. }());
  8312. BABYLON.Ray = Ray;
  8313. })(BABYLON || (BABYLON = {}));
  8314. var BABYLON;
  8315. (function (BABYLON) {
  8316. var AbstractMesh = (function (_super) {
  8317. __extends(AbstractMesh, _super);
  8318. // Constructor
  8319. function AbstractMesh(name, scene) {
  8320. var _this = this;
  8321. _super.call(this, name, scene);
  8322. // Events
  8323. /**
  8324. * An event triggered when this mesh collides with another one
  8325. * @type {BABYLON.Observable}
  8326. */
  8327. this.onCollideObservable = new BABYLON.Observable();
  8328. /**
  8329. * An event triggered when the collision's position changes
  8330. * @type {BABYLON.Observable}
  8331. */
  8332. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8333. /**
  8334. * An event triggered after the world matrix is updated
  8335. * @type {BABYLON.Observable}
  8336. */
  8337. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8338. // Properties
  8339. this.definedFacingForward = true; // orientation for POV movement & rotation
  8340. this.position = new BABYLON.Vector3(0, 0, 0);
  8341. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8342. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8343. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8344. this.visibility = 1.0;
  8345. this.alphaIndex = Number.MAX_VALUE;
  8346. this.infiniteDistance = false;
  8347. this.isVisible = true;
  8348. this.isPickable = true;
  8349. this.showBoundingBox = false;
  8350. this.showSubMeshesBoundingBox = false;
  8351. this.onDispose = null;
  8352. this.isBlocker = false;
  8353. this.renderingGroupId = 0;
  8354. this.receiveShadows = false;
  8355. this.renderOutline = false;
  8356. this.outlineColor = BABYLON.Color3.Red();
  8357. this.outlineWidth = 0.02;
  8358. this.renderOverlay = false;
  8359. this.overlayColor = BABYLON.Color3.Red();
  8360. this.overlayAlpha = 0.5;
  8361. this.hasVertexAlpha = false;
  8362. this.useVertexColors = true;
  8363. this.applyFog = true;
  8364. this.computeBonesUsingShaders = true;
  8365. this.scalingDeterminant = 1;
  8366. this.numBoneInfluencers = 4;
  8367. this.useOctreeForRenderingSelection = true;
  8368. this.useOctreeForPicking = true;
  8369. this.useOctreeForCollisions = true;
  8370. this.layerMask = 0x0FFFFFFF;
  8371. this.alwaysSelectAsActiveMesh = false;
  8372. // Collisions
  8373. this._checkCollisions = false;
  8374. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8375. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8376. this._collider = new BABYLON.Collider();
  8377. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8378. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8379. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8380. // Edges
  8381. this.edgesWidth = 1;
  8382. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8383. // Cache
  8384. this._localWorld = BABYLON.Matrix.Zero();
  8385. this._worldMatrix = BABYLON.Matrix.Zero();
  8386. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8387. this._absolutePosition = BABYLON.Vector3.Zero();
  8388. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8389. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8390. this._isDirty = false;
  8391. this._pivotMatrix = BABYLON.Matrix.Identity();
  8392. this._isDisposed = false;
  8393. this._renderId = 0;
  8394. this._intersectionsInProgress = new Array();
  8395. this._isWorldMatrixFrozen = false;
  8396. this._unIndexed = false;
  8397. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8398. if (collidedMesh === void 0) { collidedMesh = null; }
  8399. //TODO move this to the collision coordinator!
  8400. if (_this.getScene().workerCollisions)
  8401. newPosition.multiplyInPlace(_this._collider.radius);
  8402. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8403. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8404. _this.position.addInPlace(_this._diffPositionForCollisions);
  8405. }
  8406. if (collidedMesh) {
  8407. _this.onCollideObservable.notifyObservers(collidedMesh);
  8408. }
  8409. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8410. };
  8411. scene.addMesh(this);
  8412. }
  8413. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8414. get: function () {
  8415. return AbstractMesh._BILLBOARDMODE_NONE;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8421. get: function () {
  8422. return AbstractMesh._BILLBOARDMODE_X;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8428. get: function () {
  8429. return AbstractMesh._BILLBOARDMODE_Y;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8435. get: function () {
  8436. return AbstractMesh._BILLBOARDMODE_Z;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8442. get: function () {
  8443. return AbstractMesh._BILLBOARDMODE_ALL;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8449. set: function (callback) {
  8450. if (this._onCollideObserver) {
  8451. this.onCollideObservable.remove(this._onCollideObserver);
  8452. }
  8453. this._onCollideObserver = this.onCollideObservable.add(callback);
  8454. },
  8455. enumerable: true,
  8456. configurable: true
  8457. });
  8458. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8459. set: function (callback) {
  8460. if (this._onCollisionPositionChangeObserver) {
  8461. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8462. }
  8463. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8464. },
  8465. enumerable: true,
  8466. configurable: true
  8467. });
  8468. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8469. get: function () {
  8470. return this._skeleton;
  8471. },
  8472. set: function (value) {
  8473. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8474. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8475. }
  8476. if (value && value.needInitialSkinMatrix) {
  8477. value._registerMeshWithPoseMatrix(this);
  8478. }
  8479. this._skeleton = value;
  8480. if (!this._skeleton) {
  8481. this._bonesTransformMatrices = null;
  8482. }
  8483. },
  8484. enumerable: true,
  8485. configurable: true
  8486. });
  8487. /**
  8488. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8489. */
  8490. AbstractMesh.prototype.toString = function (fullDetails) {
  8491. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8492. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8493. if (this._skeleton) {
  8494. ret += ", skeleton: " + this._skeleton.name;
  8495. }
  8496. if (fullDetails) {
  8497. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8498. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8499. }
  8500. return ret;
  8501. };
  8502. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8503. /**
  8504. * Getting the rotation object.
  8505. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8506. */
  8507. get: function () {
  8508. return this._rotation;
  8509. },
  8510. set: function (newRotation) {
  8511. this._rotation = newRotation;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8517. get: function () {
  8518. return this._scaling;
  8519. },
  8520. set: function (newScaling) {
  8521. this._scaling = newScaling;
  8522. if (this.physicsImpostor) {
  8523. this.physicsImpostor.forceUpdate();
  8524. }
  8525. },
  8526. enumerable: true,
  8527. configurable: true
  8528. });
  8529. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8530. get: function () {
  8531. return this._rotationQuaternion;
  8532. },
  8533. set: function (quaternion) {
  8534. this._rotationQuaternion = quaternion;
  8535. //reset the rotation vector.
  8536. if (quaternion && this.rotation.length()) {
  8537. this.rotation.copyFromFloats(0, 0, 0);
  8538. }
  8539. },
  8540. enumerable: true,
  8541. configurable: true
  8542. });
  8543. // Methods
  8544. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8545. this._poseMatrix.copyFrom(matrix);
  8546. };
  8547. AbstractMesh.prototype.getPoseMatrix = function () {
  8548. return this._poseMatrix;
  8549. };
  8550. AbstractMesh.prototype.disableEdgesRendering = function () {
  8551. if (this._edgesRenderer !== undefined) {
  8552. this._edgesRenderer.dispose();
  8553. this._edgesRenderer = undefined;
  8554. }
  8555. };
  8556. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8557. if (epsilon === void 0) { epsilon = 0.95; }
  8558. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8559. this.disableEdgesRendering();
  8560. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8561. };
  8562. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8563. get: function () {
  8564. return false;
  8565. },
  8566. enumerable: true,
  8567. configurable: true
  8568. });
  8569. AbstractMesh.prototype.getLOD = function (camera) {
  8570. return this;
  8571. };
  8572. AbstractMesh.prototype.getTotalVertices = function () {
  8573. return 0;
  8574. };
  8575. AbstractMesh.prototype.getIndices = function () {
  8576. return null;
  8577. };
  8578. AbstractMesh.prototype.getVerticesData = function (kind) {
  8579. return null;
  8580. };
  8581. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8582. return false;
  8583. };
  8584. AbstractMesh.prototype.getBoundingInfo = function () {
  8585. if (this._masterMesh) {
  8586. return this._masterMesh.getBoundingInfo();
  8587. }
  8588. if (!this._boundingInfo) {
  8589. this._updateBoundingInfo();
  8590. }
  8591. return this._boundingInfo;
  8592. };
  8593. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8594. get: function () {
  8595. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8596. },
  8597. enumerable: true,
  8598. configurable: true
  8599. });
  8600. AbstractMesh.prototype._preActivate = function () {
  8601. };
  8602. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8603. };
  8604. AbstractMesh.prototype._activate = function (renderId) {
  8605. this._renderId = renderId;
  8606. };
  8607. AbstractMesh.prototype.getWorldMatrix = function () {
  8608. if (this._masterMesh) {
  8609. return this._masterMesh.getWorldMatrix();
  8610. }
  8611. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8612. this.computeWorldMatrix();
  8613. }
  8614. return this._worldMatrix;
  8615. };
  8616. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8617. get: function () {
  8618. return this._worldMatrix;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8624. get: function () {
  8625. return this._absolutePosition;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8631. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8632. this.computeWorldMatrix(true);
  8633. this._isWorldMatrixFrozen = true;
  8634. };
  8635. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8636. this._isWorldMatrixFrozen = false;
  8637. this.computeWorldMatrix(true);
  8638. };
  8639. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8640. get: function () {
  8641. return this._isWorldMatrixFrozen;
  8642. },
  8643. enumerable: true,
  8644. configurable: true
  8645. });
  8646. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8647. axis.normalize();
  8648. if (!this.rotationQuaternion) {
  8649. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8650. this.rotation = BABYLON.Vector3.Zero();
  8651. }
  8652. var rotationQuaternion;
  8653. if (!space || space === BABYLON.Space.LOCAL) {
  8654. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8655. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8656. }
  8657. else {
  8658. if (this.parent) {
  8659. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8660. invertParentWorldMatrix.invert();
  8661. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8662. }
  8663. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8664. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8665. }
  8666. };
  8667. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8668. var displacementVector = axis.scale(distance);
  8669. if (!space || space === BABYLON.Space.LOCAL) {
  8670. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8671. this.setPositionWithLocalVector(tempV3);
  8672. }
  8673. else {
  8674. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8675. }
  8676. };
  8677. AbstractMesh.prototype.getAbsolutePosition = function () {
  8678. this.computeWorldMatrix();
  8679. return this._absolutePosition;
  8680. };
  8681. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8682. if (!absolutePosition) {
  8683. return;
  8684. }
  8685. var absolutePositionX;
  8686. var absolutePositionY;
  8687. var absolutePositionZ;
  8688. if (absolutePosition.x === undefined) {
  8689. if (arguments.length < 3) {
  8690. return;
  8691. }
  8692. absolutePositionX = arguments[0];
  8693. absolutePositionY = arguments[1];
  8694. absolutePositionZ = arguments[2];
  8695. }
  8696. else {
  8697. absolutePositionX = absolutePosition.x;
  8698. absolutePositionY = absolutePosition.y;
  8699. absolutePositionZ = absolutePosition.z;
  8700. }
  8701. if (this.parent) {
  8702. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8703. invertParentWorldMatrix.invert();
  8704. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8705. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8706. }
  8707. else {
  8708. this.position.x = absolutePositionX;
  8709. this.position.y = absolutePositionY;
  8710. this.position.z = absolutePositionZ;
  8711. }
  8712. };
  8713. // ================================== Point of View Movement =================================
  8714. /**
  8715. * Perform relative position change from the point of view of behind the front of the mesh.
  8716. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8717. * Supports definition of mesh facing forward or backward.
  8718. * @param {number} amountRight
  8719. * @param {number} amountUp
  8720. * @param {number} amountForward
  8721. */
  8722. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8723. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8724. };
  8725. /**
  8726. * Calculate relative position change from the point of view of behind the front of the mesh.
  8727. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8728. * Supports definition of mesh facing forward or backward.
  8729. * @param {number} amountRight
  8730. * @param {number} amountUp
  8731. * @param {number} amountForward
  8732. */
  8733. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8734. var rotMatrix = new BABYLON.Matrix();
  8735. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8736. rotQuaternion.toRotationMatrix(rotMatrix);
  8737. var translationDelta = BABYLON.Vector3.Zero();
  8738. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8739. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8740. return translationDelta;
  8741. };
  8742. // ================================== Point of View Rotation =================================
  8743. /**
  8744. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8745. * Supports definition of mesh facing forward or backward.
  8746. * @param {number} flipBack
  8747. * @param {number} twirlClockwise
  8748. * @param {number} tiltRight
  8749. */
  8750. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8751. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8752. };
  8753. /**
  8754. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8755. * Supports definition of mesh facing forward or backward.
  8756. * @param {number} flipBack
  8757. * @param {number} twirlClockwise
  8758. * @param {number} tiltRight
  8759. */
  8760. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8761. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8762. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8763. };
  8764. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8765. this._pivotMatrix = matrix;
  8766. this._cache.pivotMatrixUpdated = true;
  8767. };
  8768. AbstractMesh.prototype.getPivotMatrix = function () {
  8769. return this._pivotMatrix;
  8770. };
  8771. AbstractMesh.prototype._isSynchronized = function () {
  8772. if (this._isDirty) {
  8773. return false;
  8774. }
  8775. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8776. return false;
  8777. if (this._cache.pivotMatrixUpdated) {
  8778. return false;
  8779. }
  8780. if (this.infiniteDistance) {
  8781. return false;
  8782. }
  8783. if (!this._cache.position.equals(this.position))
  8784. return false;
  8785. if (this.rotationQuaternion) {
  8786. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8787. return false;
  8788. }
  8789. else {
  8790. if (!this._cache.rotation.equals(this.rotation))
  8791. return false;
  8792. }
  8793. if (!this._cache.scaling.equals(this.scaling))
  8794. return false;
  8795. return true;
  8796. };
  8797. AbstractMesh.prototype._initCache = function () {
  8798. _super.prototype._initCache.call(this);
  8799. this._cache.localMatrixUpdated = false;
  8800. this._cache.position = BABYLON.Vector3.Zero();
  8801. this._cache.scaling = BABYLON.Vector3.Zero();
  8802. this._cache.rotation = BABYLON.Vector3.Zero();
  8803. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8804. this._cache.billboardMode = -1;
  8805. };
  8806. AbstractMesh.prototype.markAsDirty = function (property) {
  8807. if (property === "rotation") {
  8808. this.rotationQuaternion = null;
  8809. }
  8810. this._currentRenderId = Number.MAX_VALUE;
  8811. this._isDirty = true;
  8812. };
  8813. AbstractMesh.prototype._updateBoundingInfo = function () {
  8814. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8815. this._boundingInfo.update(this.worldMatrixFromCache);
  8816. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8817. };
  8818. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8819. if (!this.subMeshes) {
  8820. return;
  8821. }
  8822. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8823. var subMesh = this.subMeshes[subIndex];
  8824. if (!subMesh.IsGlobal) {
  8825. subMesh.updateBoundingInfo(matrix);
  8826. }
  8827. }
  8828. };
  8829. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8830. if (this._isWorldMatrixFrozen) {
  8831. return this._worldMatrix;
  8832. }
  8833. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8834. this._currentRenderId = this.getScene().getRenderId();
  8835. return this._worldMatrix;
  8836. }
  8837. this._cache.position.copyFrom(this.position);
  8838. this._cache.scaling.copyFrom(this.scaling);
  8839. this._cache.pivotMatrixUpdated = false;
  8840. this._cache.billboardMode = this.billboardMode;
  8841. this._currentRenderId = this.getScene().getRenderId();
  8842. this._isDirty = false;
  8843. // Scaling
  8844. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8845. // Rotation
  8846. //rotate, if quaternion is set and rotation was used
  8847. if (this.rotationQuaternion) {
  8848. var len = this.rotation.length();
  8849. if (len) {
  8850. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8851. this.rotation.copyFromFloats(0, 0, 0);
  8852. }
  8853. }
  8854. if (this.rotationQuaternion) {
  8855. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8856. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8857. }
  8858. else {
  8859. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8860. this._cache.rotation.copyFrom(this.rotation);
  8861. }
  8862. // Translation
  8863. if (this.infiniteDistance && !this.parent) {
  8864. var camera = this.getScene().activeCamera;
  8865. if (camera) {
  8866. var cameraWorldMatrix = camera.getWorldMatrix();
  8867. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8868. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8869. }
  8870. }
  8871. else {
  8872. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8873. }
  8874. // Composing transformations
  8875. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8876. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8877. // Billboarding
  8878. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8879. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8880. var localPosition = BABYLON.Tmp.Vector3[0];
  8881. if (this.parent && this.parent.getWorldMatrix) {
  8882. this._markSyncedWithParent();
  8883. var parentMatrix;
  8884. if (this._meshToBoneReferal) {
  8885. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8886. parentMatrix = BABYLON.Tmp.Matrix[6];
  8887. }
  8888. else {
  8889. parentMatrix = this.parent.getWorldMatrix();
  8890. }
  8891. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8892. localPosition = BABYLON.Tmp.Vector3[1];
  8893. }
  8894. var zero = this.getScene().activeCamera.globalPosition.clone();
  8895. if (this.parent && this.parent.position) {
  8896. localPosition.addInPlace(this.parent.position);
  8897. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8898. }
  8899. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8900. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8901. zero.x = localPosition.x + BABYLON.Epsilon;
  8902. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8903. zero.y = localPosition.y + BABYLON.Epsilon;
  8904. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8905. zero.z = localPosition.z + BABYLON.Epsilon;
  8906. }
  8907. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8908. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8909. BABYLON.Tmp.Matrix[3].invert();
  8910. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8911. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8912. }
  8913. // Local world
  8914. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8915. // Parent
  8916. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8917. this._markSyncedWithParent();
  8918. if (this._meshToBoneReferal) {
  8919. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8920. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8921. }
  8922. else {
  8923. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8924. }
  8925. }
  8926. else {
  8927. this._worldMatrix.copyFrom(this._localWorld);
  8928. }
  8929. // Bounding info
  8930. this._updateBoundingInfo();
  8931. // Absolute position
  8932. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8933. // Callbacks
  8934. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8935. if (!this._poseMatrix) {
  8936. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8937. }
  8938. return this._worldMatrix;
  8939. };
  8940. /**
  8941. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8942. * @param func: callback function to add
  8943. */
  8944. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8945. this.onAfterWorldMatrixUpdateObservable.add(func);
  8946. };
  8947. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8948. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8949. };
  8950. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8951. this.computeWorldMatrix();
  8952. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8953. };
  8954. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8955. this.computeWorldMatrix();
  8956. var invLocalWorldMatrix = this._localWorld.clone();
  8957. invLocalWorldMatrix.invert();
  8958. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8959. };
  8960. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8961. this.computeWorldMatrix(true);
  8962. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8963. };
  8964. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8965. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8966. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8967. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8968. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8969. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8970. /// <returns>Mesh oriented towards targetMesh</returns>
  8971. yawCor = yawCor || 0; // default to zero if undefined
  8972. pitchCor = pitchCor || 0;
  8973. rollCor = rollCor || 0;
  8974. var dv = targetPoint.subtract(this.position);
  8975. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8976. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8977. var pitch = Math.atan2(dv.y, len);
  8978. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8979. };
  8980. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8981. this._meshToBoneReferal = affectedMesh;
  8982. this.parent = bone;
  8983. if (bone.getWorldMatrix().determinant() < 0) {
  8984. this.scalingDeterminant *= -1;
  8985. }
  8986. };
  8987. AbstractMesh.prototype.detachFromBone = function () {
  8988. if (this.parent.getWorldMatrix().determinant() < 0) {
  8989. this.scalingDeterminant *= -1;
  8990. }
  8991. this._meshToBoneReferal = null;
  8992. this.parent = null;
  8993. };
  8994. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8995. return this._boundingInfo.isInFrustum(frustumPlanes);
  8996. };
  8997. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8998. if (!camera) {
  8999. camera = this.getScene().activeCamera;
  9000. }
  9001. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9002. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9003. return false;
  9004. }
  9005. return true;
  9006. };
  9007. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9008. if (!this._boundingInfo || !mesh._boundingInfo) {
  9009. return false;
  9010. }
  9011. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9012. };
  9013. AbstractMesh.prototype.intersectsPoint = function (point) {
  9014. if (!this._boundingInfo) {
  9015. return false;
  9016. }
  9017. return this._boundingInfo.intersectsPoint(point);
  9018. };
  9019. // Physics
  9020. /**
  9021. * @Deprecated. Use new PhysicsImpostor instead.
  9022. * */
  9023. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9024. //legacy support
  9025. if (impostor.impostor) {
  9026. options = impostor;
  9027. impostor = impostor.impostor;
  9028. }
  9029. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9030. return this.physicsImpostor.physicsBody;
  9031. };
  9032. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9033. return this.physicsImpostor;
  9034. };
  9035. /**
  9036. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9037. */
  9038. AbstractMesh.prototype.getPhysicsMass = function () {
  9039. return this.physicsImpostor.getParam("mass");
  9040. };
  9041. /**
  9042. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9043. */
  9044. AbstractMesh.prototype.getPhysicsFriction = function () {
  9045. return this.physicsImpostor.getParam("friction");
  9046. };
  9047. /**
  9048. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9049. */
  9050. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9051. return this.physicsImpostor.getParam("resitution");
  9052. };
  9053. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9054. if (!camera) {
  9055. camera = this.getScene().activeCamera;
  9056. }
  9057. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9058. };
  9059. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9060. if (!camera) {
  9061. camera = this.getScene().activeCamera;
  9062. }
  9063. return this.absolutePosition.subtract(camera.position).length();
  9064. };
  9065. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9066. if (!this.physicsImpostor) {
  9067. return;
  9068. }
  9069. this.physicsImpostor.applyImpulse(force, contactPoint);
  9070. };
  9071. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9072. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9073. return;
  9074. }
  9075. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9076. mainPivot: pivot1,
  9077. connectedPivot: pivot2,
  9078. nativeParams: options
  9079. });
  9080. };
  9081. /**
  9082. * @Deprecated
  9083. */
  9084. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9085. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9086. this.updatePhysicsBody();
  9087. };
  9088. /**
  9089. * @Deprecated
  9090. * Calling this function is not needed anymore.
  9091. * The physics engine takes care of transofmration automatically.
  9092. */
  9093. AbstractMesh.prototype.updatePhysicsBody = function () {
  9094. //Unneeded
  9095. };
  9096. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9097. // Collisions
  9098. get: function () {
  9099. return this._checkCollisions;
  9100. },
  9101. set: function (collisionEnabled) {
  9102. this._checkCollisions = collisionEnabled;
  9103. if (this.getScene().workerCollisions) {
  9104. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9105. }
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9111. var globalPosition = this.getAbsolutePosition();
  9112. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9113. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9114. this._collider.radius = this.ellipsoid;
  9115. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9116. };
  9117. // Submeshes octree
  9118. /**
  9119. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9120. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9121. */
  9122. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9123. if (maxCapacity === void 0) { maxCapacity = 64; }
  9124. if (maxDepth === void 0) { maxDepth = 2; }
  9125. if (!this._submeshesOctree) {
  9126. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9127. }
  9128. this.computeWorldMatrix(true);
  9129. // Update octree
  9130. var bbox = this.getBoundingInfo().boundingBox;
  9131. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9132. return this._submeshesOctree;
  9133. };
  9134. // Collisions
  9135. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9136. this._generatePointsArray();
  9137. // Transformation
  9138. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9139. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9140. subMesh._lastColliderWorldVertices = [];
  9141. subMesh._trianglePlanes = [];
  9142. var start = subMesh.verticesStart;
  9143. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9144. for (var i = start; i < end; i++) {
  9145. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9146. }
  9147. }
  9148. // Collide
  9149. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9150. if (collider.collisionFound) {
  9151. collider.collidedMesh = this;
  9152. }
  9153. };
  9154. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9155. var subMeshes;
  9156. var len;
  9157. // Octrees
  9158. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9159. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9160. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9161. len = intersections.length;
  9162. subMeshes = intersections.data;
  9163. }
  9164. else {
  9165. subMeshes = this.subMeshes;
  9166. len = subMeshes.length;
  9167. }
  9168. for (var index = 0; index < len; index++) {
  9169. var subMesh = subMeshes[index];
  9170. // Bounding test
  9171. if (len > 1 && !subMesh._checkCollision(collider))
  9172. continue;
  9173. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9174. }
  9175. };
  9176. AbstractMesh.prototype._checkCollision = function (collider) {
  9177. // Bounding box test
  9178. if (!this._boundingInfo._checkCollision(collider))
  9179. return;
  9180. // Transformation matrix
  9181. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9182. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9183. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9184. };
  9185. // Picking
  9186. AbstractMesh.prototype._generatePointsArray = function () {
  9187. return false;
  9188. };
  9189. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9190. var pickingInfo = new BABYLON.PickingInfo();
  9191. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9192. return pickingInfo;
  9193. }
  9194. if (!this._generatePointsArray()) {
  9195. return pickingInfo;
  9196. }
  9197. var intersectInfo = null;
  9198. // Octrees
  9199. var subMeshes;
  9200. var len;
  9201. if (this._submeshesOctree && this.useOctreeForPicking) {
  9202. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9203. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9204. len = intersections.length;
  9205. subMeshes = intersections.data;
  9206. }
  9207. else {
  9208. subMeshes = this.subMeshes;
  9209. len = subMeshes.length;
  9210. }
  9211. for (var index = 0; index < len; index++) {
  9212. var subMesh = subMeshes[index];
  9213. // Bounding test
  9214. if (len > 1 && !subMesh.canIntersects(ray))
  9215. continue;
  9216. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9217. if (currentIntersectInfo) {
  9218. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9219. intersectInfo = currentIntersectInfo;
  9220. intersectInfo.subMeshId = index;
  9221. if (fastCheck) {
  9222. break;
  9223. }
  9224. }
  9225. }
  9226. }
  9227. if (intersectInfo) {
  9228. // Get picked point
  9229. var world = this.getWorldMatrix();
  9230. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9231. var direction = ray.direction.clone();
  9232. direction = direction.scale(intersectInfo.distance);
  9233. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9234. var pickedPoint = worldOrigin.add(worldDirection);
  9235. // Return result
  9236. pickingInfo.hit = true;
  9237. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9238. pickingInfo.pickedPoint = pickedPoint;
  9239. pickingInfo.pickedMesh = this;
  9240. pickingInfo.bu = intersectInfo.bu;
  9241. pickingInfo.bv = intersectInfo.bv;
  9242. pickingInfo.faceId = intersectInfo.faceId;
  9243. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9244. return pickingInfo;
  9245. }
  9246. return pickingInfo;
  9247. };
  9248. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9249. return null;
  9250. };
  9251. AbstractMesh.prototype.releaseSubMeshes = function () {
  9252. if (this.subMeshes) {
  9253. while (this.subMeshes.length) {
  9254. this.subMeshes[0].dispose();
  9255. }
  9256. }
  9257. else {
  9258. this.subMeshes = new Array();
  9259. }
  9260. };
  9261. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9262. var _this = this;
  9263. var index;
  9264. // Action manager
  9265. if (this.actionManager) {
  9266. this.actionManager.dispose();
  9267. this.actionManager = null;
  9268. }
  9269. // Skeleton
  9270. this.skeleton = null;
  9271. // Animations
  9272. this.getScene().stopAnimation(this);
  9273. // Physics
  9274. if (this.physicsImpostor) {
  9275. this.physicsImpostor.dispose();
  9276. }
  9277. // Intersections in progress
  9278. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9279. var other = this._intersectionsInProgress[index];
  9280. var pos = other._intersectionsInProgress.indexOf(this);
  9281. other._intersectionsInProgress.splice(pos, 1);
  9282. }
  9283. this._intersectionsInProgress = [];
  9284. // Lights
  9285. var lights = this.getScene().lights;
  9286. lights.forEach(function (light) {
  9287. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9288. if (meshIndex !== -1) {
  9289. light.includedOnlyMeshes.splice(meshIndex, 1);
  9290. }
  9291. meshIndex = light.excludedMeshes.indexOf(_this);
  9292. if (meshIndex !== -1) {
  9293. light.excludedMeshes.splice(meshIndex, 1);
  9294. }
  9295. });
  9296. // Edges
  9297. if (this._edgesRenderer) {
  9298. this._edgesRenderer.dispose();
  9299. this._edgesRenderer = null;
  9300. }
  9301. // SubMeshes
  9302. this.releaseSubMeshes();
  9303. // Remove from scene
  9304. this.getScene().removeMesh(this);
  9305. if (!doNotRecurse) {
  9306. // Particles
  9307. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9308. if (this.getScene().particleSystems[index].emitter === this) {
  9309. this.getScene().particleSystems[index].dispose();
  9310. index--;
  9311. }
  9312. }
  9313. // Children
  9314. var objects = this.getDescendants(true);
  9315. for (index = 0; index < objects.length; index++) {
  9316. objects[index].dispose();
  9317. }
  9318. }
  9319. else {
  9320. var childMeshes = this.getChildMeshes(true);
  9321. for (index = 0; index < childMeshes.length; index++) {
  9322. var child = childMeshes[index];
  9323. child.parent = null;
  9324. child.computeWorldMatrix(true);
  9325. }
  9326. }
  9327. _super.prototype.dispose.call(this);
  9328. this.onAfterWorldMatrixUpdateObservable.clear();
  9329. this._isDisposed = true;
  9330. // Callback
  9331. if (this.onDispose) {
  9332. this.onDispose();
  9333. }
  9334. };
  9335. // Statics
  9336. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9337. AbstractMesh._BILLBOARDMODE_X = 1;
  9338. AbstractMesh._BILLBOARDMODE_Y = 2;
  9339. AbstractMesh._BILLBOARDMODE_Z = 4;
  9340. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9341. return AbstractMesh;
  9342. }(BABYLON.Node));
  9343. BABYLON.AbstractMesh = AbstractMesh;
  9344. })(BABYLON || (BABYLON = {}));
  9345. var BABYLON;
  9346. (function (BABYLON) {
  9347. var Light = (function (_super) {
  9348. __extends(Light, _super);
  9349. function Light(name, scene) {
  9350. _super.call(this, name, scene);
  9351. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9352. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9353. this.intensity = 1.0;
  9354. this.range = Number.MAX_VALUE;
  9355. this.includeOnlyWithLayerMask = 0;
  9356. this.includedOnlyMeshes = new Array();
  9357. this.excludedMeshes = new Array();
  9358. this.excludeWithLayerMask = 0;
  9359. // PBR Properties.
  9360. this.radius = 0.00001;
  9361. this._excludedMeshesIds = new Array();
  9362. this._includedOnlyMeshesIds = new Array();
  9363. scene.addLight(this);
  9364. }
  9365. /**
  9366. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9367. */
  9368. Light.prototype.toString = function (fullDetails) {
  9369. var ret = "Name: " + this.name;
  9370. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9371. if (this.animations) {
  9372. for (var i = 0; i < this.animations.length; i++) {
  9373. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9374. }
  9375. }
  9376. if (fullDetails) {
  9377. }
  9378. return ret;
  9379. };
  9380. Light.prototype.getShadowGenerator = function () {
  9381. return this._shadowGenerator;
  9382. };
  9383. Light.prototype.getAbsolutePosition = function () {
  9384. return BABYLON.Vector3.Zero();
  9385. };
  9386. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9387. };
  9388. Light.prototype._getWorldMatrix = function () {
  9389. return BABYLON.Matrix.Identity();
  9390. };
  9391. Light.prototype.canAffectMesh = function (mesh) {
  9392. if (!mesh) {
  9393. return true;
  9394. }
  9395. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9396. return false;
  9397. }
  9398. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9399. return false;
  9400. }
  9401. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9402. return false;
  9403. }
  9404. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9405. return false;
  9406. }
  9407. return true;
  9408. };
  9409. Light.prototype.getWorldMatrix = function () {
  9410. this._currentRenderId = this.getScene().getRenderId();
  9411. var worldMatrix = this._getWorldMatrix();
  9412. if (this.parent && this.parent.getWorldMatrix) {
  9413. if (!this._parentedWorldMatrix) {
  9414. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9415. }
  9416. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9417. this._markSyncedWithParent();
  9418. return this._parentedWorldMatrix;
  9419. }
  9420. return worldMatrix;
  9421. };
  9422. Light.prototype.dispose = function () {
  9423. if (this._shadowGenerator) {
  9424. this._shadowGenerator.dispose();
  9425. this._shadowGenerator = null;
  9426. }
  9427. // Animations
  9428. this.getScene().stopAnimation(this);
  9429. // Remove from scene
  9430. this.getScene().removeLight(this);
  9431. _super.prototype.dispose.call(this);
  9432. };
  9433. Light.prototype.getTypeID = function () {
  9434. return 0;
  9435. };
  9436. Light.prototype.clone = function (name) {
  9437. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9438. };
  9439. Light.prototype.serialize = function () {
  9440. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9441. // Type
  9442. serializationObject.type = this.getTypeID();
  9443. // Parent
  9444. if (this.parent) {
  9445. serializationObject.parentId = this.parent.id;
  9446. }
  9447. // Inclusion / exclusions
  9448. if (this.excludedMeshes.length > 0) {
  9449. serializationObject.excludedMeshesIds = [];
  9450. this.excludedMeshes.forEach(function (mesh) {
  9451. serializationObject.excludedMeshesIds.push(mesh.id);
  9452. });
  9453. }
  9454. if (this.includedOnlyMeshes.length > 0) {
  9455. serializationObject.includedOnlyMeshesIds = [];
  9456. this.includedOnlyMeshes.forEach(function (mesh) {
  9457. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9458. });
  9459. }
  9460. // Animations
  9461. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9462. serializationObject.ranges = this.serializeAnimationRanges();
  9463. return serializationObject;
  9464. };
  9465. Light.GetConstructorFromName = function (type, name, scene) {
  9466. switch (type) {
  9467. case 0:
  9468. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9469. case 1:
  9470. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9471. case 2:
  9472. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9473. case 3:
  9474. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9475. }
  9476. };
  9477. Light.Parse = function (parsedLight, scene) {
  9478. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9479. // Inclusion / exclusions
  9480. if (parsedLight.excludedMeshesIds) {
  9481. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9482. }
  9483. if (parsedLight.includedOnlyMeshesIds) {
  9484. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9485. }
  9486. // Parent
  9487. if (parsedLight.parentId) {
  9488. light._waitingParentId = parsedLight.parentId;
  9489. }
  9490. // Animations
  9491. if (parsedLight.animations) {
  9492. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9493. var parsedAnimation = parsedLight.animations[animationIndex];
  9494. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9495. }
  9496. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9497. }
  9498. if (parsedLight.autoAnimate) {
  9499. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9500. }
  9501. return light;
  9502. };
  9503. __decorate([
  9504. BABYLON.serializeAsColor3()
  9505. ], Light.prototype, "diffuse", void 0);
  9506. __decorate([
  9507. BABYLON.serializeAsColor3()
  9508. ], Light.prototype, "specular", void 0);
  9509. __decorate([
  9510. BABYLON.serialize()
  9511. ], Light.prototype, "intensity", void 0);
  9512. __decorate([
  9513. BABYLON.serialize()
  9514. ], Light.prototype, "range", void 0);
  9515. __decorate([
  9516. BABYLON.serialize()
  9517. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9518. __decorate([
  9519. BABYLON.serialize()
  9520. ], Light.prototype, "excludeWithLayerMask", void 0);
  9521. __decorate([
  9522. BABYLON.serialize()
  9523. ], Light.prototype, "radius", void 0);
  9524. return Light;
  9525. }(BABYLON.Node));
  9526. BABYLON.Light = Light;
  9527. })(BABYLON || (BABYLON = {}));
  9528. var BABYLON;
  9529. (function (BABYLON) {
  9530. var PointLight = (function (_super) {
  9531. __extends(PointLight, _super);
  9532. function PointLight(name, position, scene) {
  9533. _super.call(this, name, scene);
  9534. this.position = position;
  9535. }
  9536. PointLight.prototype.getAbsolutePosition = function () {
  9537. return this.transformedPosition ? this.transformedPosition : this.position;
  9538. };
  9539. PointLight.prototype.computeTransformedPosition = function () {
  9540. if (this.parent && this.parent.getWorldMatrix) {
  9541. if (!this.transformedPosition) {
  9542. this.transformedPosition = BABYLON.Vector3.Zero();
  9543. }
  9544. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9545. return true;
  9546. }
  9547. return false;
  9548. };
  9549. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9550. if (this.parent && this.parent.getWorldMatrix) {
  9551. this.computeTransformedPosition();
  9552. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9553. return;
  9554. }
  9555. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9556. };
  9557. PointLight.prototype.needCube = function () {
  9558. return true;
  9559. };
  9560. PointLight.prototype.supportsVSM = function () {
  9561. return false;
  9562. };
  9563. PointLight.prototype.needRefreshPerFrame = function () {
  9564. return false;
  9565. };
  9566. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9567. switch (faceIndex) {
  9568. case 0:
  9569. return new BABYLON.Vector3(1, 0, 0);
  9570. case 1:
  9571. return new BABYLON.Vector3(-1, 0, 0);
  9572. case 2:
  9573. return new BABYLON.Vector3(0, -1, 0);
  9574. case 3:
  9575. return new BABYLON.Vector3(0, 1, 0);
  9576. case 4:
  9577. return new BABYLON.Vector3(0, 0, 1);
  9578. case 5:
  9579. return new BABYLON.Vector3(0, 0, -1);
  9580. }
  9581. return BABYLON.Vector3.Zero();
  9582. };
  9583. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9584. var activeCamera = this.getScene().activeCamera;
  9585. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9586. };
  9587. PointLight.prototype._getWorldMatrix = function () {
  9588. if (!this._worldMatrix) {
  9589. this._worldMatrix = BABYLON.Matrix.Identity();
  9590. }
  9591. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9592. return this._worldMatrix;
  9593. };
  9594. PointLight.prototype.getTypeID = function () {
  9595. return 0;
  9596. };
  9597. __decorate([
  9598. BABYLON.serializeAsVector3()
  9599. ], PointLight.prototype, "position", void 0);
  9600. return PointLight;
  9601. }(BABYLON.Light));
  9602. BABYLON.PointLight = PointLight;
  9603. })(BABYLON || (BABYLON = {}));
  9604. var BABYLON;
  9605. (function (BABYLON) {
  9606. var SpotLight = (function (_super) {
  9607. __extends(SpotLight, _super);
  9608. function SpotLight(name, position, direction, angle, exponent, scene) {
  9609. _super.call(this, name, scene);
  9610. this.position = position;
  9611. this.direction = direction;
  9612. this.angle = angle;
  9613. this.exponent = exponent;
  9614. }
  9615. SpotLight.prototype.getAbsolutePosition = function () {
  9616. return this.transformedPosition ? this.transformedPosition : this.position;
  9617. };
  9618. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9619. var activeCamera = this.getScene().activeCamera;
  9620. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9621. };
  9622. SpotLight.prototype.needCube = function () {
  9623. return false;
  9624. };
  9625. SpotLight.prototype.supportsVSM = function () {
  9626. return true;
  9627. };
  9628. SpotLight.prototype.needRefreshPerFrame = function () {
  9629. return false;
  9630. };
  9631. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9632. return this.direction;
  9633. };
  9634. SpotLight.prototype.setDirectionToTarget = function (target) {
  9635. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9636. return this.direction;
  9637. };
  9638. SpotLight.prototype.computeTransformedPosition = function () {
  9639. if (this.parent && this.parent.getWorldMatrix) {
  9640. if (!this.transformedPosition) {
  9641. this.transformedPosition = BABYLON.Vector3.Zero();
  9642. }
  9643. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9644. return true;
  9645. }
  9646. return false;
  9647. };
  9648. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9649. var normalizeDirection;
  9650. if (this.parent && this.parent.getWorldMatrix) {
  9651. if (!this._transformedDirection) {
  9652. this._transformedDirection = BABYLON.Vector3.Zero();
  9653. }
  9654. this.computeTransformedPosition();
  9655. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9656. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9657. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9658. }
  9659. else {
  9660. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9661. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9662. }
  9663. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9664. };
  9665. SpotLight.prototype._getWorldMatrix = function () {
  9666. if (!this._worldMatrix) {
  9667. this._worldMatrix = BABYLON.Matrix.Identity();
  9668. }
  9669. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9670. return this._worldMatrix;
  9671. };
  9672. SpotLight.prototype.getTypeID = function () {
  9673. return 2;
  9674. };
  9675. __decorate([
  9676. BABYLON.serializeAsVector3()
  9677. ], SpotLight.prototype, "position", void 0);
  9678. __decorate([
  9679. BABYLON.serializeAsVector3()
  9680. ], SpotLight.prototype, "direction", void 0);
  9681. __decorate([
  9682. BABYLON.serialize()
  9683. ], SpotLight.prototype, "angle", void 0);
  9684. __decorate([
  9685. BABYLON.serialize()
  9686. ], SpotLight.prototype, "exponent", void 0);
  9687. return SpotLight;
  9688. }(BABYLON.Light));
  9689. BABYLON.SpotLight = SpotLight;
  9690. })(BABYLON || (BABYLON = {}));
  9691. var BABYLON;
  9692. (function (BABYLON) {
  9693. var HemisphericLight = (function (_super) {
  9694. __extends(HemisphericLight, _super);
  9695. function HemisphericLight(name, direction, scene) {
  9696. _super.call(this, name, scene);
  9697. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9698. this.direction = direction;
  9699. }
  9700. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9701. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9702. return this.direction;
  9703. };
  9704. HemisphericLight.prototype.getShadowGenerator = function () {
  9705. return null;
  9706. };
  9707. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9708. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9709. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9710. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9711. };
  9712. HemisphericLight.prototype._getWorldMatrix = function () {
  9713. if (!this._worldMatrix) {
  9714. this._worldMatrix = BABYLON.Matrix.Identity();
  9715. }
  9716. return this._worldMatrix;
  9717. };
  9718. HemisphericLight.prototype.getTypeID = function () {
  9719. return 3;
  9720. };
  9721. __decorate([
  9722. BABYLON.serializeAsColor3()
  9723. ], HemisphericLight.prototype, "groundColor", void 0);
  9724. __decorate([
  9725. BABYLON.serializeAsVector3()
  9726. ], HemisphericLight.prototype, "direction", void 0);
  9727. return HemisphericLight;
  9728. }(BABYLON.Light));
  9729. BABYLON.HemisphericLight = HemisphericLight;
  9730. })(BABYLON || (BABYLON = {}));
  9731. var BABYLON;
  9732. (function (BABYLON) {
  9733. var DirectionalLight = (function (_super) {
  9734. __extends(DirectionalLight, _super);
  9735. function DirectionalLight(name, direction, scene) {
  9736. _super.call(this, name, scene);
  9737. this.shadowOrthoScale = 0.5;
  9738. this.autoUpdateExtends = true;
  9739. // Cache
  9740. this._orthoLeft = Number.MAX_VALUE;
  9741. this._orthoRight = Number.MIN_VALUE;
  9742. this._orthoTop = Number.MIN_VALUE;
  9743. this._orthoBottom = Number.MAX_VALUE;
  9744. this.position = direction.scale(-1);
  9745. this.direction = direction;
  9746. }
  9747. DirectionalLight.prototype.getAbsolutePosition = function () {
  9748. return this.transformedPosition ? this.transformedPosition : this.position;
  9749. };
  9750. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9751. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9752. return this.direction;
  9753. };
  9754. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9755. var activeCamera = this.getScene().activeCamera;
  9756. // Check extends
  9757. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9758. var tempVector3 = BABYLON.Vector3.Zero();
  9759. this._orthoLeft = Number.MAX_VALUE;
  9760. this._orthoRight = Number.MIN_VALUE;
  9761. this._orthoTop = Number.MIN_VALUE;
  9762. this._orthoBottom = Number.MAX_VALUE;
  9763. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9764. var mesh = renderList[meshIndex];
  9765. if (!mesh) {
  9766. continue;
  9767. }
  9768. var boundingInfo = mesh.getBoundingInfo();
  9769. if (!boundingInfo) {
  9770. continue;
  9771. }
  9772. var boundingBox = boundingInfo.boundingBox;
  9773. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9774. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9775. if (tempVector3.x < this._orthoLeft)
  9776. this._orthoLeft = tempVector3.x;
  9777. if (tempVector3.y < this._orthoBottom)
  9778. this._orthoBottom = tempVector3.y;
  9779. if (tempVector3.x > this._orthoRight)
  9780. this._orthoRight = tempVector3.x;
  9781. if (tempVector3.y > this._orthoTop)
  9782. this._orthoTop = tempVector3.y;
  9783. }
  9784. }
  9785. }
  9786. var xOffset = this._orthoRight - this._orthoLeft;
  9787. var yOffset = this._orthoTop - this._orthoBottom;
  9788. 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);
  9789. };
  9790. DirectionalLight.prototype.supportsVSM = function () {
  9791. return true;
  9792. };
  9793. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9794. return true;
  9795. };
  9796. DirectionalLight.prototype.needCube = function () {
  9797. return false;
  9798. };
  9799. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9800. return this.direction;
  9801. };
  9802. DirectionalLight.prototype.computeTransformedPosition = function () {
  9803. if (this.parent && this.parent.getWorldMatrix) {
  9804. if (!this.transformedPosition) {
  9805. this.transformedPosition = BABYLON.Vector3.Zero();
  9806. }
  9807. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9808. return true;
  9809. }
  9810. return false;
  9811. };
  9812. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9813. if (this.parent && this.parent.getWorldMatrix) {
  9814. if (!this._transformedDirection) {
  9815. this._transformedDirection = BABYLON.Vector3.Zero();
  9816. }
  9817. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9818. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9819. return;
  9820. }
  9821. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9822. };
  9823. DirectionalLight.prototype._getWorldMatrix = function () {
  9824. if (!this._worldMatrix) {
  9825. this._worldMatrix = BABYLON.Matrix.Identity();
  9826. }
  9827. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9828. return this._worldMatrix;
  9829. };
  9830. DirectionalLight.prototype.getTypeID = function () {
  9831. return 1;
  9832. };
  9833. __decorate([
  9834. BABYLON.serializeAsVector3()
  9835. ], DirectionalLight.prototype, "position", void 0);
  9836. __decorate([
  9837. BABYLON.serializeAsVector3()
  9838. ], DirectionalLight.prototype, "direction", void 0);
  9839. __decorate([
  9840. BABYLON.serialize()
  9841. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9842. __decorate([
  9843. BABYLON.serialize()
  9844. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9845. return DirectionalLight;
  9846. }(BABYLON.Light));
  9847. BABYLON.DirectionalLight = DirectionalLight;
  9848. })(BABYLON || (BABYLON = {}));
  9849. var BABYLON;
  9850. (function (BABYLON) {
  9851. var ShadowGenerator = (function () {
  9852. function ShadowGenerator(mapSize, light) {
  9853. var _this = this;
  9854. // Members
  9855. this._filter = ShadowGenerator.FILTER_NONE;
  9856. this.blurScale = 2;
  9857. this._blurBoxOffset = 0;
  9858. this._bias = 0.00005;
  9859. this._lightDirection = BABYLON.Vector3.Zero();
  9860. this.forceBackFacesOnly = false;
  9861. this._darkness = 0;
  9862. this._transparencyShadow = false;
  9863. this._viewMatrix = BABYLON.Matrix.Zero();
  9864. this._projectionMatrix = BABYLON.Matrix.Zero();
  9865. this._transformMatrix = BABYLON.Matrix.Zero();
  9866. this._worldViewProjection = BABYLON.Matrix.Zero();
  9867. this._currentFaceIndex = 0;
  9868. this._currentFaceIndexCache = 0;
  9869. this._light = light;
  9870. this._scene = light.getScene();
  9871. this._mapSize = mapSize;
  9872. light._shadowGenerator = this;
  9873. // Render target
  9874. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9875. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9876. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9877. this._shadowMap.anisotropicFilteringLevel = 1;
  9878. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9879. this._shadowMap.renderParticles = false;
  9880. this._shadowMap.onBeforeRender = function (faceIndex) {
  9881. _this._currentFaceIndex = faceIndex;
  9882. };
  9883. this._shadowMap.onAfterUnbind = function () {
  9884. if (!_this.useBlurVarianceShadowMap) {
  9885. return;
  9886. }
  9887. if (!_this._shadowMap2) {
  9888. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9889. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9890. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9891. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9892. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9893. _this._downSamplePostprocess.onApply = function (effect) {
  9894. effect.setTexture("textureSampler", _this._shadowMap);
  9895. };
  9896. _this.blurBoxOffset = 1;
  9897. }
  9898. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9899. };
  9900. // Custom render function
  9901. var renderSubMesh = function (subMesh) {
  9902. var mesh = subMesh.getRenderingMesh();
  9903. var scene = _this._scene;
  9904. var engine = scene.getEngine();
  9905. // Culling
  9906. engine.setState(subMesh.getMaterial().backFaceCulling);
  9907. // Managing instances
  9908. var batch = mesh._getInstancesRenderList(subMesh._id);
  9909. if (batch.mustReturn) {
  9910. return;
  9911. }
  9912. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9913. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9914. engine.enableEffect(_this._effect);
  9915. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9916. var material = subMesh.getMaterial();
  9917. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9918. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9919. if (_this.getLight().needCube()) {
  9920. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9921. }
  9922. // Alpha test
  9923. if (material && material.needAlphaTesting()) {
  9924. var alphaTexture = material.getAlphaTestTexture();
  9925. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9926. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9927. }
  9928. // Bones
  9929. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9930. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9931. }
  9932. if (_this.forceBackFacesOnly) {
  9933. engine.setState(true, 0, false, true);
  9934. }
  9935. // Draw
  9936. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9937. if (_this.forceBackFacesOnly) {
  9938. engine.setState(true, 0, false, false);
  9939. }
  9940. }
  9941. else {
  9942. // Need to reset refresh rate of the shadowMap
  9943. _this._shadowMap.resetRefreshCounter();
  9944. }
  9945. };
  9946. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9947. var index;
  9948. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9949. renderSubMesh(opaqueSubMeshes.data[index]);
  9950. }
  9951. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9952. renderSubMesh(alphaTestSubMeshes.data[index]);
  9953. }
  9954. if (_this._transparencyShadow) {
  9955. for (index = 0; index < transparentSubMeshes.length; index++) {
  9956. renderSubMesh(transparentSubMeshes.data[index]);
  9957. }
  9958. }
  9959. };
  9960. this._shadowMap.onClear = function (engine) {
  9961. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9962. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9963. }
  9964. else {
  9965. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9966. }
  9967. };
  9968. }
  9969. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9970. // Static
  9971. get: function () {
  9972. return ShadowGenerator._FILTER_NONE;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9978. get: function () {
  9979. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9985. get: function () {
  9986. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9992. get: function () {
  9993. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9999. get: function () {
  10000. return this._bias;
  10001. },
  10002. set: function (bias) {
  10003. this._bias = bias;
  10004. },
  10005. enumerable: true,
  10006. configurable: true
  10007. });
  10008. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10009. get: function () {
  10010. return this._blurBoxOffset;
  10011. },
  10012. set: function (value) {
  10013. var _this = this;
  10014. if (this._blurBoxOffset === value) {
  10015. return;
  10016. }
  10017. this._blurBoxOffset = value;
  10018. if (this._boxBlurPostprocess) {
  10019. this._boxBlurPostprocess.dispose();
  10020. }
  10021. 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);
  10022. this._boxBlurPostprocess.onApply = function (effect) {
  10023. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10024. };
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10030. get: function () {
  10031. return this._filter;
  10032. },
  10033. set: function (value) {
  10034. if (this._filter === value) {
  10035. return;
  10036. }
  10037. this._filter = value;
  10038. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10039. this._shadowMap.anisotropicFilteringLevel = 16;
  10040. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10041. }
  10042. else {
  10043. this._shadowMap.anisotropicFilteringLevel = 1;
  10044. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10045. }
  10046. },
  10047. enumerable: true,
  10048. configurable: true
  10049. });
  10050. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10051. get: function () {
  10052. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10053. },
  10054. set: function (value) {
  10055. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10061. get: function () {
  10062. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10063. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10064. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10065. },
  10066. set: function (value) {
  10067. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10073. get: function () {
  10074. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10075. },
  10076. set: function (value) {
  10077. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10083. var defines = [];
  10084. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10085. defines.push("#define VSM");
  10086. }
  10087. if (this.getLight().needCube()) {
  10088. defines.push("#define CUBEMAP");
  10089. }
  10090. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10091. var mesh = subMesh.getMesh();
  10092. var material = subMesh.getMaterial();
  10093. // Alpha test
  10094. if (material && material.needAlphaTesting()) {
  10095. defines.push("#define ALPHATEST");
  10096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10097. attribs.push(BABYLON.VertexBuffer.UVKind);
  10098. defines.push("#define UV1");
  10099. }
  10100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10102. defines.push("#define UV2");
  10103. }
  10104. }
  10105. // Bones
  10106. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10107. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10108. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10109. if (mesh.numBoneInfluencers > 4) {
  10110. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10111. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10112. }
  10113. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10114. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10115. }
  10116. else {
  10117. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10118. }
  10119. // Instances
  10120. if (useInstances) {
  10121. defines.push("#define INSTANCES");
  10122. attribs.push("world0");
  10123. attribs.push("world1");
  10124. attribs.push("world2");
  10125. attribs.push("world3");
  10126. }
  10127. // Get correct effect
  10128. var join = defines.join("\n");
  10129. if (this._cachedDefines !== join) {
  10130. this._cachedDefines = join;
  10131. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10132. }
  10133. return this._effect.isReady();
  10134. };
  10135. ShadowGenerator.prototype.getShadowMap = function () {
  10136. return this._shadowMap;
  10137. };
  10138. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10139. if (this._shadowMap2) {
  10140. return this._shadowMap2;
  10141. }
  10142. return this._shadowMap;
  10143. };
  10144. ShadowGenerator.prototype.getLight = function () {
  10145. return this._light;
  10146. };
  10147. // Methods
  10148. ShadowGenerator.prototype.getTransformMatrix = function () {
  10149. var scene = this._scene;
  10150. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10151. return this._transformMatrix;
  10152. }
  10153. this._currentRenderID = scene.getRenderId();
  10154. this._currentFaceIndexCache = this._currentFaceIndex;
  10155. var lightPosition = this._light.position;
  10156. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10157. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10158. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10159. }
  10160. if (this._light.computeTransformedPosition()) {
  10161. lightPosition = this._light.transformedPosition;
  10162. }
  10163. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10164. this._cachedPosition = lightPosition.clone();
  10165. this._cachedDirection = this._lightDirection.clone();
  10166. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10167. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10168. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10169. }
  10170. return this._transformMatrix;
  10171. };
  10172. ShadowGenerator.prototype.getDarkness = function () {
  10173. return this._darkness;
  10174. };
  10175. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10176. if (darkness >= 1.0)
  10177. this._darkness = 1.0;
  10178. else if (darkness <= 0.0)
  10179. this._darkness = 0.0;
  10180. else
  10181. this._darkness = darkness;
  10182. };
  10183. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10184. this._transparencyShadow = hasShadow;
  10185. };
  10186. ShadowGenerator.prototype._packHalf = function (depth) {
  10187. var scale = depth * 255.0;
  10188. var fract = scale - Math.floor(scale);
  10189. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10190. };
  10191. ShadowGenerator.prototype.dispose = function () {
  10192. this._shadowMap.dispose();
  10193. if (this._shadowMap2) {
  10194. this._shadowMap2.dispose();
  10195. }
  10196. if (this._downSamplePostprocess) {
  10197. this._downSamplePostprocess.dispose();
  10198. }
  10199. if (this._boxBlurPostprocess) {
  10200. this._boxBlurPostprocess.dispose();
  10201. }
  10202. };
  10203. ShadowGenerator.prototype.serialize = function () {
  10204. var serializationObject = {};
  10205. serializationObject.lightId = this._light.id;
  10206. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10207. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10208. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10209. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10210. serializationObject.renderList = [];
  10211. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10212. var mesh = this.getShadowMap().renderList[meshIndex];
  10213. serializationObject.renderList.push(mesh.id);
  10214. }
  10215. return serializationObject;
  10216. };
  10217. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10218. //casting to point light, as light is missing the position attr and typescript complains.
  10219. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10220. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10221. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10222. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10223. shadowGenerator.getShadowMap().renderList.push(mesh);
  10224. }
  10225. if (parsedShadowGenerator.usePoissonSampling) {
  10226. shadowGenerator.usePoissonSampling = true;
  10227. }
  10228. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10229. shadowGenerator.useVarianceShadowMap = true;
  10230. }
  10231. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10232. shadowGenerator.useBlurVarianceShadowMap = true;
  10233. if (parsedShadowGenerator.blurScale) {
  10234. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10235. }
  10236. if (parsedShadowGenerator.blurBoxOffset) {
  10237. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10238. }
  10239. }
  10240. if (parsedShadowGenerator.bias !== undefined) {
  10241. shadowGenerator.bias = parsedShadowGenerator.bias;
  10242. }
  10243. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10244. return shadowGenerator;
  10245. };
  10246. ShadowGenerator._FILTER_NONE = 0;
  10247. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10248. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10249. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10250. return ShadowGenerator;
  10251. }());
  10252. BABYLON.ShadowGenerator = ShadowGenerator;
  10253. })(BABYLON || (BABYLON = {}));
  10254. var BABYLON;
  10255. (function (BABYLON) {
  10256. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10257. if (boxMin.x > sphereCenter.x + sphereRadius)
  10258. return false;
  10259. if (sphereCenter.x - sphereRadius > boxMax.x)
  10260. return false;
  10261. if (boxMin.y > sphereCenter.y + sphereRadius)
  10262. return false;
  10263. if (sphereCenter.y - sphereRadius > boxMax.y)
  10264. return false;
  10265. if (boxMin.z > sphereCenter.z + sphereRadius)
  10266. return false;
  10267. if (sphereCenter.z - sphereRadius > boxMax.z)
  10268. return false;
  10269. return true;
  10270. };
  10271. var getLowestRoot = function (a, b, c, maxR) {
  10272. var determinant = b * b - 4.0 * a * c;
  10273. var result = { root: 0, found: false };
  10274. if (determinant < 0)
  10275. return result;
  10276. var sqrtD = Math.sqrt(determinant);
  10277. var r1 = (-b - sqrtD) / (2.0 * a);
  10278. var r2 = (-b + sqrtD) / (2.0 * a);
  10279. if (r1 > r2) {
  10280. var temp = r2;
  10281. r2 = r1;
  10282. r1 = temp;
  10283. }
  10284. if (r1 > 0 && r1 < maxR) {
  10285. result.root = r1;
  10286. result.found = true;
  10287. return result;
  10288. }
  10289. if (r2 > 0 && r2 < maxR) {
  10290. result.root = r2;
  10291. result.found = true;
  10292. return result;
  10293. }
  10294. return result;
  10295. };
  10296. var Collider = (function () {
  10297. function Collider() {
  10298. this.radius = new BABYLON.Vector3(1, 1, 1);
  10299. this.retry = 0;
  10300. this.basePointWorld = BABYLON.Vector3.Zero();
  10301. this.velocityWorld = BABYLON.Vector3.Zero();
  10302. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10303. this._collisionPoint = BABYLON.Vector3.Zero();
  10304. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10305. this._tempVector = BABYLON.Vector3.Zero();
  10306. this._tempVector2 = BABYLON.Vector3.Zero();
  10307. this._tempVector3 = BABYLON.Vector3.Zero();
  10308. this._tempVector4 = BABYLON.Vector3.Zero();
  10309. this._edge = BABYLON.Vector3.Zero();
  10310. this._baseToVertex = BABYLON.Vector3.Zero();
  10311. this._destinationPoint = BABYLON.Vector3.Zero();
  10312. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10313. this._displacementVector = BABYLON.Vector3.Zero();
  10314. }
  10315. // Methods
  10316. Collider.prototype._initialize = function (source, dir, e) {
  10317. this.velocity = dir;
  10318. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10319. this.basePoint = source;
  10320. source.multiplyToRef(this.radius, this.basePointWorld);
  10321. dir.multiplyToRef(this.radius, this.velocityWorld);
  10322. this.velocityWorldLength = this.velocityWorld.length();
  10323. this.epsilon = e;
  10324. this.collisionFound = false;
  10325. };
  10326. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10327. pa.subtractToRef(point, this._tempVector);
  10328. pb.subtractToRef(point, this._tempVector2);
  10329. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10330. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10331. if (d < 0)
  10332. return false;
  10333. pc.subtractToRef(point, this._tempVector3);
  10334. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10335. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10336. if (d < 0)
  10337. return false;
  10338. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10339. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10340. return d >= 0;
  10341. };
  10342. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10343. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10344. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10345. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10346. return false;
  10347. }
  10348. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10349. return false;
  10350. return true;
  10351. };
  10352. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10353. var t0;
  10354. var embeddedInPlane = false;
  10355. //defensive programming, actually not needed.
  10356. if (!trianglePlaneArray) {
  10357. trianglePlaneArray = [];
  10358. }
  10359. if (!trianglePlaneArray[faceIndex]) {
  10360. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10361. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10362. }
  10363. var trianglePlane = trianglePlaneArray[faceIndex];
  10364. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10365. return;
  10366. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10367. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10368. if (normalDotVelocity == 0) {
  10369. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10370. return;
  10371. embeddedInPlane = true;
  10372. t0 = 0;
  10373. }
  10374. else {
  10375. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10376. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10377. if (t0 > t1) {
  10378. var temp = t1;
  10379. t1 = t0;
  10380. t0 = temp;
  10381. }
  10382. if (t0 > 1.0 || t1 < 0.0)
  10383. return;
  10384. if (t0 < 0)
  10385. t0 = 0;
  10386. if (t0 > 1.0)
  10387. t0 = 1.0;
  10388. }
  10389. this._collisionPoint.copyFromFloats(0, 0, 0);
  10390. var found = false;
  10391. var t = 1.0;
  10392. if (!embeddedInPlane) {
  10393. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10394. this.velocity.scaleToRef(t0, this._tempVector);
  10395. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10396. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10397. found = true;
  10398. t = t0;
  10399. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10400. }
  10401. }
  10402. if (!found) {
  10403. var velocitySquaredLength = this.velocity.lengthSquared();
  10404. var a = velocitySquaredLength;
  10405. this.basePoint.subtractToRef(p1, this._tempVector);
  10406. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10407. var c = this._tempVector.lengthSquared() - 1.0;
  10408. var lowestRoot = getLowestRoot(a, b, c, t);
  10409. if (lowestRoot.found) {
  10410. t = lowestRoot.root;
  10411. found = true;
  10412. this._collisionPoint.copyFrom(p1);
  10413. }
  10414. this.basePoint.subtractToRef(p2, this._tempVector);
  10415. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10416. c = this._tempVector.lengthSquared() - 1.0;
  10417. lowestRoot = getLowestRoot(a, b, c, t);
  10418. if (lowestRoot.found) {
  10419. t = lowestRoot.root;
  10420. found = true;
  10421. this._collisionPoint.copyFrom(p2);
  10422. }
  10423. this.basePoint.subtractToRef(p3, this._tempVector);
  10424. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10425. c = this._tempVector.lengthSquared() - 1.0;
  10426. lowestRoot = getLowestRoot(a, b, c, t);
  10427. if (lowestRoot.found) {
  10428. t = lowestRoot.root;
  10429. found = true;
  10430. this._collisionPoint.copyFrom(p3);
  10431. }
  10432. p2.subtractToRef(p1, this._edge);
  10433. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10434. var edgeSquaredLength = this._edge.lengthSquared();
  10435. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10436. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10437. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10438. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10439. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10440. lowestRoot = getLowestRoot(a, b, c, t);
  10441. if (lowestRoot.found) {
  10442. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10443. if (f >= 0.0 && f <= 1.0) {
  10444. t = lowestRoot.root;
  10445. found = true;
  10446. this._edge.scaleInPlace(f);
  10447. p1.addToRef(this._edge, this._collisionPoint);
  10448. }
  10449. }
  10450. p3.subtractToRef(p2, this._edge);
  10451. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10452. edgeSquaredLength = this._edge.lengthSquared();
  10453. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10454. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10455. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10456. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10457. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10458. lowestRoot = getLowestRoot(a, b, c, t);
  10459. if (lowestRoot.found) {
  10460. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10461. if (f >= 0.0 && f <= 1.0) {
  10462. t = lowestRoot.root;
  10463. found = true;
  10464. this._edge.scaleInPlace(f);
  10465. p2.addToRef(this._edge, this._collisionPoint);
  10466. }
  10467. }
  10468. p1.subtractToRef(p3, this._edge);
  10469. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10470. edgeSquaredLength = this._edge.lengthSquared();
  10471. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10472. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10473. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10474. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10475. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10476. lowestRoot = getLowestRoot(a, b, c, t);
  10477. if (lowestRoot.found) {
  10478. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10479. if (f >= 0.0 && f <= 1.0) {
  10480. t = lowestRoot.root;
  10481. found = true;
  10482. this._edge.scaleInPlace(f);
  10483. p3.addToRef(this._edge, this._collisionPoint);
  10484. }
  10485. }
  10486. }
  10487. if (found) {
  10488. var distToCollision = t * this.velocity.length();
  10489. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10490. if (!this.intersectionPoint) {
  10491. this.intersectionPoint = this._collisionPoint.clone();
  10492. }
  10493. else {
  10494. this.intersectionPoint.copyFrom(this._collisionPoint);
  10495. }
  10496. this.nearestDistance = distToCollision;
  10497. this.collisionFound = true;
  10498. }
  10499. }
  10500. };
  10501. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10502. for (var i = indexStart; i < indexEnd; i += 3) {
  10503. var p1 = pts[indices[i] - decal];
  10504. var p2 = pts[indices[i + 1] - decal];
  10505. var p3 = pts[indices[i + 2] - decal];
  10506. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10507. }
  10508. };
  10509. Collider.prototype._getResponse = function (pos, vel) {
  10510. pos.addToRef(vel, this._destinationPoint);
  10511. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10512. this.basePoint.addToRef(vel, pos);
  10513. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10514. this._slidePlaneNormal.normalize();
  10515. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10516. pos.addInPlace(this._displacementVector);
  10517. this.intersectionPoint.addInPlace(this._displacementVector);
  10518. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10519. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10520. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10521. };
  10522. return Collider;
  10523. }());
  10524. BABYLON.Collider = Collider;
  10525. })(BABYLON || (BABYLON = {}));
  10526. var BABYLON;
  10527. (function (BABYLON) {
  10528. //WebWorker code will be inserted to this variable.
  10529. BABYLON.CollisionWorker = "";
  10530. (function (WorkerTaskType) {
  10531. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10532. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10533. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10534. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10535. var WorkerTaskType = BABYLON.WorkerTaskType;
  10536. (function (WorkerReplyType) {
  10537. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10538. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10539. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10540. var WorkerReplyType = BABYLON.WorkerReplyType;
  10541. var CollisionCoordinatorWorker = (function () {
  10542. function CollisionCoordinatorWorker() {
  10543. var _this = this;
  10544. this._scaledPosition = BABYLON.Vector3.Zero();
  10545. this._scaledVelocity = BABYLON.Vector3.Zero();
  10546. this.onMeshUpdated = function (mesh) {
  10547. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10548. };
  10549. this.onGeometryUpdated = function (geometry) {
  10550. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10551. };
  10552. this._afterRender = function () {
  10553. if (!_this._init)
  10554. return;
  10555. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10556. return;
  10557. }
  10558. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10559. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10560. if (_this._runningUpdated > 4) {
  10561. return;
  10562. }
  10563. ++_this._runningUpdated;
  10564. var payload = {
  10565. updatedMeshes: _this._addUpdateMeshesList,
  10566. updatedGeometries: _this._addUpdateGeometriesList,
  10567. removedGeometries: _this._toRemoveGeometryArray,
  10568. removedMeshes: _this._toRemoveMeshesArray
  10569. };
  10570. var message = {
  10571. payload: payload,
  10572. taskType: WorkerTaskType.UPDATE
  10573. };
  10574. var serializable = [];
  10575. for (var id in payload.updatedGeometries) {
  10576. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10577. //prepare transferables
  10578. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10579. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10580. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10581. }
  10582. }
  10583. _this._worker.postMessage(message, serializable);
  10584. _this._addUpdateMeshesList = {};
  10585. _this._addUpdateGeometriesList = {};
  10586. _this._toRemoveGeometryArray = [];
  10587. _this._toRemoveMeshesArray = [];
  10588. };
  10589. this._onMessageFromWorker = function (e) {
  10590. var returnData = e.data;
  10591. if (returnData.error != WorkerReplyType.SUCCESS) {
  10592. //TODO what errors can be returned from the worker?
  10593. BABYLON.Tools.Warn("error returned from worker!");
  10594. return;
  10595. }
  10596. switch (returnData.taskType) {
  10597. case WorkerTaskType.INIT:
  10598. _this._init = true;
  10599. //Update the worked with ALL of the scene's current state
  10600. _this._scene.meshes.forEach(function (mesh) {
  10601. _this.onMeshAdded(mesh);
  10602. });
  10603. _this._scene.getGeometries().forEach(function (geometry) {
  10604. _this.onGeometryAdded(geometry);
  10605. });
  10606. break;
  10607. case WorkerTaskType.UPDATE:
  10608. _this._runningUpdated--;
  10609. break;
  10610. case WorkerTaskType.COLLIDE:
  10611. _this._runningCollisionTask = false;
  10612. var returnPayload = returnData.payload;
  10613. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10614. return;
  10615. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10616. //cleanup
  10617. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10618. break;
  10619. }
  10620. };
  10621. this._collisionsCallbackArray = [];
  10622. this._init = false;
  10623. this._runningUpdated = 0;
  10624. this._runningCollisionTask = false;
  10625. this._addUpdateMeshesList = {};
  10626. this._addUpdateGeometriesList = {};
  10627. this._toRemoveGeometryArray = [];
  10628. this._toRemoveMeshesArray = [];
  10629. }
  10630. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10631. if (!this._init)
  10632. return;
  10633. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10634. return;
  10635. position.divideToRef(collider.radius, this._scaledPosition);
  10636. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10637. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10638. var payload = {
  10639. collider: {
  10640. position: this._scaledPosition.asArray(),
  10641. velocity: this._scaledVelocity.asArray(),
  10642. radius: collider.radius.asArray()
  10643. },
  10644. collisionId: collisionIndex,
  10645. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10646. maximumRetry: maximumRetry
  10647. };
  10648. var message = {
  10649. payload: payload,
  10650. taskType: WorkerTaskType.COLLIDE
  10651. };
  10652. this._worker.postMessage(message);
  10653. };
  10654. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10655. this._scene = scene;
  10656. this._scene.registerAfterRender(this._afterRender);
  10657. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10658. this._worker = new Worker(workerUrl);
  10659. this._worker.onmessage = this._onMessageFromWorker;
  10660. var message = {
  10661. payload: {},
  10662. taskType: WorkerTaskType.INIT
  10663. };
  10664. this._worker.postMessage(message);
  10665. };
  10666. CollisionCoordinatorWorker.prototype.destroy = function () {
  10667. this._scene.unregisterAfterRender(this._afterRender);
  10668. this._worker.terminate();
  10669. };
  10670. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10671. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10672. this.onMeshUpdated(mesh);
  10673. };
  10674. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10675. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10676. };
  10677. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10678. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10679. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10680. this.onGeometryUpdated(geometry);
  10681. };
  10682. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10683. this._toRemoveGeometryArray.push(geometry.id);
  10684. };
  10685. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10686. var submeshes = [];
  10687. if (mesh.subMeshes) {
  10688. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10689. return {
  10690. position: idx,
  10691. verticesStart: sm.verticesStart,
  10692. verticesCount: sm.verticesCount,
  10693. indexStart: sm.indexStart,
  10694. indexCount: sm.indexCount,
  10695. hasMaterial: !!sm.getMaterial(),
  10696. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10697. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10698. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10699. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10700. };
  10701. });
  10702. }
  10703. var geometryId = null;
  10704. if (mesh instanceof BABYLON.Mesh) {
  10705. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10706. }
  10707. else if (mesh instanceof BABYLON.InstancedMesh) {
  10708. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10709. }
  10710. return {
  10711. uniqueId: mesh.uniqueId,
  10712. id: mesh.id,
  10713. name: mesh.name,
  10714. geometryId: geometryId,
  10715. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10716. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10717. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10718. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10719. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10720. subMeshes: submeshes,
  10721. checkCollisions: mesh.checkCollisions
  10722. };
  10723. };
  10724. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10725. return {
  10726. id: geometry.id,
  10727. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10728. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10729. indices: new Int32Array(geometry.getIndices() || []),
  10730. };
  10731. };
  10732. return CollisionCoordinatorWorker;
  10733. }());
  10734. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10735. var CollisionCoordinatorLegacy = (function () {
  10736. function CollisionCoordinatorLegacy() {
  10737. this._scaledPosition = BABYLON.Vector3.Zero();
  10738. this._scaledVelocity = BABYLON.Vector3.Zero();
  10739. this._finalPosition = BABYLON.Vector3.Zero();
  10740. }
  10741. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10742. position.divideToRef(collider.radius, this._scaledPosition);
  10743. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10744. collider.collidedMesh = null;
  10745. collider.retry = 0;
  10746. collider.initialVelocity = this._scaledVelocity;
  10747. collider.initialPosition = this._scaledPosition;
  10748. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10749. this._finalPosition.multiplyInPlace(collider.radius);
  10750. //run the callback
  10751. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10752. };
  10753. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10754. this._scene = scene;
  10755. };
  10756. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10757. //Legacy need no destruction method.
  10758. };
  10759. //No update in legacy mode
  10760. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10761. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10762. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10763. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10764. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10765. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10766. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10767. if (excludedMesh === void 0) { excludedMesh = null; }
  10768. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10769. if (collider.retry >= maximumRetry) {
  10770. finalPosition.copyFrom(position);
  10771. return;
  10772. }
  10773. collider._initialize(position, velocity, closeDistance);
  10774. // Check all meshes
  10775. for (var index = 0; index < this._scene.meshes.length; index++) {
  10776. var mesh = this._scene.meshes[index];
  10777. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10778. mesh._checkCollision(collider);
  10779. }
  10780. }
  10781. if (!collider.collisionFound) {
  10782. position.addToRef(velocity, finalPosition);
  10783. return;
  10784. }
  10785. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10786. collider._getResponse(position, velocity);
  10787. }
  10788. if (velocity.length() <= closeDistance) {
  10789. finalPosition.copyFrom(position);
  10790. return;
  10791. }
  10792. collider.retry++;
  10793. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10794. };
  10795. return CollisionCoordinatorLegacy;
  10796. }());
  10797. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10798. })(BABYLON || (BABYLON = {}));
  10799. var BABYLON;
  10800. (function (BABYLON) {
  10801. var Camera = (function (_super) {
  10802. __extends(Camera, _super);
  10803. function Camera(name, position, scene) {
  10804. _super.call(this, name, scene);
  10805. this.upVector = BABYLON.Vector3.Up();
  10806. this.orthoLeft = null;
  10807. this.orthoRight = null;
  10808. this.orthoBottom = null;
  10809. this.orthoTop = null;
  10810. this.fov = 0.8;
  10811. this.minZ = 1.0;
  10812. this.maxZ = 10000.0;
  10813. this.inertia = 0.9;
  10814. this.mode = Camera.PERSPECTIVE_CAMERA;
  10815. this.isIntermediate = false;
  10816. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10817. this.layerMask = 0x0FFFFFFF;
  10818. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10819. // Camera rig members
  10820. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10821. this._rigCameras = new Array();
  10822. // Cache
  10823. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10824. this._projectionMatrix = new BABYLON.Matrix();
  10825. this._postProcesses = new Array();
  10826. this._postProcessesTakenIndices = [];
  10827. this._activeMeshes = new BABYLON.SmartArray(256);
  10828. this._globalPosition = BABYLON.Vector3.Zero();
  10829. scene.addCamera(this);
  10830. if (!scene.activeCamera) {
  10831. scene.activeCamera = this;
  10832. }
  10833. this.position = position;
  10834. }
  10835. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10836. get: function () {
  10837. return Camera._PERSPECTIVE_CAMERA;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10843. get: function () {
  10844. return Camera._ORTHOGRAPHIC_CAMERA;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10850. get: function () {
  10851. return Camera._FOVMODE_VERTICAL_FIXED;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10857. get: function () {
  10858. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10864. get: function () {
  10865. return Camera._RIG_MODE_NONE;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10871. get: function () {
  10872. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10878. get: function () {
  10879. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10885. get: function () {
  10886. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10892. get: function () {
  10893. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10899. get: function () {
  10900. return Camera._RIG_MODE_VR;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. /**
  10906. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10907. */
  10908. Camera.prototype.toString = function (fullDetails) {
  10909. var ret = "Name: " + this.name;
  10910. ret += ", type: " + this.getTypeName();
  10911. if (this.animations) {
  10912. for (var i = 0; i < this.animations.length; i++) {
  10913. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10914. }
  10915. }
  10916. if (fullDetails) {
  10917. }
  10918. return ret;
  10919. };
  10920. Object.defineProperty(Camera.prototype, "globalPosition", {
  10921. get: function () {
  10922. return this._globalPosition;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Camera.prototype.getActiveMeshes = function () {
  10928. return this._activeMeshes;
  10929. };
  10930. Camera.prototype.isActiveMesh = function (mesh) {
  10931. return (this._activeMeshes.indexOf(mesh) !== -1);
  10932. };
  10933. //Cache
  10934. Camera.prototype._initCache = function () {
  10935. _super.prototype._initCache.call(this);
  10936. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10937. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10938. this._cache.mode = undefined;
  10939. this._cache.minZ = undefined;
  10940. this._cache.maxZ = undefined;
  10941. this._cache.fov = undefined;
  10942. this._cache.aspectRatio = undefined;
  10943. this._cache.orthoLeft = undefined;
  10944. this._cache.orthoRight = undefined;
  10945. this._cache.orthoBottom = undefined;
  10946. this._cache.orthoTop = undefined;
  10947. this._cache.renderWidth = undefined;
  10948. this._cache.renderHeight = undefined;
  10949. };
  10950. Camera.prototype._updateCache = function (ignoreParentClass) {
  10951. if (!ignoreParentClass) {
  10952. _super.prototype._updateCache.call(this);
  10953. }
  10954. var engine = this.getEngine();
  10955. this._cache.position.copyFrom(this.position);
  10956. this._cache.upVector.copyFrom(this.upVector);
  10957. this._cache.mode = this.mode;
  10958. this._cache.minZ = this.minZ;
  10959. this._cache.maxZ = this.maxZ;
  10960. this._cache.fov = this.fov;
  10961. this._cache.aspectRatio = engine.getAspectRatio(this);
  10962. this._cache.orthoLeft = this.orthoLeft;
  10963. this._cache.orthoRight = this.orthoRight;
  10964. this._cache.orthoBottom = this.orthoBottom;
  10965. this._cache.orthoTop = this.orthoTop;
  10966. this._cache.renderWidth = engine.getRenderWidth();
  10967. this._cache.renderHeight = engine.getRenderHeight();
  10968. };
  10969. Camera.prototype._updateFromScene = function () {
  10970. this.updateCache();
  10971. this._update();
  10972. };
  10973. // Synchronized
  10974. Camera.prototype._isSynchronized = function () {
  10975. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10976. };
  10977. Camera.prototype._isSynchronizedViewMatrix = function () {
  10978. if (!_super.prototype._isSynchronized.call(this))
  10979. return false;
  10980. return this._cache.position.equals(this.position)
  10981. && this._cache.upVector.equals(this.upVector)
  10982. && this.isSynchronizedWithParent();
  10983. };
  10984. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10985. var check = this._cache.mode === this.mode
  10986. && this._cache.minZ === this.minZ
  10987. && this._cache.maxZ === this.maxZ;
  10988. if (!check) {
  10989. return false;
  10990. }
  10991. var engine = this.getEngine();
  10992. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10993. check = this._cache.fov === this.fov
  10994. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10995. }
  10996. else {
  10997. check = this._cache.orthoLeft === this.orthoLeft
  10998. && this._cache.orthoRight === this.orthoRight
  10999. && this._cache.orthoBottom === this.orthoBottom
  11000. && this._cache.orthoTop === this.orthoTop
  11001. && this._cache.renderWidth === engine.getRenderWidth()
  11002. && this._cache.renderHeight === engine.getRenderHeight();
  11003. }
  11004. return check;
  11005. };
  11006. // Controls
  11007. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11008. };
  11009. Camera.prototype.detachControl = function (element) {
  11010. };
  11011. Camera.prototype._update = function () {
  11012. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11013. this._updateRigCameras();
  11014. }
  11015. this._checkInputs();
  11016. };
  11017. Camera.prototype._checkInputs = function () {
  11018. };
  11019. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11020. if (insertAt === void 0) { insertAt = null; }
  11021. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11022. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11023. return 0;
  11024. }
  11025. if (insertAt == null || insertAt < 0) {
  11026. this._postProcesses.push(postProcess);
  11027. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11028. return this._postProcesses.length - 1;
  11029. }
  11030. var add = 0;
  11031. var i;
  11032. var start;
  11033. if (this._postProcesses[insertAt]) {
  11034. start = this._postProcesses.length - 1;
  11035. for (i = start; i >= insertAt + 1; --i) {
  11036. this._postProcesses[i + 1] = this._postProcesses[i];
  11037. }
  11038. add = 1;
  11039. }
  11040. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11041. if (this._postProcessesTakenIndices[i] < insertAt) {
  11042. continue;
  11043. }
  11044. start = this._postProcessesTakenIndices.length - 1;
  11045. for (var j = start; j >= i; --j) {
  11046. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11047. }
  11048. this._postProcessesTakenIndices[i] = insertAt;
  11049. break;
  11050. }
  11051. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11052. this._postProcessesTakenIndices.push(insertAt);
  11053. }
  11054. var result = insertAt + add;
  11055. this._postProcesses[result] = postProcess;
  11056. return result;
  11057. };
  11058. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11059. if (atIndices === void 0) { atIndices = null; }
  11060. var result = [];
  11061. var i;
  11062. var index;
  11063. if (!atIndices) {
  11064. var length = this._postProcesses.length;
  11065. for (i = 0; i < length; i++) {
  11066. if (this._postProcesses[i] !== postProcess) {
  11067. continue;
  11068. }
  11069. delete this._postProcesses[i];
  11070. index = this._postProcessesTakenIndices.indexOf(i);
  11071. this._postProcessesTakenIndices.splice(index, 1);
  11072. }
  11073. }
  11074. else {
  11075. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11076. for (i = 0; i < atIndices.length; i++) {
  11077. var foundPostProcess = this._postProcesses[atIndices[i]];
  11078. if (foundPostProcess !== postProcess) {
  11079. result.push(i);
  11080. continue;
  11081. }
  11082. delete this._postProcesses[atIndices[i]];
  11083. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11084. this._postProcessesTakenIndices.splice(index, 1);
  11085. }
  11086. }
  11087. return result;
  11088. };
  11089. Camera.prototype.getWorldMatrix = function () {
  11090. if (!this._worldMatrix) {
  11091. this._worldMatrix = BABYLON.Matrix.Identity();
  11092. }
  11093. var viewMatrix = this.getViewMatrix();
  11094. viewMatrix.invertToRef(this._worldMatrix);
  11095. return this._worldMatrix;
  11096. };
  11097. Camera.prototype._getViewMatrix = function () {
  11098. return BABYLON.Matrix.Identity();
  11099. };
  11100. Camera.prototype.getViewMatrix = function (force) {
  11101. this._computedViewMatrix = this._computeViewMatrix(force);
  11102. if (!force && this._isSynchronizedViewMatrix()) {
  11103. return this._computedViewMatrix;
  11104. }
  11105. if (!this.parent || !this.parent.getWorldMatrix) {
  11106. this._globalPosition.copyFrom(this.position);
  11107. }
  11108. else {
  11109. if (!this._worldMatrix) {
  11110. this._worldMatrix = BABYLON.Matrix.Identity();
  11111. }
  11112. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11113. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11114. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11115. this._computedViewMatrix.invert();
  11116. this._markSyncedWithParent();
  11117. }
  11118. this._currentRenderId = this.getScene().getRenderId();
  11119. return this._computedViewMatrix;
  11120. };
  11121. Camera.prototype._computeViewMatrix = function (force) {
  11122. if (!force && this._isSynchronizedViewMatrix()) {
  11123. return this._computedViewMatrix;
  11124. }
  11125. this._computedViewMatrix = this._getViewMatrix();
  11126. this._currentRenderId = this.getScene().getRenderId();
  11127. return this._computedViewMatrix;
  11128. };
  11129. Camera.prototype.getProjectionMatrix = function (force) {
  11130. if (!force && this._isSynchronizedProjectionMatrix()) {
  11131. return this._projectionMatrix;
  11132. }
  11133. var engine = this.getEngine();
  11134. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11135. if (this.minZ <= 0) {
  11136. this.minZ = 0.1;
  11137. }
  11138. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11139. return this._projectionMatrix;
  11140. }
  11141. var halfWidth = engine.getRenderWidth() / 2.0;
  11142. var halfHeight = engine.getRenderHeight() / 2.0;
  11143. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11144. return this._projectionMatrix;
  11145. };
  11146. Camera.prototype.dispose = function () {
  11147. // Animations
  11148. this.getScene().stopAnimation(this);
  11149. // Remove from scene
  11150. this.getScene().removeCamera(this);
  11151. while (this._rigCameras.length > 0) {
  11152. this._rigCameras.pop().dispose();
  11153. }
  11154. // Postprocesses
  11155. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11156. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11157. }
  11158. _super.prototype.dispose.call(this);
  11159. };
  11160. // ---- Camera rigs section ----
  11161. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11162. while (this._rigCameras.length > 0) {
  11163. this._rigCameras.pop().dispose();
  11164. }
  11165. this.cameraRigMode = mode;
  11166. this._cameraRigParams = {};
  11167. switch (this.cameraRigMode) {
  11168. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11169. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11170. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11171. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11172. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11173. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11174. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11175. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11176. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11177. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11178. break;
  11179. }
  11180. var postProcesses = new Array();
  11181. switch (this.cameraRigMode) {
  11182. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11183. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11184. this._rigCameras[0].isIntermediate = true;
  11185. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11186. postProcesses[1].onApply = function (effect) {
  11187. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11188. };
  11189. break;
  11190. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11191. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11192. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11193. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11194. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11195. var secondCamIndex = 1 - firstCamIndex;
  11196. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11197. this._rigCameras[firstCamIndex].isIntermediate = true;
  11198. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11199. break;
  11200. case Camera.RIG_MODE_VR:
  11201. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11202. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11203. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11204. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11205. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11206. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11207. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11208. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11209. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11210. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11211. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11212. if (metrics.compensateDistortion) {
  11213. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11214. }
  11215. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11216. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11217. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11218. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11219. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11220. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11221. if (metrics.compensateDistortion) {
  11222. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11223. }
  11224. break;
  11225. }
  11226. this._update();
  11227. };
  11228. Camera.prototype._getVRProjectionMatrix = function () {
  11229. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11230. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11231. return this._projectionMatrix;
  11232. };
  11233. Camera.prototype.setCameraRigParameter = function (name, value) {
  11234. this._cameraRigParams[name] = value;
  11235. //provisionnally:
  11236. if (name === "interaxialDistance") {
  11237. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11238. }
  11239. };
  11240. /**
  11241. * May needs to be overridden by children so sub has required properties to be copied
  11242. */
  11243. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11244. return null;
  11245. };
  11246. /**
  11247. * May needs to be overridden by children
  11248. */
  11249. Camera.prototype._updateRigCameras = function () {
  11250. for (var i = 0; i < this._rigCameras.length; i++) {
  11251. this._rigCameras[i].minZ = this.minZ;
  11252. this._rigCameras[i].maxZ = this.maxZ;
  11253. this._rigCameras[i].fov = this.fov;
  11254. }
  11255. // only update viewport when ANAGLYPH
  11256. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11257. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11258. }
  11259. };
  11260. Camera.prototype.serialize = function () {
  11261. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11262. // Type
  11263. serializationObject.type = this.getTypeName();
  11264. // Parent
  11265. if (this.parent) {
  11266. serializationObject.parentId = this.parent.id;
  11267. }
  11268. if (this.inputs) {
  11269. this.inputs.serialize(serializationObject);
  11270. }
  11271. // Animations
  11272. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11273. serializationObject.ranges = this.serializeAnimationRanges();
  11274. return serializationObject;
  11275. };
  11276. Camera.prototype.getTypeName = function () {
  11277. return "Camera";
  11278. };
  11279. Camera.prototype.clone = function (name) {
  11280. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11281. };
  11282. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11283. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11284. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11285. switch (type) {
  11286. case "ArcRotateCamera":
  11287. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11288. case "DeviceOrientationCamera":
  11289. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11290. case "FollowCamera":
  11291. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11292. case "ArcFollowCamera":
  11293. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11294. case "GamepadCamera":
  11295. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11296. case "TouchCamera":
  11297. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11298. case "VirtualJoysticksCamera":
  11299. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11300. case "WebVRFreeCamera":
  11301. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11302. case "VRDeviceOrientationFreeCamera":
  11303. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11304. case "AnaglyphArcRotateCamera":
  11305. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11306. case "AnaglyphFreeCamera":
  11307. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11308. case "AnaglyphGamepadCamera":
  11309. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11310. case "AnaglyphUniversalCamera":
  11311. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11312. case "StereoscopicArcRotateCamera":
  11313. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11314. case "StereoscopicFreeCamera":
  11315. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11316. case "StereoscopicGamepadCamera":
  11317. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11318. case "StereoscopicUniversalCamera":
  11319. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11320. case "FreeCamera":
  11321. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11322. default:
  11323. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11324. }
  11325. };
  11326. Camera.Parse = function (parsedCamera, scene) {
  11327. var type = parsedCamera.type;
  11328. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11329. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11330. // Parent
  11331. if (parsedCamera.parentId) {
  11332. camera._waitingParentId = parsedCamera.parentId;
  11333. }
  11334. //If camera has an input manager, let it parse inputs settings
  11335. if (camera.inputs) {
  11336. camera.inputs.parse(parsedCamera);
  11337. }
  11338. // Target
  11339. if (parsedCamera.target) {
  11340. if (camera.setTarget) {
  11341. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11342. }
  11343. }
  11344. // Apply 3d rig, when found
  11345. if (parsedCamera.cameraRigMode) {
  11346. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11347. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11348. }
  11349. // Animations
  11350. if (parsedCamera.animations) {
  11351. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11352. var parsedAnimation = parsedCamera.animations[animationIndex];
  11353. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11354. }
  11355. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11356. }
  11357. if (parsedCamera.autoAnimate) {
  11358. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11359. }
  11360. return camera;
  11361. };
  11362. // Statics
  11363. Camera._PERSPECTIVE_CAMERA = 0;
  11364. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11365. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11366. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11367. Camera._RIG_MODE_NONE = 0;
  11368. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11369. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11370. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11371. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11372. Camera._RIG_MODE_VR = 20;
  11373. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11374. __decorate([
  11375. BABYLON.serializeAsVector3()
  11376. ], Camera.prototype, "position", void 0);
  11377. __decorate([
  11378. BABYLON.serializeAsVector3()
  11379. ], Camera.prototype, "upVector", void 0);
  11380. __decorate([
  11381. BABYLON.serialize()
  11382. ], Camera.prototype, "orthoLeft", void 0);
  11383. __decorate([
  11384. BABYLON.serialize()
  11385. ], Camera.prototype, "orthoRight", void 0);
  11386. __decorate([
  11387. BABYLON.serialize()
  11388. ], Camera.prototype, "orthoBottom", void 0);
  11389. __decorate([
  11390. BABYLON.serialize()
  11391. ], Camera.prototype, "orthoTop", void 0);
  11392. __decorate([
  11393. BABYLON.serialize()
  11394. ], Camera.prototype, "fov", void 0);
  11395. __decorate([
  11396. BABYLON.serialize()
  11397. ], Camera.prototype, "minZ", void 0);
  11398. __decorate([
  11399. BABYLON.serialize()
  11400. ], Camera.prototype, "maxZ", void 0);
  11401. __decorate([
  11402. BABYLON.serialize()
  11403. ], Camera.prototype, "inertia", void 0);
  11404. __decorate([
  11405. BABYLON.serialize()
  11406. ], Camera.prototype, "mode", void 0);
  11407. __decorate([
  11408. BABYLON.serialize()
  11409. ], Camera.prototype, "layerMask", void 0);
  11410. __decorate([
  11411. BABYLON.serialize()
  11412. ], Camera.prototype, "fovMode", void 0);
  11413. __decorate([
  11414. BABYLON.serialize()
  11415. ], Camera.prototype, "cameraRigMode", void 0);
  11416. __decorate([
  11417. BABYLON.serialize()
  11418. ], Camera.prototype, "interaxialDistance", void 0);
  11419. __decorate([
  11420. BABYLON.serialize()
  11421. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11422. return Camera;
  11423. }(BABYLON.Node));
  11424. BABYLON.Camera = Camera;
  11425. })(BABYLON || (BABYLON = {}));
  11426. var BABYLON;
  11427. (function (BABYLON) {
  11428. BABYLON.CameraInputTypes = {};
  11429. var CameraInputsManager = (function () {
  11430. function CameraInputsManager(camera) {
  11431. this.attached = {};
  11432. this.camera = camera;
  11433. this.checkInputs = function () { };
  11434. }
  11435. CameraInputsManager.prototype.add = function (input) {
  11436. var type = input.getSimpleName();
  11437. if (this.attached[type]) {
  11438. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11439. return;
  11440. }
  11441. this.attached[type] = input;
  11442. input.camera = this.camera;
  11443. //for checkInputs, we are dynamically creating a function
  11444. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11445. if (input.checkInputs) {
  11446. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11447. }
  11448. if (this.attachedElement) {
  11449. input.attachControl(this.attachedElement);
  11450. }
  11451. };
  11452. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11453. for (var cam in this.attached) {
  11454. var input = this.attached[cam];
  11455. if (input === inputToRemove) {
  11456. input.detachControl(this.attachedElement);
  11457. delete this.attached[cam];
  11458. this.rebuildInputCheck();
  11459. }
  11460. }
  11461. };
  11462. CameraInputsManager.prototype.removeByType = function (inputType) {
  11463. for (var cam in this.attached) {
  11464. var input = this.attached[cam];
  11465. if (input.getTypeName() === inputType) {
  11466. input.detachControl(this.attachedElement);
  11467. delete this.attached[cam];
  11468. this.rebuildInputCheck();
  11469. }
  11470. }
  11471. };
  11472. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11473. var current = this.checkInputs;
  11474. return function () {
  11475. current();
  11476. fn();
  11477. };
  11478. };
  11479. CameraInputsManager.prototype.attachInput = function (input) {
  11480. input.attachControl(this.attachedElement, this.noPreventDefault);
  11481. };
  11482. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11483. if (this.attachedElement) {
  11484. return;
  11485. }
  11486. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11487. this.attachedElement = element;
  11488. this.noPreventDefault = noPreventDefault;
  11489. for (var cam in this.attached) {
  11490. var input = this.attached[cam];
  11491. this.attached[cam].attachControl(element, noPreventDefault);
  11492. }
  11493. };
  11494. CameraInputsManager.prototype.detachElement = function (element) {
  11495. if (this.attachedElement !== element) {
  11496. return;
  11497. }
  11498. for (var cam in this.attached) {
  11499. var input = this.attached[cam];
  11500. this.attached[cam].detachControl(element);
  11501. }
  11502. this.attachedElement = null;
  11503. };
  11504. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11505. this.checkInputs = function () { };
  11506. for (var cam in this.attached) {
  11507. var input = this.attached[cam];
  11508. if (input.checkInputs) {
  11509. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11510. }
  11511. }
  11512. };
  11513. CameraInputsManager.prototype.clear = function () {
  11514. if (this.attachedElement) {
  11515. this.detachElement(this.attachedElement);
  11516. }
  11517. this.attached = {};
  11518. this.attachedElement = null;
  11519. this.checkInputs = function () { };
  11520. };
  11521. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11522. var inputs = {};
  11523. for (var cam in this.attached) {
  11524. var input = this.attached[cam];
  11525. var res = BABYLON.SerializationHelper.Serialize(input);
  11526. inputs[input.getTypeName()] = res;
  11527. }
  11528. serializedCamera.inputsmgr = inputs;
  11529. };
  11530. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11531. var parsedInputs = parsedCamera.inputsmgr;
  11532. if (parsedInputs) {
  11533. this.clear();
  11534. for (var n in parsedInputs) {
  11535. var construct = BABYLON.CameraInputTypes[n];
  11536. if (construct) {
  11537. var parsedinput = parsedInputs[n];
  11538. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11539. this.add(input);
  11540. }
  11541. }
  11542. }
  11543. else {
  11544. //2016-03-08 this part is for managing backward compatibility
  11545. for (var n in this.attached) {
  11546. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11547. if (construct) {
  11548. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11549. this.remove(this.attached[n]);
  11550. this.add(input);
  11551. }
  11552. }
  11553. }
  11554. };
  11555. return CameraInputsManager;
  11556. }());
  11557. BABYLON.CameraInputsManager = CameraInputsManager;
  11558. })(BABYLON || (BABYLON = {}));
  11559. var BABYLON;
  11560. (function (BABYLON) {
  11561. var FreeCameraMouseInput = (function () {
  11562. function FreeCameraMouseInput() {
  11563. this.angularSensibility = 2000.0;
  11564. }
  11565. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11566. var _this = this;
  11567. if (!this._pointerInput) {
  11568. var camera = this.camera;
  11569. var engine = this.camera.getEngine();
  11570. this._pointerInput = function (p, s) {
  11571. var evt = p.event;
  11572. if (p.type === 1 /* PointerDown */) {
  11573. // evt.srcElement.setPointerCapture(evt.pointerId);
  11574. _this.previousPosition = {
  11575. x: evt.clientX,
  11576. y: evt.clientY
  11577. };
  11578. if (!noPreventDefault) {
  11579. evt.preventDefault();
  11580. }
  11581. }
  11582. else if (p.type === 2 /* PointerUp */) {
  11583. // evt.srcElement.releasePointerCapture(evt.pointerId);
  11584. _this.previousPosition = null;
  11585. if (!noPreventDefault) {
  11586. evt.preventDefault();
  11587. }
  11588. }
  11589. else if (p.type === 3 /* PointerMove */) {
  11590. if (!_this.previousPosition && !engine.isPointerLock) {
  11591. return;
  11592. }
  11593. var offsetX;
  11594. var offsetY;
  11595. if (!engine.isPointerLock) {
  11596. offsetX = evt.clientX - _this.previousPosition.x;
  11597. offsetY = evt.clientY - _this.previousPosition.y;
  11598. }
  11599. else {
  11600. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11601. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11602. }
  11603. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11604. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11605. _this.previousPosition = {
  11606. x: evt.clientX,
  11607. y: evt.clientY
  11608. };
  11609. if (!noPreventDefault) {
  11610. evt.preventDefault();
  11611. }
  11612. }
  11613. };
  11614. }
  11615. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput);
  11616. };
  11617. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11618. if (this._observer && element) {
  11619. this.camera.getScene().onPointerObservable.remove(this._observer);
  11620. this._observer = null;
  11621. this.previousPosition = null;
  11622. }
  11623. };
  11624. FreeCameraMouseInput.prototype.getTypeName = function () {
  11625. return "FreeCameraMouseInput";
  11626. };
  11627. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11628. return "mouse";
  11629. };
  11630. __decorate([
  11631. BABYLON.serialize()
  11632. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11633. return FreeCameraMouseInput;
  11634. }());
  11635. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11636. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11637. })(BABYLON || (BABYLON = {}));
  11638. var BABYLON;
  11639. (function (BABYLON) {
  11640. var FreeCameraKeyboardMoveInput = (function () {
  11641. function FreeCameraKeyboardMoveInput() {
  11642. this._keys = [];
  11643. this.keysUp = [38];
  11644. this.keysDown = [40];
  11645. this.keysLeft = [37];
  11646. this.keysRight = [39];
  11647. }
  11648. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11649. var _this = this;
  11650. if (!this._onKeyDown) {
  11651. this._onKeyDown = function (evt) {
  11652. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11653. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11654. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11655. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11656. var index = _this._keys.indexOf(evt.keyCode);
  11657. if (index === -1) {
  11658. _this._keys.push(evt.keyCode);
  11659. }
  11660. if (!noPreventDefault) {
  11661. evt.preventDefault();
  11662. }
  11663. }
  11664. };
  11665. this._onKeyUp = function (evt) {
  11666. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11667. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11668. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11669. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11670. var index = _this._keys.indexOf(evt.keyCode);
  11671. if (index >= 0) {
  11672. _this._keys.splice(index, 1);
  11673. }
  11674. if (!noPreventDefault) {
  11675. evt.preventDefault();
  11676. }
  11677. }
  11678. };
  11679. BABYLON.Tools.RegisterTopRootEvents([
  11680. { name: "keydown", handler: this._onKeyDown },
  11681. { name: "keyup", handler: this._onKeyUp },
  11682. { name: "blur", handler: this._onLostFocus }
  11683. ]);
  11684. }
  11685. };
  11686. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11687. if (this._onKeyDown) {
  11688. BABYLON.Tools.UnregisterTopRootEvents([
  11689. { name: "keydown", handler: this._onKeyDown },
  11690. { name: "keyup", handler: this._onKeyUp },
  11691. { name: "blur", handler: this._onLostFocus }
  11692. ]);
  11693. this._keys = [];
  11694. this._onKeyDown = null;
  11695. this._onKeyUp = null;
  11696. }
  11697. };
  11698. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11699. if (this._onKeyDown) {
  11700. var camera = this.camera;
  11701. // Keyboard
  11702. for (var index = 0; index < this._keys.length; index++) {
  11703. var keyCode = this._keys[index];
  11704. var speed = camera._computeLocalCameraSpeed();
  11705. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11706. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11707. }
  11708. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11709. camera._localDirection.copyFromFloats(0, 0, speed);
  11710. }
  11711. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11712. camera._localDirection.copyFromFloats(speed, 0, 0);
  11713. }
  11714. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11715. camera._localDirection.copyFromFloats(0, 0, -speed);
  11716. }
  11717. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11718. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11719. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11720. }
  11721. }
  11722. };
  11723. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11724. return "FreeCameraKeyboardMoveInput";
  11725. };
  11726. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11727. this._keys = [];
  11728. };
  11729. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11730. return "keyboard";
  11731. };
  11732. __decorate([
  11733. BABYLON.serialize()
  11734. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11735. __decorate([
  11736. BABYLON.serialize()
  11737. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11738. __decorate([
  11739. BABYLON.serialize()
  11740. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11741. __decorate([
  11742. BABYLON.serialize()
  11743. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11744. return FreeCameraKeyboardMoveInput;
  11745. }());
  11746. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11747. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11748. })(BABYLON || (BABYLON = {}));
  11749. var BABYLON;
  11750. (function (BABYLON) {
  11751. var FreeCameraTouchInput = (function () {
  11752. function FreeCameraTouchInput() {
  11753. this._offsetX = null;
  11754. this._offsetY = null;
  11755. this._pointerCount = 0;
  11756. this._pointerPressed = [];
  11757. this.touchAngularSensibility = 200000.0;
  11758. this.touchMoveSensibility = 250.0;
  11759. }
  11760. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11761. var _this = this;
  11762. var previousPosition;
  11763. if (this._pointerInput === undefined) {
  11764. this._onLostFocus = function (evt) {
  11765. _this._offsetX = null;
  11766. _this._offsetY = null;
  11767. };
  11768. this._pointerInput = function (p, s) {
  11769. var evt = p.event;
  11770. if (p.type === 1 /* PointerDown */) {
  11771. if (evt.pointerType === "mouse") {
  11772. return;
  11773. }
  11774. if (!noPreventDefault) {
  11775. evt.preventDefault();
  11776. }
  11777. // evt.srcElement.setPointerCapture(evt.pointerId);
  11778. _this._pointerPressed.push(evt.pointerId);
  11779. if (_this._pointerPressed.length !== 1) {
  11780. return;
  11781. }
  11782. previousPosition = {
  11783. x: evt.clientX,
  11784. y: evt.clientY
  11785. };
  11786. }
  11787. else if (p.type === 2 /* PointerUp */) {
  11788. if (evt.pointerType === "mouse") {
  11789. return;
  11790. }
  11791. if (!noPreventDefault) {
  11792. evt.preventDefault();
  11793. }
  11794. // evt.srcElement.releasePointerCapture(evt.pointerId);
  11795. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11796. if (index === -1) {
  11797. return;
  11798. }
  11799. _this._pointerPressed.splice(index, 1);
  11800. if (index != 0) {
  11801. return;
  11802. }
  11803. previousPosition = null;
  11804. _this._offsetX = null;
  11805. _this._offsetY = null;
  11806. }
  11807. else if (p.type === 3 /* PointerMove */) {
  11808. if (evt.pointerType === "mouse") {
  11809. return;
  11810. }
  11811. if (!noPreventDefault) {
  11812. evt.preventDefault();
  11813. }
  11814. if (!previousPosition) {
  11815. return;
  11816. }
  11817. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11818. if (index != 0) {
  11819. return;
  11820. }
  11821. _this._offsetX = evt.clientX - previousPosition.x;
  11822. _this._offsetY = -(evt.clientY - previousPosition.y);
  11823. }
  11824. };
  11825. }
  11826. element.addEventListener("blur", this._onLostFocus);
  11827. };
  11828. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11829. if (this._pointerInput && element) {
  11830. this.camera.getScene().onPointerObservable.remove(this._observer);
  11831. this._observer = null;
  11832. element.removeEventListener("blur", this._onLostFocus);
  11833. this._onLostFocus = null;
  11834. this._pointerPressed = [];
  11835. this._offsetX = null;
  11836. this._offsetY = null;
  11837. this._pointerCount = 0;
  11838. }
  11839. };
  11840. FreeCameraTouchInput.prototype.checkInputs = function () {
  11841. if (this._offsetX) {
  11842. var camera = this.camera;
  11843. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11844. if (this._pointerPressed.length > 1) {
  11845. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11846. }
  11847. else {
  11848. var speed = camera._computeLocalCameraSpeed();
  11849. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11850. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11851. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11852. }
  11853. }
  11854. };
  11855. FreeCameraTouchInput.prototype.getTypeName = function () {
  11856. return "FreeCameraTouchInput";
  11857. };
  11858. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11859. return "touch";
  11860. };
  11861. __decorate([
  11862. BABYLON.serialize()
  11863. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11864. __decorate([
  11865. BABYLON.serialize()
  11866. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11867. return FreeCameraTouchInput;
  11868. }());
  11869. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11870. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11871. })(BABYLON || (BABYLON = {}));
  11872. var BABYLON;
  11873. (function (BABYLON) {
  11874. var FreeCameraDeviceOrientationInput = (function () {
  11875. function FreeCameraDeviceOrientationInput() {
  11876. this._offsetX = null;
  11877. this._offsetY = null;
  11878. this._orientationGamma = 0;
  11879. this._orientationBeta = 0;
  11880. this._initialOrientationGamma = 0;
  11881. this._initialOrientationBeta = 0;
  11882. this.angularSensibility = 10000.0;
  11883. this.moveSensibility = 50.0;
  11884. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11885. this._orientationChanged = this.orientationChanged.bind(this);
  11886. }
  11887. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11888. window.addEventListener("resize", this._resetOrientationGamma, false);
  11889. window.addEventListener("deviceorientation", this._orientationChanged);
  11890. };
  11891. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11892. this._initialOrientationGamma = null;
  11893. };
  11894. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11895. if (!this._initialOrientationGamma) {
  11896. this._initialOrientationGamma = evt.gamma;
  11897. this._initialOrientationBeta = evt.beta;
  11898. }
  11899. this._orientationGamma = evt.gamma;
  11900. this._orientationBeta = evt.beta;
  11901. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11902. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11903. };
  11904. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11905. window.removeEventListener("resize", this._resetOrientationGamma);
  11906. window.removeEventListener("deviceorientation", this._orientationChanged);
  11907. this._orientationGamma = 0;
  11908. this._orientationBeta = 0;
  11909. this._initialOrientationGamma = 0;
  11910. this._initialOrientationBeta = 0;
  11911. this._offsetX = null;
  11912. this._offsetY = null;
  11913. };
  11914. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11915. if (!this._offsetX) {
  11916. return;
  11917. }
  11918. var camera = this.camera;
  11919. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11920. var speed = camera._computeLocalCameraSpeed();
  11921. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11922. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11923. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11924. };
  11925. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11926. return "FreeCameraDeviceOrientationInput";
  11927. };
  11928. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11929. return "deviceOrientation";
  11930. };
  11931. __decorate([
  11932. BABYLON.serialize()
  11933. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11934. __decorate([
  11935. BABYLON.serialize()
  11936. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11937. return FreeCameraDeviceOrientationInput;
  11938. }());
  11939. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11940. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11941. })(BABYLON || (BABYLON = {}));
  11942. var BABYLON;
  11943. (function (BABYLON) {
  11944. var FreeCameraVRDeviceOrientationInput = (function () {
  11945. function FreeCameraVRDeviceOrientationInput() {
  11946. this.alphaCorrection = 1;
  11947. this.betaCorrection = 1;
  11948. this.gammaCorrection = 1;
  11949. this._alpha = 0;
  11950. this._beta = 0;
  11951. this._gamma = 0;
  11952. this._dirty = false;
  11953. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11954. }
  11955. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11956. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11957. };
  11958. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11959. var camera = this.camera;
  11960. this._alpha = +evt.alpha | 0;
  11961. this._beta = +evt.beta | 0;
  11962. this._gamma = +evt.gamma | 0;
  11963. this._dirty = true;
  11964. };
  11965. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11966. if (this._dirty) {
  11967. this._dirty = false;
  11968. var rotationX = this._gamma;
  11969. if (rotationX < 0) {
  11970. rotationX = 90 + rotationX;
  11971. }
  11972. else {
  11973. // Incline it in the correct angle.
  11974. rotationX = 270 - rotationX;
  11975. }
  11976. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11977. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11978. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11979. }
  11980. };
  11981. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11982. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11983. };
  11984. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11985. return "FreeCameraVRDeviceOrientationInput";
  11986. };
  11987. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11988. return "VRDeviceOrientation";
  11989. };
  11990. return FreeCameraVRDeviceOrientationInput;
  11991. }());
  11992. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  11993. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  11994. })(BABYLON || (BABYLON = {}));
  11995. var BABYLON;
  11996. (function (BABYLON) {
  11997. var FreeCameraGamepadInput = (function () {
  11998. function FreeCameraGamepadInput() {
  11999. this.gamepadAngularSensibility = 200;
  12000. this.gamepadMoveSensibility = 40;
  12001. }
  12002. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12003. var _this = this;
  12004. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12005. };
  12006. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12007. if (this._gamepads) {
  12008. this._gamepads.dispose();
  12009. }
  12010. this.gamepad = null;
  12011. };
  12012. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12013. if (this.gamepad) {
  12014. var camera = this.camera;
  12015. var LSValues = this.gamepad.leftStick;
  12016. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12017. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12018. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12019. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12020. var RSValues = this.gamepad.rightStick;
  12021. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12022. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12023. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12024. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12025. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12026. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12027. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12028. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12029. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12030. }
  12031. };
  12032. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12033. // Only the first gamepad can control the camera
  12034. if (gamepad.index === 0) {
  12035. this.gamepad = gamepad;
  12036. }
  12037. };
  12038. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12039. return "FreeCameraGamepadInput";
  12040. };
  12041. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12042. return "gamepad";
  12043. };
  12044. __decorate([
  12045. BABYLON.serialize()
  12046. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12047. __decorate([
  12048. BABYLON.serialize()
  12049. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12050. return FreeCameraGamepadInput;
  12051. }());
  12052. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12053. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12054. })(BABYLON || (BABYLON = {}));
  12055. var BABYLON;
  12056. (function (BABYLON) {
  12057. var FreeCameraVirtualJoystickInput = (function () {
  12058. function FreeCameraVirtualJoystickInput() {
  12059. }
  12060. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12061. return this._leftjoystick;
  12062. };
  12063. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12064. return this._rightjoystick;
  12065. };
  12066. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12067. if (this._leftjoystick) {
  12068. var camera = this.camera;
  12069. var speed = camera._computeLocalCameraSpeed() * 50;
  12070. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12071. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12072. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12073. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12074. if (!this._leftjoystick.pressed) {
  12075. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12076. }
  12077. if (!this._rightjoystick.pressed) {
  12078. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12079. }
  12080. }
  12081. };
  12082. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12083. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12084. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12085. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12086. this._leftjoystick.setJoystickSensibility(0.15);
  12087. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12088. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12089. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12090. this._rightjoystick.reverseUpDown = true;
  12091. this._rightjoystick.setJoystickSensibility(0.05);
  12092. this._rightjoystick.setJoystickColor("yellow");
  12093. };
  12094. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12095. this._leftjoystick.releaseCanvas();
  12096. this._rightjoystick.releaseCanvas();
  12097. };
  12098. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12099. return "FreeCameraVirtualJoystickInput";
  12100. };
  12101. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12102. return "virtualJoystick";
  12103. };
  12104. return FreeCameraVirtualJoystickInput;
  12105. }());
  12106. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12107. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12108. })(BABYLON || (BABYLON = {}));
  12109. var BABYLON;
  12110. (function (BABYLON) {
  12111. var ArcRotateCameraKeyboardMoveInput = (function () {
  12112. function ArcRotateCameraKeyboardMoveInput() {
  12113. this._keys = [];
  12114. this.keysUp = [38];
  12115. this.keysDown = [40];
  12116. this.keysLeft = [37];
  12117. this.keysRight = [39];
  12118. }
  12119. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12120. var _this = this;
  12121. this._onKeyDown = function (evt) {
  12122. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12123. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12124. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12125. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12126. var index = _this._keys.indexOf(evt.keyCode);
  12127. if (index === -1) {
  12128. _this._keys.push(evt.keyCode);
  12129. }
  12130. if (evt.preventDefault) {
  12131. if (!noPreventDefault) {
  12132. evt.preventDefault();
  12133. }
  12134. }
  12135. }
  12136. };
  12137. this._onKeyUp = function (evt) {
  12138. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12139. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12140. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12141. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12142. var index = _this._keys.indexOf(evt.keyCode);
  12143. if (index >= 0) {
  12144. _this._keys.splice(index, 1);
  12145. }
  12146. if (evt.preventDefault) {
  12147. if (!noPreventDefault) {
  12148. evt.preventDefault();
  12149. }
  12150. }
  12151. }
  12152. };
  12153. this._onLostFocus = function () {
  12154. _this._keys = [];
  12155. };
  12156. BABYLON.Tools.RegisterTopRootEvents([
  12157. { name: "keydown", handler: this._onKeyDown },
  12158. { name: "keyup", handler: this._onKeyUp },
  12159. { name: "blur", handler: this._onLostFocus }
  12160. ]);
  12161. };
  12162. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12163. BABYLON.Tools.UnregisterTopRootEvents([
  12164. { name: "keydown", handler: this._onKeyDown },
  12165. { name: "keyup", handler: this._onKeyUp },
  12166. { name: "blur", handler: this._onLostFocus }
  12167. ]);
  12168. this._keys = [];
  12169. this._onKeyDown = null;
  12170. this._onKeyUp = null;
  12171. this._onLostFocus = null;
  12172. };
  12173. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12174. if (this._onKeyDown) {
  12175. var camera = this.camera;
  12176. for (var index = 0; index < this._keys.length; index++) {
  12177. var keyCode = this._keys[index];
  12178. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12179. camera.inertialAlphaOffset -= 0.01;
  12180. }
  12181. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12182. camera.inertialBetaOffset -= 0.01;
  12183. }
  12184. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12185. camera.inertialAlphaOffset += 0.01;
  12186. }
  12187. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12188. camera.inertialBetaOffset += 0.01;
  12189. }
  12190. }
  12191. }
  12192. };
  12193. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12194. return "ArcRotateCameraKeyboardMoveInput";
  12195. };
  12196. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12197. return "keyboard";
  12198. };
  12199. __decorate([
  12200. BABYLON.serialize()
  12201. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12202. __decorate([
  12203. BABYLON.serialize()
  12204. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12205. __decorate([
  12206. BABYLON.serialize()
  12207. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12208. __decorate([
  12209. BABYLON.serialize()
  12210. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12211. return ArcRotateCameraKeyboardMoveInput;
  12212. }());
  12213. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12214. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12215. })(BABYLON || (BABYLON = {}));
  12216. var BABYLON;
  12217. (function (BABYLON) {
  12218. var ArcRotateCameraMouseWheelInput = (function () {
  12219. function ArcRotateCameraMouseWheelInput() {
  12220. this.wheelPrecision = 3.0;
  12221. }
  12222. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12223. var _this = this;
  12224. this._wheel = function (p, s) {
  12225. var event = p.event;
  12226. var delta = 0;
  12227. if (event.wheelDelta) {
  12228. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12229. }
  12230. else if (event.detail) {
  12231. delta = -event.detail / _this.wheelPrecision;
  12232. }
  12233. if (delta)
  12234. _this.camera.inertialRadiusOffset += delta;
  12235. if (event.preventDefault) {
  12236. if (!noPreventDefault) {
  12237. event.preventDefault();
  12238. }
  12239. }
  12240. };
  12241. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel);
  12242. };
  12243. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12244. if (this._observer && element) {
  12245. this.camera.getScene().onPointerObservable.remove(this._observer);
  12246. this._observer = null;
  12247. this._wheel = null;
  12248. }
  12249. };
  12250. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12251. return "ArcRotateCameraMouseWheelInput";
  12252. };
  12253. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12254. return "mousewheel";
  12255. };
  12256. __decorate([
  12257. BABYLON.serialize()
  12258. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12259. return ArcRotateCameraMouseWheelInput;
  12260. }());
  12261. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12262. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12263. })(BABYLON || (BABYLON = {}));
  12264. var BABYLON;
  12265. (function (BABYLON) {
  12266. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12267. var ArcRotateCameraPointersInput = (function () {
  12268. function ArcRotateCameraPointersInput() {
  12269. this.angularSensibilityX = 1000.0;
  12270. this.angularSensibilityY = 1000.0;
  12271. this.pinchPrecision = 6.0;
  12272. this.panningSensibility = 50.0;
  12273. this._isRightClick = false;
  12274. this._isCtrlPushed = false;
  12275. this.pinchInwards = true;
  12276. }
  12277. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12278. var _this = this;
  12279. var engine = this.camera.getEngine();
  12280. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12281. var pointers = new BABYLON.SmartCollection();
  12282. var previousPinchDistance = 0;
  12283. this._pointerInput = function (p, s) {
  12284. var evt = p.event;
  12285. if (p.type === 1 /* PointerDown */) {
  12286. evt.srcElement.setPointerCapture(evt.pointerId);
  12287. // Manage panning with right click
  12288. _this._isRightClick = evt.button === 2;
  12289. // manage pointers
  12290. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12291. cacheSoloPointer = pointers.item(evt.pointerId);
  12292. if (!noPreventDefault) {
  12293. evt.preventDefault();
  12294. }
  12295. }
  12296. else if (p.type === 2 /* PointerUp */) {
  12297. evt.srcElement.releasePointerCapture(evt.pointerId);
  12298. cacheSoloPointer = null;
  12299. previousPinchDistance = 0;
  12300. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12301. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12302. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12303. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12304. pointers.empty();
  12305. if (!noPreventDefault) {
  12306. evt.preventDefault();
  12307. }
  12308. }
  12309. else if (p.type === 3 /* PointerMove */) {
  12310. if (!noPreventDefault) {
  12311. evt.preventDefault();
  12312. }
  12313. switch (pointers.count) {
  12314. case 1:
  12315. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12316. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12317. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12318. }
  12319. else {
  12320. var offsetX = evt.clientX - cacheSoloPointer.x;
  12321. var offsetY = evt.clientY - cacheSoloPointer.y;
  12322. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12323. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12324. }
  12325. cacheSoloPointer.x = evt.clientX;
  12326. cacheSoloPointer.y = evt.clientY;
  12327. break;
  12328. case 2:
  12329. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12330. pointers.item(evt.pointerId).x = evt.clientX;
  12331. pointers.item(evt.pointerId).y = evt.clientY;
  12332. var direction = _this.pinchInwards ? 1 : -1;
  12333. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12334. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12335. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12336. if (previousPinchDistance === 0) {
  12337. previousPinchDistance = pinchSquaredDistance;
  12338. return;
  12339. }
  12340. if (pinchSquaredDistance !== previousPinchDistance) {
  12341. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12342. previousPinchDistance = pinchSquaredDistance;
  12343. }
  12344. break;
  12345. default:
  12346. if (pointers.item(evt.pointerId)) {
  12347. pointers.item(evt.pointerId).x = evt.clientX;
  12348. pointers.item(evt.pointerId).y = evt.clientY;
  12349. }
  12350. }
  12351. }
  12352. };
  12353. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput);
  12354. this._onContextMenu = function (evt) {
  12355. evt.preventDefault();
  12356. };
  12357. if (!this.camera._useCtrlForPanning) {
  12358. element.addEventListener("contextmenu", this._onContextMenu, false);
  12359. }
  12360. this._onLostFocus = function () {
  12361. //this._keys = [];
  12362. pointers.empty();
  12363. previousPinchDistance = 0;
  12364. cacheSoloPointer = null;
  12365. };
  12366. this._onKeyDown = function (evt) {
  12367. _this._isCtrlPushed = evt.ctrlKey;
  12368. };
  12369. this._onKeyUp = function (evt) {
  12370. _this._isCtrlPushed = evt.ctrlKey;
  12371. };
  12372. this._onMouseMove = function (evt) {
  12373. if (!engine.isPointerLock) {
  12374. return;
  12375. }
  12376. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12377. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12378. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12379. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12380. if (!noPreventDefault) {
  12381. evt.preventDefault();
  12382. }
  12383. };
  12384. this._onGestureStart = function (e) {
  12385. if (window.MSGesture === undefined) {
  12386. return;
  12387. }
  12388. if (!_this._MSGestureHandler) {
  12389. _this._MSGestureHandler = new MSGesture();
  12390. _this._MSGestureHandler.target = element;
  12391. }
  12392. _this._MSGestureHandler.addPointer(e.pointerId);
  12393. };
  12394. this._onGesture = function (e) {
  12395. _this.camera.radius *= e.scale;
  12396. if (e.preventDefault) {
  12397. if (!noPreventDefault) {
  12398. e.stopPropagation();
  12399. e.preventDefault();
  12400. }
  12401. }
  12402. };
  12403. element.addEventListener("mousemove", this._onMouseMove, false);
  12404. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12405. element.addEventListener("MSGestureChange", this._onGesture, false);
  12406. BABYLON.Tools.RegisterTopRootEvents([
  12407. { name: "keydown", handler: this._onKeyDown },
  12408. { name: "keyup", handler: this._onKeyUp },
  12409. { name: "blur", handler: this._onLostFocus }
  12410. ]);
  12411. };
  12412. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12413. if (element && this._observer) {
  12414. this.camera.getScene().onPointerObservable.remove(this._observer);
  12415. this._observer = null;
  12416. element.removeEventListener("contextmenu", this._onContextMenu);
  12417. element.removeEventListener("mousemove", this._onMouseMove);
  12418. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12419. element.removeEventListener("MSGestureChange", this._onGesture);
  12420. this._isRightClick = false;
  12421. this._isCtrlPushed = false;
  12422. this.pinchInwards = true;
  12423. this._onKeyDown = null;
  12424. this._onKeyUp = null;
  12425. this._onMouseMove = null;
  12426. this._onGestureStart = null;
  12427. this._onGesture = null;
  12428. this._MSGestureHandler = null;
  12429. this._onLostFocus = null;
  12430. this._onContextMenu = null;
  12431. }
  12432. BABYLON.Tools.UnregisterTopRootEvents([
  12433. { name: "keydown", handler: this._onKeyDown },
  12434. { name: "keyup", handler: this._onKeyUp },
  12435. { name: "blur", handler: this._onLostFocus }
  12436. ]);
  12437. };
  12438. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12439. return "ArcRotateCameraPointersInput";
  12440. };
  12441. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12442. return "pointers";
  12443. };
  12444. __decorate([
  12445. BABYLON.serialize()
  12446. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12447. __decorate([
  12448. BABYLON.serialize()
  12449. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12450. __decorate([
  12451. BABYLON.serialize()
  12452. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12453. __decorate([
  12454. BABYLON.serialize()
  12455. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12456. return ArcRotateCameraPointersInput;
  12457. }());
  12458. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12459. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12460. })(BABYLON || (BABYLON = {}));
  12461. var BABYLON;
  12462. (function (BABYLON) {
  12463. var ArcRotateCameraGamepadInput = (function () {
  12464. function ArcRotateCameraGamepadInput() {
  12465. this.gamepadRotationSensibility = 80;
  12466. this.gamepadMoveSensibility = 40;
  12467. }
  12468. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12469. var _this = this;
  12470. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12471. };
  12472. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12473. if (this._gamepads) {
  12474. this._gamepads.dispose();
  12475. }
  12476. this.gamepad = null;
  12477. };
  12478. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12479. if (this.gamepad) {
  12480. var camera = this.camera;
  12481. var RSValues = this.gamepad.rightStick;
  12482. if (RSValues.x != 0) {
  12483. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12484. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12485. camera.inertialAlphaOffset += normalizedRX;
  12486. }
  12487. }
  12488. if (RSValues.y != 0) {
  12489. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12490. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12491. camera.inertialBetaOffset += normalizedRY;
  12492. }
  12493. }
  12494. var LSValues = this.gamepad.leftStick;
  12495. if (LSValues.y != 0) {
  12496. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12497. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12498. this.camera.inertialRadiusOffset -= normalizedLY;
  12499. }
  12500. }
  12501. }
  12502. };
  12503. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12504. // Only the first gamepad can control the camera
  12505. if (gamepad.index === 0) {
  12506. this.gamepad = gamepad;
  12507. }
  12508. };
  12509. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12510. return "ArcRotateCameraGamepadInput";
  12511. };
  12512. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12513. return "gamepad";
  12514. };
  12515. __decorate([
  12516. BABYLON.serialize()
  12517. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12518. __decorate([
  12519. BABYLON.serialize()
  12520. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12521. return ArcRotateCameraGamepadInput;
  12522. }());
  12523. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12524. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12525. })(BABYLON || (BABYLON = {}));
  12526. var BABYLON;
  12527. (function (BABYLON) {
  12528. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12529. function ArcRotateCameraVRDeviceOrientationInput() {
  12530. this.alphaCorrection = 1;
  12531. this.betaCorrection = 1;
  12532. this.gammaCorrection = 1;
  12533. this._alpha = 0;
  12534. this._beta = 0;
  12535. this._gamma = 0;
  12536. this._dirty = false;
  12537. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12538. }
  12539. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12540. this.camera.attachControl(element, noPreventDefault);
  12541. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12542. };
  12543. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12544. var camera = this.camera;
  12545. this._alpha = +evt.alpha | 0;
  12546. this._beta = +evt.beta | 0;
  12547. this._gamma = +evt.gamma | 0;
  12548. this._dirty = true;
  12549. };
  12550. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12551. if (this._dirty) {
  12552. this._dirty = false;
  12553. if (this._gamma < 0) {
  12554. this._gamma = 180 + this._gamma;
  12555. }
  12556. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12557. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12558. }
  12559. };
  12560. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12561. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12562. };
  12563. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12564. return "ArcRotateCameraVRDeviceOrientationInput";
  12565. };
  12566. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12567. return "VRDeviceOrientation";
  12568. };
  12569. return ArcRotateCameraVRDeviceOrientationInput;
  12570. }());
  12571. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12572. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12573. })(BABYLON || (BABYLON = {}));
  12574. var BABYLON;
  12575. (function (BABYLON) {
  12576. var TargetCamera = (function (_super) {
  12577. __extends(TargetCamera, _super);
  12578. function TargetCamera(name, position, scene) {
  12579. _super.call(this, name, position, scene);
  12580. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12581. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12582. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12583. this.speed = 2.0;
  12584. this.noRotationConstraint = false;
  12585. this.lockedTarget = null;
  12586. this._currentTarget = BABYLON.Vector3.Zero();
  12587. this._viewMatrix = BABYLON.Matrix.Zero();
  12588. this._camMatrix = BABYLON.Matrix.Zero();
  12589. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12590. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12591. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12592. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12593. this._lookAtTemp = BABYLON.Matrix.Zero();
  12594. this._tempMatrix = BABYLON.Matrix.Zero();
  12595. }
  12596. TargetCamera.prototype.getFrontPosition = function (distance) {
  12597. var direction = this.getTarget().subtract(this.position);
  12598. direction.normalize();
  12599. direction.scaleInPlace(distance);
  12600. return this.globalPosition.add(direction);
  12601. };
  12602. TargetCamera.prototype._getLockedTargetPosition = function () {
  12603. if (!this.lockedTarget) {
  12604. return null;
  12605. }
  12606. return this.lockedTarget.position || this.lockedTarget;
  12607. };
  12608. // Cache
  12609. TargetCamera.prototype._initCache = function () {
  12610. _super.prototype._initCache.call(this);
  12611. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12612. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12613. };
  12614. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12615. if (!ignoreParentClass) {
  12616. _super.prototype._updateCache.call(this);
  12617. }
  12618. var lockedTargetPosition = this._getLockedTargetPosition();
  12619. if (!lockedTargetPosition) {
  12620. this._cache.lockedTarget = null;
  12621. }
  12622. else {
  12623. if (!this._cache.lockedTarget) {
  12624. this._cache.lockedTarget = lockedTargetPosition.clone();
  12625. }
  12626. else {
  12627. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12628. }
  12629. }
  12630. this._cache.rotation.copyFrom(this.rotation);
  12631. };
  12632. // Synchronized
  12633. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12634. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12635. return false;
  12636. }
  12637. var lockedTargetPosition = this._getLockedTargetPosition();
  12638. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12639. && this._cache.rotation.equals(this.rotation);
  12640. };
  12641. // Methods
  12642. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12643. var engine = this.getEngine();
  12644. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12645. };
  12646. // Target
  12647. TargetCamera.prototype.setTarget = function (target) {
  12648. this.upVector.normalize();
  12649. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12650. this._camMatrix.invert();
  12651. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12652. var vDir = target.subtract(this.position);
  12653. if (vDir.x >= 0.0) {
  12654. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12655. }
  12656. else {
  12657. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12658. }
  12659. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12660. if (isNaN(this.rotation.x)) {
  12661. this.rotation.x = 0;
  12662. }
  12663. if (isNaN(this.rotation.y)) {
  12664. this.rotation.y = 0;
  12665. }
  12666. if (isNaN(this.rotation.z)) {
  12667. this.rotation.z = 0;
  12668. }
  12669. };
  12670. TargetCamera.prototype.getTarget = function () {
  12671. return this._currentTarget;
  12672. };
  12673. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12674. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12675. };
  12676. TargetCamera.prototype._updatePosition = function () {
  12677. this.position.addInPlace(this.cameraDirection);
  12678. };
  12679. TargetCamera.prototype._checkInputs = function () {
  12680. var needToMove = this._decideIfNeedsToMove();
  12681. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12682. // Move
  12683. if (needToMove) {
  12684. this._updatePosition();
  12685. }
  12686. // Rotate
  12687. if (needToRotate) {
  12688. this.rotation.x += this.cameraRotation.x;
  12689. this.rotation.y += this.cameraRotation.y;
  12690. if (!this.noRotationConstraint) {
  12691. var limit = (Math.PI / 2) * 0.95;
  12692. if (this.rotation.x > limit)
  12693. this.rotation.x = limit;
  12694. if (this.rotation.x < -limit)
  12695. this.rotation.x = -limit;
  12696. }
  12697. }
  12698. // Inertia
  12699. if (needToMove) {
  12700. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12701. this.cameraDirection.x = 0;
  12702. }
  12703. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12704. this.cameraDirection.y = 0;
  12705. }
  12706. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12707. this.cameraDirection.z = 0;
  12708. }
  12709. this.cameraDirection.scaleInPlace(this.inertia);
  12710. }
  12711. if (needToRotate) {
  12712. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12713. this.cameraRotation.x = 0;
  12714. }
  12715. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12716. this.cameraRotation.y = 0;
  12717. }
  12718. this.cameraRotation.scaleInPlace(this.inertia);
  12719. }
  12720. _super.prototype._checkInputs.call(this);
  12721. };
  12722. TargetCamera.prototype._getViewMatrix = function () {
  12723. if (!this.lockedTarget) {
  12724. // Compute
  12725. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12726. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12727. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12728. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12729. this._lookAtTemp.invert();
  12730. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12731. }
  12732. else {
  12733. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12734. }
  12735. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12736. // Computing target and final matrix
  12737. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12738. }
  12739. else {
  12740. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12741. }
  12742. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12743. return this._viewMatrix;
  12744. };
  12745. TargetCamera.prototype._getVRViewMatrix = function () {
  12746. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12747. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12748. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12749. // Computing target and final matrix
  12750. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12751. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12752. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12753. return this._viewMatrix;
  12754. };
  12755. /**
  12756. * @override
  12757. * Override Camera.createRigCamera
  12758. */
  12759. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12760. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12761. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12762. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12763. rigCamera._cameraRigParams = {};
  12764. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12765. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12766. }
  12767. return rigCamera;
  12768. }
  12769. return null;
  12770. };
  12771. /**
  12772. * @override
  12773. * Override Camera._updateRigCameras
  12774. */
  12775. TargetCamera.prototype._updateRigCameras = function () {
  12776. switch (this.cameraRigMode) {
  12777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12779. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12780. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12781. case BABYLON.Camera.RIG_MODE_VR:
  12782. var camLeft = this._rigCameras[0];
  12783. var camRight = this._rigCameras[1];
  12784. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12785. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12786. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12787. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12788. camLeft.position.copyFrom(this.position);
  12789. camRight.position.copyFrom(this.position);
  12790. }
  12791. else {
  12792. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12793. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12794. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12795. camLeft.setTarget(this.getTarget());
  12796. camRight.setTarget(this.getTarget());
  12797. }
  12798. break;
  12799. }
  12800. _super.prototype._updateRigCameras.call(this);
  12801. };
  12802. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12803. if (!this._rigCamTransformMatrix) {
  12804. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12805. }
  12806. var target = this.getTarget();
  12807. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12808. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12809. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12810. };
  12811. TargetCamera.prototype.getTypeName = function () {
  12812. return "TargetCamera";
  12813. };
  12814. __decorate([
  12815. BABYLON.serializeAsVector3()
  12816. ], TargetCamera.prototype, "rotation", void 0);
  12817. __decorate([
  12818. BABYLON.serialize()
  12819. ], TargetCamera.prototype, "speed", void 0);
  12820. __decorate([
  12821. BABYLON.serializeAsMeshReference("lockedTargetId")
  12822. ], TargetCamera.prototype, "lockedTarget", void 0);
  12823. return TargetCamera;
  12824. }(BABYLON.Camera));
  12825. BABYLON.TargetCamera = TargetCamera;
  12826. })(BABYLON || (BABYLON = {}));
  12827. var BABYLON;
  12828. (function (BABYLON) {
  12829. var FreeCamera = (function (_super) {
  12830. __extends(FreeCamera, _super);
  12831. function FreeCamera(name, position, scene) {
  12832. var _this = this;
  12833. _super.call(this, name, position, scene);
  12834. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12835. this.checkCollisions = false;
  12836. this.applyGravity = false;
  12837. this._collider = new BABYLON.Collider();
  12838. this._needMoveForGravity = false;
  12839. this._oldPosition = BABYLON.Vector3.Zero();
  12840. this._diffPosition = BABYLON.Vector3.Zero();
  12841. this._newPosition = BABYLON.Vector3.Zero();
  12842. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12843. if (collidedMesh === void 0) { collidedMesh = null; }
  12844. //TODO move this to the collision coordinator!
  12845. if (_this.getScene().workerCollisions)
  12846. newPosition.multiplyInPlace(_this._collider.radius);
  12847. var updatePosition = function (newPos) {
  12848. _this._newPosition.copyFrom(newPos);
  12849. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12850. var oldPosition = _this.position.clone();
  12851. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12852. _this.position.addInPlace(_this._diffPosition);
  12853. if (_this.onCollide && collidedMesh) {
  12854. _this.onCollide(collidedMesh);
  12855. }
  12856. }
  12857. };
  12858. updatePosition(newPosition);
  12859. };
  12860. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12861. this.inputs.addKeyboard().addMouse();
  12862. }
  12863. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12864. //-- begin properties for backward compatibility for inputs
  12865. get: function () {
  12866. var mouse = this.inputs.attached["mouse"];
  12867. if (mouse)
  12868. return mouse.angularSensibility;
  12869. },
  12870. set: function (value) {
  12871. var mouse = this.inputs.attached["mouse"];
  12872. if (mouse)
  12873. mouse.angularSensibility = value;
  12874. },
  12875. enumerable: true,
  12876. configurable: true
  12877. });
  12878. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12879. get: function () {
  12880. var keyboard = this.inputs.attached["keyboard"];
  12881. if (keyboard)
  12882. return keyboard.keysUp;
  12883. },
  12884. set: function (value) {
  12885. var keyboard = this.inputs.attached["keyboard"];
  12886. if (keyboard)
  12887. keyboard.keysUp = value;
  12888. },
  12889. enumerable: true,
  12890. configurable: true
  12891. });
  12892. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12893. get: function () {
  12894. var keyboard = this.inputs.attached["keyboard"];
  12895. if (keyboard)
  12896. return keyboard.keysDown;
  12897. },
  12898. set: function (value) {
  12899. var keyboard = this.inputs.attached["keyboard"];
  12900. if (keyboard)
  12901. keyboard.keysDown = value;
  12902. },
  12903. enumerable: true,
  12904. configurable: true
  12905. });
  12906. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12907. get: function () {
  12908. var keyboard = this.inputs.attached["keyboard"];
  12909. if (keyboard)
  12910. return keyboard.keysLeft;
  12911. },
  12912. set: function (value) {
  12913. var keyboard = this.inputs.attached["keyboard"];
  12914. if (keyboard)
  12915. keyboard.keysLeft = value;
  12916. },
  12917. enumerable: true,
  12918. configurable: true
  12919. });
  12920. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12921. get: function () {
  12922. var keyboard = this.inputs.attached["keyboard"];
  12923. if (keyboard)
  12924. return keyboard.keysRight;
  12925. },
  12926. set: function (value) {
  12927. var keyboard = this.inputs.attached["keyboard"];
  12928. if (keyboard)
  12929. keyboard.keysRight = value;
  12930. },
  12931. enumerable: true,
  12932. configurable: true
  12933. });
  12934. // Controls
  12935. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12936. this.inputs.attachElement(element, noPreventDefault);
  12937. };
  12938. FreeCamera.prototype.detachControl = function (element) {
  12939. this.inputs.detachElement(element);
  12940. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12941. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12942. };
  12943. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12944. var globalPosition;
  12945. if (this.parent) {
  12946. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12947. }
  12948. else {
  12949. globalPosition = this.position;
  12950. }
  12951. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12952. this._collider.radius = this.ellipsoid;
  12953. //no need for clone, as long as gravity is not on.
  12954. var actualVelocity = velocity;
  12955. //add gravity to the velocity to prevent the dual-collision checking
  12956. if (this.applyGravity) {
  12957. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12958. actualVelocity = velocity.add(this.getScene().gravity);
  12959. }
  12960. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12961. };
  12962. FreeCamera.prototype._checkInputs = function () {
  12963. if (!this._localDirection) {
  12964. this._localDirection = BABYLON.Vector3.Zero();
  12965. this._transformedDirection = BABYLON.Vector3.Zero();
  12966. }
  12967. this.inputs.checkInputs();
  12968. _super.prototype._checkInputs.call(this);
  12969. };
  12970. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12971. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12972. };
  12973. FreeCamera.prototype._updatePosition = function () {
  12974. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12975. this._collideWithWorld(this.cameraDirection);
  12976. }
  12977. else {
  12978. this.position.addInPlace(this.cameraDirection);
  12979. }
  12980. };
  12981. FreeCamera.prototype.dispose = function () {
  12982. this.inputs.clear();
  12983. _super.prototype.dispose.call(this);
  12984. };
  12985. FreeCamera.prototype.getTypeName = function () {
  12986. return "FreeCamera";
  12987. };
  12988. __decorate([
  12989. BABYLON.serializeAsVector3()
  12990. ], FreeCamera.prototype, "ellipsoid", void 0);
  12991. __decorate([
  12992. BABYLON.serialize()
  12993. ], FreeCamera.prototype, "checkCollisions", void 0);
  12994. __decorate([
  12995. BABYLON.serialize()
  12996. ], FreeCamera.prototype, "applyGravity", void 0);
  12997. return FreeCamera;
  12998. }(BABYLON.TargetCamera));
  12999. BABYLON.FreeCamera = FreeCamera;
  13000. })(BABYLON || (BABYLON = {}));
  13001. var BABYLON;
  13002. (function (BABYLON) {
  13003. var FreeCameraInputsManager = (function (_super) {
  13004. __extends(FreeCameraInputsManager, _super);
  13005. function FreeCameraInputsManager(camera) {
  13006. _super.call(this, camera);
  13007. }
  13008. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13009. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13010. return this;
  13011. };
  13012. FreeCameraInputsManager.prototype.addMouse = function () {
  13013. this.add(new BABYLON.FreeCameraMouseInput());
  13014. return this;
  13015. };
  13016. FreeCameraInputsManager.prototype.addGamepad = function () {
  13017. this.add(new BABYLON.FreeCameraGamepadInput());
  13018. return this;
  13019. };
  13020. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13021. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13022. return this;
  13023. };
  13024. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13025. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13026. return this;
  13027. };
  13028. FreeCameraInputsManager.prototype.addTouch = function () {
  13029. this.add(new BABYLON.FreeCameraTouchInput());
  13030. return this;
  13031. };
  13032. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13033. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13034. return this;
  13035. };
  13036. return FreeCameraInputsManager;
  13037. }(BABYLON.CameraInputsManager));
  13038. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13039. })(BABYLON || (BABYLON = {}));
  13040. var BABYLON;
  13041. (function (BABYLON) {
  13042. var FollowCamera = (function (_super) {
  13043. __extends(FollowCamera, _super);
  13044. function FollowCamera(name, position, scene, target) {
  13045. _super.call(this, name, position, scene);
  13046. this.radius = 12;
  13047. this.rotationOffset = 0;
  13048. this.heightOffset = 4;
  13049. this.cameraAcceleration = 0.05;
  13050. this.maxCameraSpeed = 20;
  13051. this.target = target;
  13052. }
  13053. FollowCamera.prototype.getRadians = function (degrees) {
  13054. return degrees * Math.PI / 180;
  13055. };
  13056. FollowCamera.prototype.follow = function (cameraTarget) {
  13057. if (!cameraTarget)
  13058. return;
  13059. var yRotation;
  13060. if (cameraTarget.rotationQuaternion) {
  13061. var rotMatrix = new BABYLON.Matrix();
  13062. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13063. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13064. }
  13065. else {
  13066. yRotation = cameraTarget.rotation.y;
  13067. }
  13068. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13069. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13070. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13071. var dx = targetX - this.position.x;
  13072. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13073. var dz = (targetZ) - this.position.z;
  13074. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13075. var vy = dy * this.cameraAcceleration;
  13076. var vz = dz * this.cameraAcceleration * 2;
  13077. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13078. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13079. }
  13080. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13081. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13082. }
  13083. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13084. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13085. }
  13086. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13087. this.setTarget(cameraTarget.position);
  13088. };
  13089. FollowCamera.prototype._checkInputs = function () {
  13090. _super.prototype._checkInputs.call(this);
  13091. this.follow(this.target);
  13092. };
  13093. FollowCamera.prototype.getTypeName = function () {
  13094. return "FollowCamera";
  13095. };
  13096. __decorate([
  13097. BABYLON.serialize()
  13098. ], FollowCamera.prototype, "radius", void 0);
  13099. __decorate([
  13100. BABYLON.serialize()
  13101. ], FollowCamera.prototype, "rotationOffset", void 0);
  13102. __decorate([
  13103. BABYLON.serialize()
  13104. ], FollowCamera.prototype, "heightOffset", void 0);
  13105. __decorate([
  13106. BABYLON.serialize()
  13107. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13108. __decorate([
  13109. BABYLON.serialize()
  13110. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13111. __decorate([
  13112. BABYLON.serializeAsMeshReference("lockedTargetId")
  13113. ], FollowCamera.prototype, "target", void 0);
  13114. return FollowCamera;
  13115. }(BABYLON.TargetCamera));
  13116. BABYLON.FollowCamera = FollowCamera;
  13117. var ArcFollowCamera = (function (_super) {
  13118. __extends(ArcFollowCamera, _super);
  13119. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13120. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13121. this.alpha = alpha;
  13122. this.beta = beta;
  13123. this.radius = radius;
  13124. this.target = target;
  13125. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13126. this.follow();
  13127. }
  13128. ArcFollowCamera.prototype.follow = function () {
  13129. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13130. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13131. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13132. this.position = this.target.position.add(this._cartesianCoordinates);
  13133. this.setTarget(this.target.position);
  13134. };
  13135. ArcFollowCamera.prototype._checkInputs = function () {
  13136. _super.prototype._checkInputs.call(this);
  13137. this.follow();
  13138. };
  13139. ArcFollowCamera.prototype.getTypeName = function () {
  13140. return "ArcFollowCamera";
  13141. };
  13142. return ArcFollowCamera;
  13143. }(BABYLON.TargetCamera));
  13144. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13145. })(BABYLON || (BABYLON = {}));
  13146. var BABYLON;
  13147. (function (BABYLON) {
  13148. // We're mainly based on the logic defined into the FreeCamera code
  13149. var TouchCamera = (function (_super) {
  13150. __extends(TouchCamera, _super);
  13151. //-- end properties for backward compatibility for inputs
  13152. function TouchCamera(name, position, scene) {
  13153. _super.call(this, name, position, scene);
  13154. this.inputs.addTouch();
  13155. }
  13156. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13157. //-- Begin properties for backward compatibility for inputs
  13158. get: function () {
  13159. var touch = this.inputs.attached["touch"];
  13160. if (touch)
  13161. return touch.touchAngularSensibility;
  13162. },
  13163. set: function (value) {
  13164. var touch = this.inputs.attached["touch"];
  13165. if (touch)
  13166. touch.touchAngularSensibility = value;
  13167. },
  13168. enumerable: true,
  13169. configurable: true
  13170. });
  13171. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13172. get: function () {
  13173. var touch = this.inputs.attached["touch"];
  13174. if (touch)
  13175. return touch.touchMoveSensibility;
  13176. },
  13177. set: function (value) {
  13178. var touch = this.inputs.attached["touch"];
  13179. if (touch)
  13180. touch.touchMoveSensibility = value;
  13181. },
  13182. enumerable: true,
  13183. configurable: true
  13184. });
  13185. TouchCamera.prototype.getTypeName = function () {
  13186. return "TouchCamera";
  13187. };
  13188. return TouchCamera;
  13189. }(BABYLON.FreeCamera));
  13190. BABYLON.TouchCamera = TouchCamera;
  13191. })(BABYLON || (BABYLON = {}));
  13192. var BABYLON;
  13193. (function (BABYLON) {
  13194. var ArcRotateCamera = (function (_super) {
  13195. __extends(ArcRotateCamera, _super);
  13196. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13197. var _this = this;
  13198. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13199. this.inertialAlphaOffset = 0;
  13200. this.inertialBetaOffset = 0;
  13201. this.inertialRadiusOffset = 0;
  13202. this.lowerAlphaLimit = null;
  13203. this.upperAlphaLimit = null;
  13204. this.lowerBetaLimit = 0.01;
  13205. this.upperBetaLimit = Math.PI;
  13206. this.lowerRadiusLimit = null;
  13207. this.upperRadiusLimit = null;
  13208. this.inertialPanningX = 0;
  13209. this.inertialPanningY = 0;
  13210. //-- end properties for backward compatibility for inputs
  13211. this.zoomOnFactor = 1;
  13212. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13213. this.allowUpsideDown = true;
  13214. this._viewMatrix = new BABYLON.Matrix();
  13215. // Panning
  13216. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13217. this.checkCollisions = false;
  13218. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13219. this._collider = new BABYLON.Collider();
  13220. this._previousPosition = BABYLON.Vector3.Zero();
  13221. this._collisionVelocity = BABYLON.Vector3.Zero();
  13222. this._newPosition = BABYLON.Vector3.Zero();
  13223. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13224. if (collidedMesh === void 0) { collidedMesh = null; }
  13225. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13226. newPosition.multiplyInPlace(_this._collider.radius);
  13227. }
  13228. if (!collidedMesh) {
  13229. _this._previousPosition.copyFrom(_this.position);
  13230. }
  13231. else {
  13232. _this.setPosition(newPosition);
  13233. if (_this.onCollide) {
  13234. _this.onCollide(collidedMesh);
  13235. }
  13236. }
  13237. // Recompute because of constraints
  13238. var cosa = Math.cos(_this.alpha);
  13239. var sina = Math.sin(_this.alpha);
  13240. var cosb = Math.cos(_this.beta);
  13241. var sinb = Math.sin(_this.beta);
  13242. if (sinb === 0) {
  13243. sinb = 0.0001;
  13244. }
  13245. var target = _this._getTargetPosition();
  13246. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13247. _this.position.copyFrom(_this._newPosition);
  13248. var up = _this.upVector;
  13249. if (_this.allowUpsideDown && _this.beta < 0) {
  13250. up = up.clone();
  13251. up = up.negate();
  13252. }
  13253. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13254. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13255. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13256. _this._collisionTriggered = false;
  13257. };
  13258. if (!target) {
  13259. this.target = BABYLON.Vector3.Zero();
  13260. }
  13261. else {
  13262. this.target = target;
  13263. }
  13264. this.alpha = alpha;
  13265. this.beta = beta;
  13266. this.radius = radius;
  13267. this.getViewMatrix();
  13268. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13269. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13270. }
  13271. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13272. //-- begin properties for backward compatibility for inputs
  13273. get: function () {
  13274. var pointers = this.inputs.attached["pointers"];
  13275. if (pointers)
  13276. return pointers.angularSensibilityX;
  13277. },
  13278. set: function (value) {
  13279. var pointers = this.inputs.attached["pointers"];
  13280. if (pointers) {
  13281. pointers.angularSensibilityX = value;
  13282. }
  13283. },
  13284. enumerable: true,
  13285. configurable: true
  13286. });
  13287. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13288. get: function () {
  13289. var pointers = this.inputs.attached["pointers"];
  13290. if (pointers)
  13291. return pointers.angularSensibilityY;
  13292. },
  13293. set: function (value) {
  13294. var pointers = this.inputs.attached["pointers"];
  13295. if (pointers) {
  13296. pointers.angularSensibilityY = value;
  13297. }
  13298. },
  13299. enumerable: true,
  13300. configurable: true
  13301. });
  13302. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13303. get: function () {
  13304. var pointers = this.inputs.attached["pointers"];
  13305. if (pointers)
  13306. return pointers.pinchPrecision;
  13307. },
  13308. set: function (value) {
  13309. var pointers = this.inputs.attached["pointers"];
  13310. if (pointers) {
  13311. pointers.pinchPrecision = value;
  13312. }
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13318. get: function () {
  13319. var pointers = this.inputs.attached["pointers"];
  13320. if (pointers)
  13321. return pointers.panningSensibility;
  13322. },
  13323. set: function (value) {
  13324. var pointers = this.inputs.attached["pointers"];
  13325. if (pointers) {
  13326. pointers.panningSensibility = value;
  13327. }
  13328. },
  13329. enumerable: true,
  13330. configurable: true
  13331. });
  13332. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13333. get: function () {
  13334. var keyboard = this.inputs.attached["keyboard"];
  13335. if (keyboard)
  13336. return keyboard.keysUp;
  13337. },
  13338. set: function (value) {
  13339. var keyboard = this.inputs.attached["keyboard"];
  13340. if (keyboard)
  13341. keyboard.keysUp = value;
  13342. },
  13343. enumerable: true,
  13344. configurable: true
  13345. });
  13346. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13347. get: function () {
  13348. var keyboard = this.inputs.attached["keyboard"];
  13349. if (keyboard)
  13350. return keyboard.keysDown;
  13351. },
  13352. set: function (value) {
  13353. var keyboard = this.inputs.attached["keyboard"];
  13354. if (keyboard)
  13355. keyboard.keysDown = value;
  13356. },
  13357. enumerable: true,
  13358. configurable: true
  13359. });
  13360. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13361. get: function () {
  13362. var keyboard = this.inputs.attached["keyboard"];
  13363. if (keyboard)
  13364. return keyboard.keysLeft;
  13365. },
  13366. set: function (value) {
  13367. var keyboard = this.inputs.attached["keyboard"];
  13368. if (keyboard)
  13369. keyboard.keysLeft = value;
  13370. },
  13371. enumerable: true,
  13372. configurable: true
  13373. });
  13374. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13375. get: function () {
  13376. var keyboard = this.inputs.attached["keyboard"];
  13377. if (keyboard)
  13378. return keyboard.keysRight;
  13379. },
  13380. set: function (value) {
  13381. var keyboard = this.inputs.attached["keyboard"];
  13382. if (keyboard)
  13383. keyboard.keysRight = value;
  13384. },
  13385. enumerable: true,
  13386. configurable: true
  13387. });
  13388. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13389. get: function () {
  13390. var mousewheel = this.inputs.attached["mousewheel"];
  13391. if (mousewheel)
  13392. return mousewheel.wheelPrecision;
  13393. },
  13394. set: function (value) {
  13395. var mousewheel = this.inputs.attached["mousewheel"];
  13396. if (mousewheel)
  13397. mousewheel.wheelPrecision = value;
  13398. },
  13399. enumerable: true,
  13400. configurable: true
  13401. });
  13402. // Cache
  13403. ArcRotateCamera.prototype._initCache = function () {
  13404. _super.prototype._initCache.call(this);
  13405. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13406. this._cache.alpha = undefined;
  13407. this._cache.beta = undefined;
  13408. this._cache.radius = undefined;
  13409. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13410. };
  13411. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13412. if (!ignoreParentClass) {
  13413. _super.prototype._updateCache.call(this);
  13414. }
  13415. this._cache.target.copyFrom(this._getTargetPosition());
  13416. this._cache.alpha = this.alpha;
  13417. this._cache.beta = this.beta;
  13418. this._cache.radius = this.radius;
  13419. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13420. };
  13421. ArcRotateCamera.prototype._getTargetPosition = function () {
  13422. if (this.target.getAbsolutePosition) {
  13423. return this.target.getAbsolutePosition();
  13424. }
  13425. return this.target;
  13426. };
  13427. // Synchronized
  13428. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13429. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13430. return false;
  13431. return this._cache.target.equals(this.target)
  13432. && this._cache.alpha === this.alpha
  13433. && this._cache.beta === this.beta
  13434. && this._cache.radius === this.radius
  13435. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13436. };
  13437. // Methods
  13438. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13439. var _this = this;
  13440. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13441. this._useCtrlForPanning = useCtrlForPanning;
  13442. this.inputs.attachElement(element, noPreventDefault);
  13443. this._reset = function () {
  13444. _this.inertialAlphaOffset = 0;
  13445. _this.inertialBetaOffset = 0;
  13446. _this.inertialRadiusOffset = 0;
  13447. };
  13448. };
  13449. ArcRotateCamera.prototype.detachControl = function (element) {
  13450. this.inputs.detachElement(element);
  13451. if (this._reset) {
  13452. this._reset();
  13453. }
  13454. };
  13455. ArcRotateCamera.prototype._checkInputs = function () {
  13456. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13457. if (this._collisionTriggered) {
  13458. return;
  13459. }
  13460. this.inputs.checkInputs();
  13461. // Inertia
  13462. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13463. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13464. this.beta += this.inertialBetaOffset;
  13465. this.radius -= this.inertialRadiusOffset;
  13466. this.inertialAlphaOffset *= this.inertia;
  13467. this.inertialBetaOffset *= this.inertia;
  13468. this.inertialRadiusOffset *= this.inertia;
  13469. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13470. this.inertialAlphaOffset = 0;
  13471. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13472. this.inertialBetaOffset = 0;
  13473. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13474. this.inertialRadiusOffset = 0;
  13475. }
  13476. // Panning inertia
  13477. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13478. if (!this._localDirection) {
  13479. this._localDirection = BABYLON.Vector3.Zero();
  13480. this._transformedDirection = BABYLON.Vector3.Zero();
  13481. }
  13482. this.inertialPanningX *= this.inertia;
  13483. this.inertialPanningY *= this.inertia;
  13484. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13485. this.inertialPanningX = 0;
  13486. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13487. this.inertialPanningY = 0;
  13488. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13489. this._localDirection.multiplyInPlace(this.panningAxis);
  13490. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13491. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13492. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13493. if (!this.panningAxis.y) {
  13494. this._transformedDirection.y = 0;
  13495. }
  13496. this.target.addInPlace(this._transformedDirection);
  13497. }
  13498. // Limits
  13499. this._checkLimits();
  13500. _super.prototype._checkInputs.call(this);
  13501. };
  13502. ArcRotateCamera.prototype._checkLimits = function () {
  13503. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13504. if (this.allowUpsideDown && this.beta > Math.PI) {
  13505. this.beta = this.beta - (2 * Math.PI);
  13506. }
  13507. }
  13508. else {
  13509. if (this.beta < this.lowerBetaLimit) {
  13510. this.beta = this.lowerBetaLimit;
  13511. }
  13512. }
  13513. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13514. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13515. this.beta = this.beta + (2 * Math.PI);
  13516. }
  13517. }
  13518. else {
  13519. if (this.beta > this.upperBetaLimit) {
  13520. this.beta = this.upperBetaLimit;
  13521. }
  13522. }
  13523. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13524. this.alpha = this.lowerAlphaLimit;
  13525. }
  13526. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13527. this.alpha = this.upperAlphaLimit;
  13528. }
  13529. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13530. this.radius = this.lowerRadiusLimit;
  13531. }
  13532. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13533. this.radius = this.upperRadiusLimit;
  13534. }
  13535. };
  13536. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13537. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13538. this.radius = radiusv3.length();
  13539. // Alpha
  13540. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13541. if (radiusv3.z < 0) {
  13542. this.alpha = 2 * Math.PI - this.alpha;
  13543. }
  13544. // Beta
  13545. this.beta = Math.acos(radiusv3.y / this.radius);
  13546. this._checkLimits();
  13547. };
  13548. ArcRotateCamera.prototype.setPosition = function (position) {
  13549. if (this.position.equals(position)) {
  13550. return;
  13551. }
  13552. this.position = position;
  13553. this.rebuildAnglesAndRadius();
  13554. };
  13555. ArcRotateCamera.prototype.setTarget = function (target) {
  13556. if (this._getTargetPosition().equals(target)) {
  13557. return;
  13558. }
  13559. this.target = target;
  13560. this.rebuildAnglesAndRadius();
  13561. };
  13562. ArcRotateCamera.prototype._getViewMatrix = function () {
  13563. // Compute
  13564. var cosa = Math.cos(this.alpha);
  13565. var sina = Math.sin(this.alpha);
  13566. var cosb = Math.cos(this.beta);
  13567. var sinb = Math.sin(this.beta);
  13568. if (sinb === 0) {
  13569. sinb = 0.0001;
  13570. }
  13571. var target = this._getTargetPosition();
  13572. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13573. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13574. this._collider.radius = this.collisionRadius;
  13575. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13576. this._collisionTriggered = true;
  13577. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13578. }
  13579. else {
  13580. this.position.copyFrom(this._newPosition);
  13581. var up = this.upVector;
  13582. if (this.allowUpsideDown && this.beta < 0) {
  13583. up = up.clone();
  13584. up = up.negate();
  13585. }
  13586. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13587. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13588. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13589. }
  13590. return this._viewMatrix;
  13591. };
  13592. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13593. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13594. meshes = meshes || this.getScene().meshes;
  13595. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13596. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13597. this.radius = distance * this.zoomOnFactor;
  13598. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13599. };
  13600. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13601. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13602. var meshesOrMinMaxVector;
  13603. var distance;
  13604. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13605. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13606. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13607. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13608. }
  13609. else {
  13610. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13611. distance = meshesOrMinMaxVectorAndDistance.distance;
  13612. }
  13613. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13614. if (!doNotUpdateMaxZ) {
  13615. this.maxZ = distance * 2;
  13616. }
  13617. };
  13618. /**
  13619. * @override
  13620. * Override Camera.createRigCamera
  13621. */
  13622. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13623. switch (this.cameraRigMode) {
  13624. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13626. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13628. case BABYLON.Camera.RIG_MODE_VR:
  13629. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13630. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13631. rigCam._cameraRigParams = {};
  13632. return rigCam;
  13633. }
  13634. return null;
  13635. };
  13636. /**
  13637. * @override
  13638. * Override Camera._updateRigCameras
  13639. */
  13640. ArcRotateCamera.prototype._updateRigCameras = function () {
  13641. switch (this.cameraRigMode) {
  13642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13643. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13644. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13645. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13646. case BABYLON.Camera.RIG_MODE_VR:
  13647. var camLeft = this._rigCameras[0];
  13648. var camRight = this._rigCameras[1];
  13649. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13650. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13651. camLeft.beta = camRight.beta = this.beta;
  13652. camLeft.radius = camRight.radius = this.radius;
  13653. break;
  13654. }
  13655. _super.prototype._updateRigCameras.call(this);
  13656. };
  13657. ArcRotateCamera.prototype.dispose = function () {
  13658. this.inputs.clear();
  13659. _super.prototype.dispose.call(this);
  13660. };
  13661. ArcRotateCamera.prototype.getTypeName = function () {
  13662. return "ArcRotateCamera";
  13663. };
  13664. __decorate([
  13665. BABYLON.serialize()
  13666. ], ArcRotateCamera.prototype, "alpha", void 0);
  13667. __decorate([
  13668. BABYLON.serialize()
  13669. ], ArcRotateCamera.prototype, "beta", void 0);
  13670. __decorate([
  13671. BABYLON.serialize()
  13672. ], ArcRotateCamera.prototype, "radius", void 0);
  13673. __decorate([
  13674. BABYLON.serializeAsVector3()
  13675. ], ArcRotateCamera.prototype, "target", void 0);
  13676. __decorate([
  13677. BABYLON.serialize()
  13678. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13679. __decorate([
  13680. BABYLON.serialize()
  13681. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13682. __decorate([
  13683. BABYLON.serialize()
  13684. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13685. __decorate([
  13686. BABYLON.serialize()
  13687. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13688. __decorate([
  13689. BABYLON.serialize()
  13690. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13691. __decorate([
  13692. BABYLON.serialize()
  13693. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13694. __decorate([
  13695. BABYLON.serialize()
  13696. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13697. __decorate([
  13698. BABYLON.serialize()
  13699. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13700. __decorate([
  13701. BABYLON.serialize()
  13702. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13703. __decorate([
  13704. BABYLON.serialize()
  13705. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13706. __decorate([
  13707. BABYLON.serialize()
  13708. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13709. __decorate([
  13710. BABYLON.serialize()
  13711. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13712. __decorate([
  13713. BABYLON.serialize()
  13714. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13715. return ArcRotateCamera;
  13716. }(BABYLON.TargetCamera));
  13717. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13718. })(BABYLON || (BABYLON = {}));
  13719. var BABYLON;
  13720. (function (BABYLON) {
  13721. var ArcRotateCameraInputsManager = (function (_super) {
  13722. __extends(ArcRotateCameraInputsManager, _super);
  13723. function ArcRotateCameraInputsManager(camera) {
  13724. _super.call(this, camera);
  13725. }
  13726. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13727. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13728. return this;
  13729. };
  13730. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13731. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13732. return this;
  13733. };
  13734. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13735. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13736. return this;
  13737. };
  13738. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13739. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13740. return this;
  13741. };
  13742. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13743. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13744. return this;
  13745. };
  13746. return ArcRotateCameraInputsManager;
  13747. }(BABYLON.CameraInputsManager));
  13748. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13749. })(BABYLON || (BABYLON = {}));
  13750. var BABYLON;
  13751. (function (BABYLON) {
  13752. var RenderingManager = (function () {
  13753. function RenderingManager(scene) {
  13754. this._renderingGroups = new Array();
  13755. this._scene = scene;
  13756. }
  13757. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13758. if (this._scene._activeParticleSystems.length === 0) {
  13759. return;
  13760. }
  13761. // Particles
  13762. var activeCamera = this._scene.activeCamera;
  13763. var beforeParticlesDate = BABYLON.Tools.Now;
  13764. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13765. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13766. if (particleSystem.renderingGroupId !== index) {
  13767. continue;
  13768. }
  13769. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13770. continue;
  13771. }
  13772. this._clearDepthBuffer();
  13773. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13774. this._scene._activeParticles += particleSystem.render();
  13775. }
  13776. }
  13777. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13778. };
  13779. RenderingManager.prototype._renderSprites = function (index) {
  13780. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13781. return;
  13782. }
  13783. // Sprites
  13784. var activeCamera = this._scene.activeCamera;
  13785. var beforeSpritessDate = BABYLON.Tools.Now;
  13786. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13787. var spriteManager = this._scene.spriteManagers[id];
  13788. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13789. this._clearDepthBuffer();
  13790. spriteManager.render();
  13791. }
  13792. }
  13793. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13794. };
  13795. RenderingManager.prototype._clearDepthBuffer = function () {
  13796. if (this._depthBufferAlreadyCleaned) {
  13797. return;
  13798. }
  13799. this._scene.getEngine().clear(0, false, true);
  13800. this._depthBufferAlreadyCleaned = true;
  13801. };
  13802. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13803. if (this._currentRenderSprites) {
  13804. this._renderSprites(this._currentIndex);
  13805. }
  13806. if (this._currentRenderParticles) {
  13807. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13808. }
  13809. };
  13810. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13811. this._currentActiveMeshes = activeMeshes;
  13812. this._currentRenderParticles = renderParticles;
  13813. this._currentRenderSprites = renderSprites;
  13814. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13815. this._depthBufferAlreadyCleaned = index == 0;
  13816. var renderingGroup = this._renderingGroups[index];
  13817. var needToStepBack = false;
  13818. this._currentIndex = index;
  13819. if (renderingGroup) {
  13820. this._clearDepthBuffer();
  13821. if (!renderingGroup.onBeforeTransparentRendering) {
  13822. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13823. }
  13824. if (!renderingGroup.render(customRenderFunction)) {
  13825. this._renderingGroups.splice(index, 1);
  13826. needToStepBack = true;
  13827. this._renderSpritesAndParticles();
  13828. }
  13829. }
  13830. else {
  13831. this._renderSpritesAndParticles();
  13832. }
  13833. if (needToStepBack) {
  13834. index--;
  13835. }
  13836. }
  13837. };
  13838. RenderingManager.prototype.reset = function () {
  13839. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13840. if (renderingGroup) {
  13841. renderingGroup.prepare();
  13842. }
  13843. });
  13844. };
  13845. RenderingManager.prototype.dispatch = function (subMesh) {
  13846. var mesh = subMesh.getMesh();
  13847. var renderingGroupId = mesh.renderingGroupId || 0;
  13848. if (!this._renderingGroups[renderingGroupId]) {
  13849. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13850. }
  13851. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13852. };
  13853. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13854. return RenderingManager;
  13855. }());
  13856. BABYLON.RenderingManager = RenderingManager;
  13857. })(BABYLON || (BABYLON = {}));
  13858. var BABYLON;
  13859. (function (BABYLON) {
  13860. var RenderingGroup = (function () {
  13861. function RenderingGroup(index, scene) {
  13862. this.index = index;
  13863. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13864. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13865. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13866. this._scene = scene;
  13867. }
  13868. RenderingGroup.prototype.render = function (customRenderFunction) {
  13869. if (customRenderFunction) {
  13870. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13871. return true;
  13872. }
  13873. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13874. if (this.onBeforeTransparentRendering) {
  13875. this.onBeforeTransparentRendering();
  13876. }
  13877. return false;
  13878. }
  13879. var engine = this._scene.getEngine();
  13880. // Opaque
  13881. var subIndex;
  13882. var submesh;
  13883. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13884. submesh = this._opaqueSubMeshes.data[subIndex];
  13885. submesh.render(false);
  13886. }
  13887. // Alpha test
  13888. engine.setAlphaTesting(true);
  13889. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13890. submesh = this._alphaTestSubMeshes.data[subIndex];
  13891. submesh.render(false);
  13892. }
  13893. engine.setAlphaTesting(false);
  13894. if (this.onBeforeTransparentRendering) {
  13895. this.onBeforeTransparentRendering();
  13896. }
  13897. // Transparent
  13898. if (this._transparentSubMeshes.length) {
  13899. // Sorting
  13900. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13901. submesh = this._transparentSubMeshes.data[subIndex];
  13902. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13903. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13904. }
  13905. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13906. sortedArray.sort(function (a, b) {
  13907. // Alpha index first
  13908. if (a._alphaIndex > b._alphaIndex) {
  13909. return 1;
  13910. }
  13911. if (a._alphaIndex < b._alphaIndex) {
  13912. return -1;
  13913. }
  13914. // Then distance to camera
  13915. if (a._distanceToCamera < b._distanceToCamera) {
  13916. return 1;
  13917. }
  13918. if (a._distanceToCamera > b._distanceToCamera) {
  13919. return -1;
  13920. }
  13921. return 0;
  13922. });
  13923. // Rendering
  13924. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13925. submesh = sortedArray[subIndex];
  13926. submesh.render(true);
  13927. }
  13928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13929. }
  13930. return true;
  13931. };
  13932. RenderingGroup.prototype.prepare = function () {
  13933. this._opaqueSubMeshes.reset();
  13934. this._transparentSubMeshes.reset();
  13935. this._alphaTestSubMeshes.reset();
  13936. };
  13937. RenderingGroup.prototype.dispatch = function (subMesh) {
  13938. var material = subMesh.getMaterial();
  13939. var mesh = subMesh.getMesh();
  13940. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13941. this._transparentSubMeshes.push(subMesh);
  13942. }
  13943. else if (material.needAlphaTesting()) {
  13944. this._alphaTestSubMeshes.push(subMesh);
  13945. }
  13946. else {
  13947. this._opaqueSubMeshes.push(subMesh); // Opaque
  13948. }
  13949. };
  13950. return RenderingGroup;
  13951. }());
  13952. BABYLON.RenderingGroup = RenderingGroup;
  13953. })(BABYLON || (BABYLON = {}));
  13954. var BABYLON;
  13955. (function (BABYLON) {
  13956. /**
  13957. * This type contains all the data related to a pointer event in Babylon.js.
  13958. * The event member is an instnce of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel
  13959. */
  13960. var PointerInfo = (function () {
  13961. function PointerInfo(type, event, pickInfo) {
  13962. this.type = type;
  13963. this.event = event;
  13964. this.pickInfo = pickInfo;
  13965. }
  13966. return PointerInfo;
  13967. }());
  13968. BABYLON.PointerInfo = PointerInfo;
  13969. /**
  13970. * Represents a scene to be rendered by the engine.
  13971. * @see http://doc.babylonjs.com/page.php?p=21911
  13972. */
  13973. var Scene = (function () {
  13974. /**
  13975. * @constructor
  13976. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  13977. */
  13978. function Scene(engine) {
  13979. // Members
  13980. this.autoClear = true;
  13981. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  13982. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13983. this.forceWireframe = false;
  13984. this.forcePointsCloud = false;
  13985. this.forceShowBoundingBoxes = false;
  13986. this.animationsEnabled = true;
  13987. this.constantlyUpdateMeshUnderPointer = false;
  13988. // Events
  13989. /**
  13990. * An event triggered when the scene is disposed.
  13991. * @type {BABYLON.Observable}
  13992. */
  13993. this.onDisposeObservable = new BABYLON.Observable();
  13994. /**
  13995. * An event triggered before rendering the scene
  13996. * @type {BABYLON.Observable}
  13997. */
  13998. this.onBeforeRenderObservable = new BABYLON.Observable();
  13999. /**
  14000. * An event triggered after rendering the scene
  14001. * @type {BABYLON.Observable}
  14002. */
  14003. this.onAfterRenderObservable = new BABYLON.Observable();
  14004. /**
  14005. * An event triggered when the scene is ready
  14006. * @type {BABYLON.Observable}
  14007. */
  14008. this.onReadyObservable = new BABYLON.Observable();
  14009. /**
  14010. * An event triggered before rendering a camera
  14011. * @type {BABYLON.Observable}
  14012. */
  14013. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14014. /**
  14015. * An event triggered after rendering a camera
  14016. * @type {BABYLON.Observable}
  14017. */
  14018. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14019. /**
  14020. * An event triggered when a camera is created
  14021. * @type {BABYLON.Observable}
  14022. */
  14023. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14024. /**
  14025. * An event triggered when a camera is removed
  14026. * @type {BABYLON.Observable}
  14027. */
  14028. this.onCameraRemovedObservable = new BABYLON.Observable();
  14029. /**
  14030. * An event triggered when a light is created
  14031. * @type {BABYLON.Observable}
  14032. */
  14033. this.onNewLightAddedObservable = new BABYLON.Observable();
  14034. /**
  14035. * An event triggered when a light is removed
  14036. * @type {BABYLON.Observable}
  14037. */
  14038. this.onLightRemovedObservable = new BABYLON.Observable();
  14039. /**
  14040. * An event triggered when a geometry is created
  14041. * @type {BABYLON.Observable}
  14042. */
  14043. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14044. /**
  14045. * An event triggered when a geometry is removed
  14046. * @type {BABYLON.Observable}
  14047. */
  14048. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14049. /**
  14050. * An event triggered when a mesh is created
  14051. * @type {BABYLON.Observable}
  14052. */
  14053. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14054. /**
  14055. * An event triggered when a mesh is removed
  14056. * @type {BABYLON.Observable}
  14057. */
  14058. this.onMeshRemovedObservable = new BABYLON.Observable();
  14059. // Animations
  14060. this.animations = [];
  14061. /**
  14062. * Observable event triggered each time an input event is received from the rendering canvas
  14063. */
  14064. this.onPointerObservable = new BABYLON.Observable();
  14065. 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
  14066. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14067. this._startingPointerTime = 0;
  14068. // Fog
  14069. /**
  14070. * is fog enabled on this scene.
  14071. * @type {boolean}
  14072. */
  14073. this.fogEnabled = true;
  14074. this.fogMode = Scene.FOGMODE_NONE;
  14075. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14076. this.fogDensity = 0.1;
  14077. this.fogStart = 0;
  14078. this.fogEnd = 1000.0;
  14079. // Lights
  14080. /**
  14081. * is shadow enabled on this scene.
  14082. * @type {boolean}
  14083. */
  14084. this.shadowsEnabled = true;
  14085. /**
  14086. * is light enabled on this scene.
  14087. * @type {boolean}
  14088. */
  14089. this.lightsEnabled = true;
  14090. /**
  14091. * All of the lights added to this scene.
  14092. * @see BABYLON.Light
  14093. * @type {BABYLON.Light[]}
  14094. */
  14095. this.lights = new Array();
  14096. // Cameras
  14097. /**
  14098. * All of the cameras added to this scene.
  14099. * @see BABYLON.Camera
  14100. * @type {BABYLON.Camera[]}
  14101. */
  14102. this.cameras = new Array();
  14103. this.activeCameras = new Array();
  14104. // Meshes
  14105. /**
  14106. * All of the (abstract) meshes added to this scene.
  14107. * @see BABYLON.AbstractMesh
  14108. * @type {BABYLON.AbstractMesh[]}
  14109. */
  14110. this.meshes = new Array();
  14111. // Geometries
  14112. this._geometries = new Array();
  14113. this.materials = new Array();
  14114. this.multiMaterials = new Array();
  14115. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14116. // Textures
  14117. this.texturesEnabled = true;
  14118. this.textures = new Array();
  14119. // Particles
  14120. this.particlesEnabled = true;
  14121. this.particleSystems = new Array();
  14122. // Sprites
  14123. this.spritesEnabled = true;
  14124. this.spriteManagers = new Array();
  14125. // Layers
  14126. this.layers = new Array();
  14127. // Skeletons
  14128. this.skeletonsEnabled = true;
  14129. this.skeletons = new Array();
  14130. // Lens flares
  14131. this.lensFlaresEnabled = true;
  14132. this.lensFlareSystems = new Array();
  14133. // Collisions
  14134. this.collisionsEnabled = true;
  14135. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14136. // Postprocesses
  14137. this.postProcessesEnabled = true;
  14138. // Customs render targets
  14139. this.renderTargetsEnabled = true;
  14140. this.dumpNextRenderTargets = false;
  14141. this.customRenderTargets = new Array();
  14142. // Imported meshes
  14143. this.importedMeshesFiles = new Array();
  14144. // Probes
  14145. this.probesEnabled = true;
  14146. this.reflectionProbes = new Array();
  14147. this._actionManagers = new Array();
  14148. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14149. // Procedural textures
  14150. this.proceduralTexturesEnabled = true;
  14151. this._proceduralTextures = new Array();
  14152. this.soundTracks = new Array();
  14153. this._audioEnabled = true;
  14154. this._headphone = false;
  14155. this._totalVertices = 0;
  14156. this._activeIndices = 0;
  14157. this._activeParticles = 0;
  14158. this._lastFrameDuration = 0;
  14159. this._evaluateActiveMeshesDuration = 0;
  14160. this._renderTargetsDuration = 0;
  14161. this._particlesDuration = 0;
  14162. this._renderDuration = 0;
  14163. this._spritesDuration = 0;
  14164. this._animationRatio = 0;
  14165. this._renderId = 0;
  14166. this._executeWhenReadyTimeoutId = -1;
  14167. this._intermediateRendering = false;
  14168. this._toBeDisposed = new BABYLON.SmartArray(256);
  14169. this._pendingData = []; //ANY
  14170. this._activeMeshes = new BABYLON.SmartArray(256);
  14171. this._processedMaterials = new BABYLON.SmartArray(256);
  14172. this._renderTargets = new BABYLON.SmartArray(256);
  14173. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14174. this._activeSkeletons = new BABYLON.SmartArray(32);
  14175. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14176. this._activeBones = 0;
  14177. this._activeAnimatables = new Array();
  14178. this._transformMatrix = BABYLON.Matrix.Zero();
  14179. this._edgesRenderers = new BABYLON.SmartArray(16);
  14180. this._uniqueIdCounter = 0;
  14181. this._engine = engine;
  14182. engine.scenes.push(this);
  14183. this._renderingManager = new BABYLON.RenderingManager(this);
  14184. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14185. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14186. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14187. if (BABYLON.OutlineRenderer) {
  14188. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14189. }
  14190. this.attachControl();
  14191. this._debugLayer = new BABYLON.DebugLayer(this);
  14192. if (BABYLON.SoundTrack) {
  14193. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14194. }
  14195. //simplification queue
  14196. if (BABYLON.SimplificationQueue) {
  14197. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14198. }
  14199. //collision coordinator initialization. For now legacy per default.
  14200. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14201. }
  14202. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14203. get: function () {
  14204. return Scene._FOGMODE_NONE;
  14205. },
  14206. enumerable: true,
  14207. configurable: true
  14208. });
  14209. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14210. get: function () {
  14211. return Scene._FOGMODE_EXP;
  14212. },
  14213. enumerable: true,
  14214. configurable: true
  14215. });
  14216. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14217. get: function () {
  14218. return Scene._FOGMODE_EXP2;
  14219. },
  14220. enumerable: true,
  14221. configurable: true
  14222. });
  14223. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14224. get: function () {
  14225. return Scene._FOGMODE_LINEAR;
  14226. },
  14227. enumerable: true,
  14228. configurable: true
  14229. });
  14230. Object.defineProperty(Scene.prototype, "onDispose", {
  14231. set: function (callback) {
  14232. if (this._onDisposeObserver) {
  14233. this.onDisposeObservable.remove(this._onDisposeObserver);
  14234. }
  14235. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14236. },
  14237. enumerable: true,
  14238. configurable: true
  14239. });
  14240. Object.defineProperty(Scene.prototype, "beforeRender", {
  14241. set: function (callback) {
  14242. if (this._onBeforeRenderObserver) {
  14243. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14244. }
  14245. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. Object.defineProperty(Scene.prototype, "afterRender", {
  14251. set: function (callback) {
  14252. if (this._onAfterRenderObserver) {
  14253. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14254. }
  14255. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14256. },
  14257. enumerable: true,
  14258. configurable: true
  14259. });
  14260. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14261. set: function (callback) {
  14262. if (this._onBeforeCameraRenderObserver) {
  14263. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14264. }
  14265. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14271. set: function (callback) {
  14272. if (this._onAfterCameraRenderObserver) {
  14273. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14274. }
  14275. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. Object.defineProperty(Scene.prototype, "debugLayer", {
  14281. // Properties
  14282. get: function () {
  14283. return this._debugLayer;
  14284. },
  14285. enumerable: true,
  14286. configurable: true
  14287. });
  14288. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14289. get: function () {
  14290. return this._workerCollisions;
  14291. },
  14292. set: function (enabled) {
  14293. enabled = (enabled && !!Worker);
  14294. this._workerCollisions = enabled;
  14295. if (this.collisionCoordinator) {
  14296. this.collisionCoordinator.destroy();
  14297. }
  14298. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14299. this.collisionCoordinator.init(this);
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14305. get: function () {
  14306. return this._selectionOctree;
  14307. },
  14308. enumerable: true,
  14309. configurable: true
  14310. });
  14311. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14312. /**
  14313. * The mesh that is currently under the pointer.
  14314. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14315. */
  14316. get: function () {
  14317. return this._pointerOverMesh;
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Object.defineProperty(Scene.prototype, "pointerX", {
  14323. /**
  14324. * Current on-screen X position of the pointer
  14325. * @return {number} X position of the pointer
  14326. */
  14327. get: function () {
  14328. return this._pointerX;
  14329. },
  14330. enumerable: true,
  14331. configurable: true
  14332. });
  14333. Object.defineProperty(Scene.prototype, "pointerY", {
  14334. /**
  14335. * Current on-screen Y position of the pointer
  14336. * @return {number} Y position of the pointer
  14337. */
  14338. get: function () {
  14339. return this._pointerY;
  14340. },
  14341. enumerable: true,
  14342. configurable: true
  14343. });
  14344. Scene.prototype.getCachedMaterial = function () {
  14345. return this._cachedMaterial;
  14346. };
  14347. Scene.prototype.getBoundingBoxRenderer = function () {
  14348. return this._boundingBoxRenderer;
  14349. };
  14350. Scene.prototype.getOutlineRenderer = function () {
  14351. return this._outlineRenderer;
  14352. };
  14353. Scene.prototype.getEngine = function () {
  14354. return this._engine;
  14355. };
  14356. Scene.prototype.getTotalVertices = function () {
  14357. return this._totalVertices;
  14358. };
  14359. Scene.prototype.getActiveIndices = function () {
  14360. return this._activeIndices;
  14361. };
  14362. Scene.prototype.getActiveParticles = function () {
  14363. return this._activeParticles;
  14364. };
  14365. Scene.prototype.getActiveBones = function () {
  14366. return this._activeBones;
  14367. };
  14368. // Stats
  14369. Scene.prototype.getLastFrameDuration = function () {
  14370. return this._lastFrameDuration;
  14371. };
  14372. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14373. return this._evaluateActiveMeshesDuration;
  14374. };
  14375. Scene.prototype.getActiveMeshes = function () {
  14376. return this._activeMeshes;
  14377. };
  14378. Scene.prototype.getRenderTargetsDuration = function () {
  14379. return this._renderTargetsDuration;
  14380. };
  14381. Scene.prototype.getRenderDuration = function () {
  14382. return this._renderDuration;
  14383. };
  14384. Scene.prototype.getParticlesDuration = function () {
  14385. return this._particlesDuration;
  14386. };
  14387. Scene.prototype.getSpritesDuration = function () {
  14388. return this._spritesDuration;
  14389. };
  14390. Scene.prototype.getAnimationRatio = function () {
  14391. return this._animationRatio;
  14392. };
  14393. Scene.prototype.getRenderId = function () {
  14394. return this._renderId;
  14395. };
  14396. Scene.prototype.incrementRenderId = function () {
  14397. this._renderId++;
  14398. };
  14399. Scene.prototype._updatePointerPosition = function (evt) {
  14400. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14401. this._pointerX = evt.clientX - canvasRect.left;
  14402. this._pointerY = evt.clientY - canvasRect.top;
  14403. this._unTranslatedPointerX = this._pointerX;
  14404. this._unTranslatedPointerY = this._pointerY;
  14405. if (this.cameraToUseForPointers) {
  14406. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14407. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14408. }
  14409. };
  14410. // Pointers handling
  14411. /**
  14412. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14413. * @param attachUp defines if you want to attach events to pointerup
  14414. * @param attachDown defines if you want to attach events to pointerdown
  14415. * @param attachMove defines if you want to attach events to pointermove
  14416. */
  14417. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14418. var _this = this;
  14419. if (attachUp === void 0) { attachUp = true; }
  14420. if (attachDown === void 0) { attachDown = true; }
  14421. if (attachMove === void 0) { attachMove = true; }
  14422. var spritePredicate = function (sprite) {
  14423. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14424. };
  14425. this._onPointerMove = function (evt) {
  14426. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14427. return;
  14428. }
  14429. var canvas = _this._engine.getRenderingCanvas();
  14430. _this._updatePointerPosition(evt);
  14431. if (!_this.pointerMovePredicate) {
  14432. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14433. }
  14434. // Meshes
  14435. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14436. if (pickResult.hit && pickResult.pickedMesh) {
  14437. _this.setPointerOverSprite(null);
  14438. _this.setPointerOverMesh(pickResult.pickedMesh);
  14439. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14440. canvas.style.cursor = "pointer";
  14441. }
  14442. else {
  14443. canvas.style.cursor = "";
  14444. }
  14445. }
  14446. else {
  14447. _this.setPointerOverMesh(null);
  14448. // Sprites
  14449. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14450. if (pickResult.hit && pickResult.pickedSprite) {
  14451. canvas.style.cursor = "pointer";
  14452. _this.setPointerOverSprite(pickResult.pickedSprite);
  14453. }
  14454. else {
  14455. _this.setPointerOverSprite(null);
  14456. // Restore pointer
  14457. canvas.style.cursor = "";
  14458. }
  14459. }
  14460. if (_this.onPointerMove) {
  14461. _this.onPointerMove(evt, pickResult);
  14462. }
  14463. if (_this.onPointerObservable.hasObservers()) {
  14464. var pi = new PointerInfo(evt.type === "mousewheel" ? 4 /* PointerWheel */ : 3 /* PointerMove */, evt, pickResult);
  14465. _this.onPointerObservable.notifyObservers(pi);
  14466. }
  14467. };
  14468. this._onPointerDown = function (evt) {
  14469. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14470. return;
  14471. }
  14472. _this._updatePointerPosition(evt);
  14473. _this._startingPointerPosition.x = _this._pointerX;
  14474. _this._startingPointerPosition.y = _this._pointerY;
  14475. _this._startingPointerTime = new Date().getTime();
  14476. if (!_this.pointerDownPredicate) {
  14477. _this.pointerDownPredicate = function (mesh) {
  14478. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14479. };
  14480. }
  14481. // Meshes
  14482. _this._pickedDownMesh = null;
  14483. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14484. if (pickResult.hit && pickResult.pickedMesh) {
  14485. if (pickResult.pickedMesh.actionManager) {
  14486. _this._pickedDownMesh = pickResult.pickedMesh;
  14487. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14488. switch (evt.button) {
  14489. case 0:
  14490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14491. break;
  14492. case 1:
  14493. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14494. break;
  14495. case 2:
  14496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14497. break;
  14498. }
  14499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14500. }
  14501. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14502. var that = _this;
  14503. window.setTimeout(function () {
  14504. 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);
  14505. if (pickResult.hit && pickResult.pickedMesh) {
  14506. if (pickResult.pickedMesh.actionManager) {
  14507. 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)) {
  14508. that._startingPointerTime = 0;
  14509. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14510. }
  14511. }
  14512. }
  14513. }, BABYLON.ActionManager.LongPressDelay);
  14514. }
  14515. }
  14516. }
  14517. if (_this.onPointerDown) {
  14518. _this.onPointerDown(evt, pickResult);
  14519. }
  14520. if (_this.onPointerObservable.hasObservers()) {
  14521. var pi = new PointerInfo(1 /* PointerDown */, evt, pickResult);
  14522. _this.onPointerObservable.notifyObservers(pi);
  14523. }
  14524. // Sprites
  14525. _this._pickedDownSprite = null;
  14526. if (_this.spriteManagers.length > 0) {
  14527. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14528. if (pickResult.hit && pickResult.pickedSprite) {
  14529. if (pickResult.pickedSprite.actionManager) {
  14530. _this._pickedDownSprite = pickResult.pickedSprite;
  14531. switch (evt.button) {
  14532. case 0:
  14533. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14534. break;
  14535. case 1:
  14536. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14537. break;
  14538. case 2:
  14539. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14540. break;
  14541. }
  14542. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14543. }
  14544. }
  14545. }
  14546. };
  14547. this._onPointerUp = function (evt) {
  14548. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14549. return;
  14550. }
  14551. _this._updatePointerPosition(evt);
  14552. if (!_this.pointerUpPredicate) {
  14553. _this.pointerUpPredicate = function (mesh) {
  14554. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14555. };
  14556. }
  14557. // Meshes
  14558. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14559. if (pickResult.hit && pickResult.pickedMesh) {
  14560. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14561. if (_this.onPointerPick) {
  14562. _this.onPointerPick(evt, pickResult);
  14563. }
  14564. if (_this.onPointerObservable.hasObservers()) {
  14565. var pi = new PointerInfo(5 /* PointerPick */, evt, pickResult);
  14566. _this.onPointerObservable.notifyObservers(pi);
  14567. }
  14568. }
  14569. if (pickResult.pickedMesh.actionManager) {
  14570. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14571. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14572. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14573. }
  14574. }
  14575. }
  14576. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14577. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14578. }
  14579. if (_this.onPointerUp) {
  14580. _this.onPointerUp(evt, pickResult);
  14581. }
  14582. if (_this.onPointerObservable.hasObservers()) {
  14583. var pi = new PointerInfo(2 /* PointerUp */, evt, pickResult);
  14584. _this.onPointerObservable.notifyObservers(pi);
  14585. }
  14586. _this._startingPointerTime = 0;
  14587. // Sprites
  14588. if (_this.spriteManagers.length > 0) {
  14589. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14590. if (pickResult.hit && pickResult.pickedSprite) {
  14591. if (pickResult.pickedSprite.actionManager) {
  14592. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14593. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14594. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14595. }
  14596. }
  14597. }
  14598. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14599. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14600. }
  14601. }
  14602. };
  14603. this._onKeyDown = function (evt) {
  14604. if (_this.actionManager) {
  14605. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14606. }
  14607. };
  14608. this._onKeyUp = function (evt) {
  14609. if (_this.actionManager) {
  14610. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14611. }
  14612. };
  14613. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14614. if (attachMove) {
  14615. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14616. // Wheel
  14617. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14618. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14619. }
  14620. if (attachDown) {
  14621. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14622. }
  14623. if (attachUp) {
  14624. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14625. }
  14626. BABYLON.Tools.RegisterTopRootEvents([
  14627. { name: "keydown", handler: this._onKeyDown },
  14628. { name: "keyup", handler: this._onKeyUp }
  14629. ]);
  14630. };
  14631. Scene.prototype.detachControl = function () {
  14632. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14633. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14634. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14635. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14636. // Wheel
  14637. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14638. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14639. BABYLON.Tools.UnregisterTopRootEvents([
  14640. { name: "keydown", handler: this._onKeyDown },
  14641. { name: "keyup", handler: this._onKeyUp }
  14642. ]);
  14643. };
  14644. // Ready
  14645. Scene.prototype.isReady = function () {
  14646. if (this._pendingData.length > 0) {
  14647. return false;
  14648. }
  14649. var index;
  14650. for (index = 0; index < this._geometries.length; index++) {
  14651. var geometry = this._geometries[index];
  14652. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14653. return false;
  14654. }
  14655. }
  14656. for (index = 0; index < this.meshes.length; index++) {
  14657. var mesh = this.meshes[index];
  14658. if (!mesh.isReady()) {
  14659. return false;
  14660. }
  14661. var mat = mesh.material;
  14662. if (mat) {
  14663. if (!mat.isReady(mesh)) {
  14664. return false;
  14665. }
  14666. }
  14667. }
  14668. return true;
  14669. };
  14670. Scene.prototype.resetCachedMaterial = function () {
  14671. this._cachedMaterial = null;
  14672. };
  14673. Scene.prototype.registerBeforeRender = function (func) {
  14674. this.onBeforeRenderObservable.add(func);
  14675. };
  14676. Scene.prototype.unregisterBeforeRender = function (func) {
  14677. this.onBeforeRenderObservable.removeCallback(func);
  14678. };
  14679. Scene.prototype.registerAfterRender = function (func) {
  14680. this.onAfterRenderObservable.add(func);
  14681. };
  14682. Scene.prototype.unregisterAfterRender = function (func) {
  14683. this.onAfterRenderObservable.removeCallback(func);
  14684. };
  14685. Scene.prototype._addPendingData = function (data) {
  14686. this._pendingData.push(data);
  14687. };
  14688. Scene.prototype._removePendingData = function (data) {
  14689. var index = this._pendingData.indexOf(data);
  14690. if (index !== -1) {
  14691. this._pendingData.splice(index, 1);
  14692. }
  14693. };
  14694. Scene.prototype.getWaitingItemsCount = function () {
  14695. return this._pendingData.length;
  14696. };
  14697. /**
  14698. * Registers a function to be executed when the scene is ready.
  14699. * @param {Function} func - the function to be executed.
  14700. */
  14701. Scene.prototype.executeWhenReady = function (func) {
  14702. var _this = this;
  14703. this.onReadyObservable.add(func);
  14704. if (this._executeWhenReadyTimeoutId !== -1) {
  14705. return;
  14706. }
  14707. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14708. _this._checkIsReady();
  14709. }, 150);
  14710. };
  14711. Scene.prototype._checkIsReady = function () {
  14712. var _this = this;
  14713. if (this.isReady()) {
  14714. this.onReadyObservable.notifyObservers(this);
  14715. this.onReadyObservable.clear();
  14716. this._executeWhenReadyTimeoutId = -1;
  14717. return;
  14718. }
  14719. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14720. _this._checkIsReady();
  14721. }, 150);
  14722. };
  14723. // Animations
  14724. /**
  14725. * Will start the animation sequence of a given target
  14726. * @param target - the target
  14727. * @param {number} from - from which frame should animation start
  14728. * @param {number} to - till which frame should animation run.
  14729. * @param {boolean} [loop] - should the animation loop
  14730. * @param {number} [speedRatio] - the speed in which to run the animation
  14731. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14732. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14733. * @return {BABYLON.Animatable} the animatable object created for this animation
  14734. * @see BABYLON.Animatable
  14735. * @see http://doc.babylonjs.com/page.php?p=22081
  14736. */
  14737. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14738. if (speedRatio === void 0) { speedRatio = 1.0; }
  14739. this.stopAnimation(target);
  14740. if (!animatable) {
  14741. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14742. }
  14743. // Local animations
  14744. if (target.animations) {
  14745. animatable.appendAnimations(target, target.animations);
  14746. }
  14747. // Children animations
  14748. if (target.getAnimatables) {
  14749. var animatables = target.getAnimatables();
  14750. for (var index = 0; index < animatables.length; index++) {
  14751. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14752. }
  14753. }
  14754. animatable.reset();
  14755. return animatable;
  14756. };
  14757. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14758. if (speedRatio === undefined) {
  14759. speedRatio = 1.0;
  14760. }
  14761. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14762. return animatable;
  14763. };
  14764. Scene.prototype.getAnimatableByTarget = function (target) {
  14765. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14766. if (this._activeAnimatables[index].target === target) {
  14767. return this._activeAnimatables[index];
  14768. }
  14769. }
  14770. return null;
  14771. };
  14772. Object.defineProperty(Scene.prototype, "Animatables", {
  14773. get: function () {
  14774. return this._activeAnimatables;
  14775. },
  14776. enumerable: true,
  14777. configurable: true
  14778. });
  14779. /**
  14780. * Will stop the animation of the given target
  14781. * @param target - the target
  14782. * @see beginAnimation
  14783. */
  14784. Scene.prototype.stopAnimation = function (target) {
  14785. var animatable = this.getAnimatableByTarget(target);
  14786. if (animatable) {
  14787. animatable.stop();
  14788. }
  14789. };
  14790. Scene.prototype._animate = function () {
  14791. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14792. return;
  14793. }
  14794. if (!this._animationStartDate) {
  14795. if (this._pendingData.length > 0) {
  14796. return;
  14797. }
  14798. this._animationStartDate = BABYLON.Tools.Now;
  14799. }
  14800. // Getting time
  14801. var now = BABYLON.Tools.Now;
  14802. var delay = now - this._animationStartDate;
  14803. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14804. this._activeAnimatables[index]._animate(delay);
  14805. }
  14806. };
  14807. // Matrix
  14808. Scene.prototype.getViewMatrix = function () {
  14809. return this._viewMatrix;
  14810. };
  14811. Scene.prototype.getProjectionMatrix = function () {
  14812. return this._projectionMatrix;
  14813. };
  14814. Scene.prototype.getTransformMatrix = function () {
  14815. return this._transformMatrix;
  14816. };
  14817. Scene.prototype.setTransformMatrix = function (view, projection) {
  14818. this._viewMatrix = view;
  14819. this._projectionMatrix = projection;
  14820. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14821. };
  14822. // Methods
  14823. Scene.prototype.addMesh = function (newMesh) {
  14824. newMesh.uniqueId = this._uniqueIdCounter++;
  14825. var position = this.meshes.push(newMesh);
  14826. //notify the collision coordinator
  14827. this.collisionCoordinator.onMeshAdded(newMesh);
  14828. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14829. };
  14830. Scene.prototype.removeMesh = function (toRemove) {
  14831. var index = this.meshes.indexOf(toRemove);
  14832. if (index !== -1) {
  14833. // Remove from the scene if mesh found
  14834. this.meshes.splice(index, 1);
  14835. }
  14836. //notify the collision coordinator
  14837. this.collisionCoordinator.onMeshRemoved(toRemove);
  14838. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14839. return index;
  14840. };
  14841. Scene.prototype.removeSkeleton = function (toRemove) {
  14842. var index = this.skeletons.indexOf(toRemove);
  14843. if (index !== -1) {
  14844. // Remove from the scene if mesh found
  14845. this.skeletons.splice(index, 1);
  14846. }
  14847. return index;
  14848. };
  14849. Scene.prototype.removeLight = function (toRemove) {
  14850. var index = this.lights.indexOf(toRemove);
  14851. if (index !== -1) {
  14852. // Remove from the scene if mesh found
  14853. this.lights.splice(index, 1);
  14854. }
  14855. this.onLightRemovedObservable.notifyObservers(toRemove);
  14856. return index;
  14857. };
  14858. Scene.prototype.removeCamera = function (toRemove) {
  14859. var index = this.cameras.indexOf(toRemove);
  14860. if (index !== -1) {
  14861. // Remove from the scene if mesh found
  14862. this.cameras.splice(index, 1);
  14863. }
  14864. // Remove from activeCameras
  14865. var index2 = this.activeCameras.indexOf(toRemove);
  14866. if (index2 !== -1) {
  14867. // Remove from the scene if mesh found
  14868. this.activeCameras.splice(index2, 1);
  14869. }
  14870. // Reset the activeCamera
  14871. if (this.activeCamera === toRemove) {
  14872. if (this.cameras.length > 0) {
  14873. this.activeCamera = this.cameras[0];
  14874. }
  14875. else {
  14876. this.activeCamera = null;
  14877. }
  14878. }
  14879. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14880. return index;
  14881. };
  14882. Scene.prototype.addLight = function (newLight) {
  14883. newLight.uniqueId = this._uniqueIdCounter++;
  14884. var position = this.lights.push(newLight);
  14885. this.onNewLightAddedObservable.notifyObservers(newLight);
  14886. };
  14887. Scene.prototype.addCamera = function (newCamera) {
  14888. newCamera.uniqueId = this._uniqueIdCounter++;
  14889. var position = this.cameras.push(newCamera);
  14890. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  14891. };
  14892. /**
  14893. * Switch active camera
  14894. * @param {Camera} newCamera - new active camera
  14895. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14896. */
  14897. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14898. if (attachControl === void 0) { attachControl = true; }
  14899. var canvas = this._engine.getRenderingCanvas();
  14900. this.activeCamera.detachControl(canvas);
  14901. this.activeCamera = newCamera;
  14902. if (attachControl) {
  14903. newCamera.attachControl(canvas);
  14904. }
  14905. };
  14906. /**
  14907. * sets the active camera of the scene using its ID
  14908. * @param {string} id - the camera's ID
  14909. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14910. * @see activeCamera
  14911. */
  14912. Scene.prototype.setActiveCameraByID = function (id) {
  14913. var camera = this.getCameraByID(id);
  14914. if (camera) {
  14915. this.activeCamera = camera;
  14916. return camera;
  14917. }
  14918. return null;
  14919. };
  14920. /**
  14921. * sets the active camera of the scene using its name
  14922. * @param {string} name - the camera's name
  14923. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14924. * @see activeCamera
  14925. */
  14926. Scene.prototype.setActiveCameraByName = function (name) {
  14927. var camera = this.getCameraByName(name);
  14928. if (camera) {
  14929. this.activeCamera = camera;
  14930. return camera;
  14931. }
  14932. return null;
  14933. };
  14934. /**
  14935. * get a material using its id
  14936. * @param {string} the material's ID
  14937. * @return {BABYLON.Material|null} the material or null if none found.
  14938. */
  14939. Scene.prototype.getMaterialByID = function (id) {
  14940. for (var index = 0; index < this.materials.length; index++) {
  14941. if (this.materials[index].id === id) {
  14942. return this.materials[index];
  14943. }
  14944. }
  14945. return null;
  14946. };
  14947. /**
  14948. * get a material using its name
  14949. * @param {string} the material's name
  14950. * @return {BABYLON.Material|null} the material or null if none found.
  14951. */
  14952. Scene.prototype.getMaterialByName = function (name) {
  14953. for (var index = 0; index < this.materials.length; index++) {
  14954. if (this.materials[index].name === name) {
  14955. return this.materials[index];
  14956. }
  14957. }
  14958. return null;
  14959. };
  14960. Scene.prototype.getLensFlareSystemByName = function (name) {
  14961. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  14962. if (this.lensFlareSystems[index].name === name) {
  14963. return this.lensFlareSystems[index];
  14964. }
  14965. }
  14966. return null;
  14967. };
  14968. Scene.prototype.getCameraByID = function (id) {
  14969. for (var index = 0; index < this.cameras.length; index++) {
  14970. if (this.cameras[index].id === id) {
  14971. return this.cameras[index];
  14972. }
  14973. }
  14974. return null;
  14975. };
  14976. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  14977. for (var index = 0; index < this.cameras.length; index++) {
  14978. if (this.cameras[index].uniqueId === uniqueId) {
  14979. return this.cameras[index];
  14980. }
  14981. }
  14982. return null;
  14983. };
  14984. /**
  14985. * get a camera using its name
  14986. * @param {string} the camera's name
  14987. * @return {BABYLON.Camera|null} the camera or null if none found.
  14988. */
  14989. Scene.prototype.getCameraByName = function (name) {
  14990. for (var index = 0; index < this.cameras.length; index++) {
  14991. if (this.cameras[index].name === name) {
  14992. return this.cameras[index];
  14993. }
  14994. }
  14995. return null;
  14996. };
  14997. /**
  14998. * get a bone using its id
  14999. * @param {string} the bone's id
  15000. * @return {BABYLON.Bone|null} the bone or null if not found
  15001. */
  15002. Scene.prototype.getBoneByID = function (id) {
  15003. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15004. var skeleton = this.skeletons[skeletonIndex];
  15005. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15006. if (skeleton.bones[boneIndex].id === id) {
  15007. return skeleton.bones[boneIndex];
  15008. }
  15009. }
  15010. }
  15011. return null;
  15012. };
  15013. /**
  15014. * get a bone using its id
  15015. * @param {string} the bone's name
  15016. * @return {BABYLON.Bone|null} the bone or null if not found
  15017. */
  15018. Scene.prototype.getBoneByName = function (name) {
  15019. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15020. var skeleton = this.skeletons[skeletonIndex];
  15021. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15022. if (skeleton.bones[boneIndex].name === name) {
  15023. return skeleton.bones[boneIndex];
  15024. }
  15025. }
  15026. }
  15027. return null;
  15028. };
  15029. /**
  15030. * get a light node using its name
  15031. * @param {string} the light's name
  15032. * @return {BABYLON.Light|null} the light or null if none found.
  15033. */
  15034. Scene.prototype.getLightByName = function (name) {
  15035. for (var index = 0; index < this.lights.length; index++) {
  15036. if (this.lights[index].name === name) {
  15037. return this.lights[index];
  15038. }
  15039. }
  15040. return null;
  15041. };
  15042. /**
  15043. * get a light node using its ID
  15044. * @param {string} the light's id
  15045. * @return {BABYLON.Light|null} the light or null if none found.
  15046. */
  15047. Scene.prototype.getLightByID = function (id) {
  15048. for (var index = 0; index < this.lights.length; index++) {
  15049. if (this.lights[index].id === id) {
  15050. return this.lights[index];
  15051. }
  15052. }
  15053. return null;
  15054. };
  15055. /**
  15056. * get a light node using its scene-generated unique ID
  15057. * @param {number} the light's unique id
  15058. * @return {BABYLON.Light|null} the light or null if none found.
  15059. */
  15060. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15061. for (var index = 0; index < this.lights.length; index++) {
  15062. if (this.lights[index].uniqueId === uniqueId) {
  15063. return this.lights[index];
  15064. }
  15065. }
  15066. return null;
  15067. };
  15068. /**
  15069. * get a particle system by id
  15070. * @param id {number} the particle system id
  15071. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15072. */
  15073. Scene.prototype.getParticleSystemByID = function (id) {
  15074. for (var index = 0; index < this.particleSystems.length; index++) {
  15075. if (this.particleSystems[index].id === id) {
  15076. return this.particleSystems[index];
  15077. }
  15078. }
  15079. return null;
  15080. };
  15081. /**
  15082. * get a geometry using its ID
  15083. * @param {string} the geometry's id
  15084. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15085. */
  15086. Scene.prototype.getGeometryByID = function (id) {
  15087. for (var index = 0; index < this._geometries.length; index++) {
  15088. if (this._geometries[index].id === id) {
  15089. return this._geometries[index];
  15090. }
  15091. }
  15092. return null;
  15093. };
  15094. /**
  15095. * add a new geometry to this scene.
  15096. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15097. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15098. * @return {boolean} was the geometry added or not
  15099. */
  15100. Scene.prototype.pushGeometry = function (geometry, force) {
  15101. if (!force && this.getGeometryByID(geometry.id)) {
  15102. return false;
  15103. }
  15104. this._geometries.push(geometry);
  15105. //notify the collision coordinator
  15106. this.collisionCoordinator.onGeometryAdded(geometry);
  15107. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15108. return true;
  15109. };
  15110. /**
  15111. * Removes an existing geometry
  15112. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15113. * @return {boolean} was the geometry removed or not
  15114. */
  15115. Scene.prototype.removeGeometry = function (geometry) {
  15116. var index = this._geometries.indexOf(geometry);
  15117. if (index > -1) {
  15118. this._geometries.splice(index, 1);
  15119. //notify the collision coordinator
  15120. this.collisionCoordinator.onGeometryDeleted(geometry);
  15121. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15122. return true;
  15123. }
  15124. return false;
  15125. };
  15126. Scene.prototype.getGeometries = function () {
  15127. return this._geometries;
  15128. };
  15129. /**
  15130. * Get the first added mesh found of a given ID
  15131. * @param {string} id - the id to search for
  15132. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15133. */
  15134. Scene.prototype.getMeshByID = function (id) {
  15135. for (var index = 0; index < this.meshes.length; index++) {
  15136. if (this.meshes[index].id === id) {
  15137. return this.meshes[index];
  15138. }
  15139. }
  15140. return null;
  15141. };
  15142. /**
  15143. * Get a mesh with its auto-generated unique id
  15144. * @param {number} uniqueId - the unique id to search for
  15145. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15146. */
  15147. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15148. for (var index = 0; index < this.meshes.length; index++) {
  15149. if (this.meshes[index].uniqueId === uniqueId) {
  15150. return this.meshes[index];
  15151. }
  15152. }
  15153. return null;
  15154. };
  15155. /**
  15156. * Get a the last added mesh found of a given ID
  15157. * @param {string} id - the id to search for
  15158. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15159. */
  15160. Scene.prototype.getLastMeshByID = function (id) {
  15161. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15162. if (this.meshes[index].id === id) {
  15163. return this.meshes[index];
  15164. }
  15165. }
  15166. return null;
  15167. };
  15168. /**
  15169. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15170. * @param {string} id - the id to search for
  15171. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15172. */
  15173. Scene.prototype.getLastEntryByID = function (id) {
  15174. var index;
  15175. for (index = this.meshes.length - 1; index >= 0; index--) {
  15176. if (this.meshes[index].id === id) {
  15177. return this.meshes[index];
  15178. }
  15179. }
  15180. for (index = this.cameras.length - 1; index >= 0; index--) {
  15181. if (this.cameras[index].id === id) {
  15182. return this.cameras[index];
  15183. }
  15184. }
  15185. for (index = this.lights.length - 1; index >= 0; index--) {
  15186. if (this.lights[index].id === id) {
  15187. return this.lights[index];
  15188. }
  15189. }
  15190. return null;
  15191. };
  15192. Scene.prototype.getNodeByID = function (id) {
  15193. var mesh = this.getMeshByID(id);
  15194. if (mesh) {
  15195. return mesh;
  15196. }
  15197. var light = this.getLightByID(id);
  15198. if (light) {
  15199. return light;
  15200. }
  15201. var camera = this.getCameraByID(id);
  15202. if (camera) {
  15203. return camera;
  15204. }
  15205. var bone = this.getBoneByID(id);
  15206. return bone;
  15207. };
  15208. Scene.prototype.getNodeByName = function (name) {
  15209. var mesh = this.getMeshByName(name);
  15210. if (mesh) {
  15211. return mesh;
  15212. }
  15213. var light = this.getLightByName(name);
  15214. if (light) {
  15215. return light;
  15216. }
  15217. var camera = this.getCameraByName(name);
  15218. if (camera) {
  15219. return camera;
  15220. }
  15221. var bone = this.getBoneByName(name);
  15222. return bone;
  15223. };
  15224. Scene.prototype.getMeshByName = function (name) {
  15225. for (var index = 0; index < this.meshes.length; index++) {
  15226. if (this.meshes[index].name === name) {
  15227. return this.meshes[index];
  15228. }
  15229. }
  15230. return null;
  15231. };
  15232. Scene.prototype.getSoundByName = function (name) {
  15233. var index;
  15234. if (BABYLON.AudioEngine) {
  15235. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15236. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15237. return this.mainSoundTrack.soundCollection[index];
  15238. }
  15239. }
  15240. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15241. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15242. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15243. return this.soundTracks[sdIndex].soundCollection[index];
  15244. }
  15245. }
  15246. }
  15247. }
  15248. return null;
  15249. };
  15250. Scene.prototype.getLastSkeletonByID = function (id) {
  15251. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15252. if (this.skeletons[index].id === id) {
  15253. return this.skeletons[index];
  15254. }
  15255. }
  15256. return null;
  15257. };
  15258. Scene.prototype.getSkeletonById = function (id) {
  15259. for (var index = 0; index < this.skeletons.length; index++) {
  15260. if (this.skeletons[index].id === id) {
  15261. return this.skeletons[index];
  15262. }
  15263. }
  15264. return null;
  15265. };
  15266. Scene.prototype.getSkeletonByName = function (name) {
  15267. for (var index = 0; index < this.skeletons.length; index++) {
  15268. if (this.skeletons[index].name === name) {
  15269. return this.skeletons[index];
  15270. }
  15271. }
  15272. return null;
  15273. };
  15274. Scene.prototype.isActiveMesh = function (mesh) {
  15275. return (this._activeMeshes.indexOf(mesh) !== -1);
  15276. };
  15277. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15278. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15279. var material = subMesh.getMaterial();
  15280. if (mesh.showSubMeshesBoundingBox) {
  15281. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15282. }
  15283. if (material) {
  15284. // Render targets
  15285. if (material.getRenderTargetTextures) {
  15286. if (this._processedMaterials.indexOf(material) === -1) {
  15287. this._processedMaterials.push(material);
  15288. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15289. }
  15290. }
  15291. // Dispatch
  15292. this._activeIndices += subMesh.indexCount;
  15293. this._renderingManager.dispatch(subMesh);
  15294. }
  15295. }
  15296. };
  15297. Scene.prototype._isInIntermediateRendering = function () {
  15298. return this._intermediateRendering;
  15299. };
  15300. Scene.prototype._evaluateActiveMeshes = function () {
  15301. this.activeCamera._activeMeshes.reset();
  15302. this._activeMeshes.reset();
  15303. this._renderingManager.reset();
  15304. this._processedMaterials.reset();
  15305. this._activeParticleSystems.reset();
  15306. this._activeSkeletons.reset();
  15307. this._softwareSkinnedMeshes.reset();
  15308. this._boundingBoxRenderer.reset();
  15309. this._edgesRenderers.reset();
  15310. if (!this._frustumPlanes) {
  15311. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15312. }
  15313. else {
  15314. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15315. }
  15316. // Meshes
  15317. var meshes;
  15318. var len;
  15319. if (this._selectionOctree) {
  15320. var selection = this._selectionOctree.select(this._frustumPlanes);
  15321. meshes = selection.data;
  15322. len = selection.length;
  15323. }
  15324. else {
  15325. len = this.meshes.length;
  15326. meshes = this.meshes;
  15327. }
  15328. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15329. var mesh = meshes[meshIndex];
  15330. if (mesh.isBlocked) {
  15331. continue;
  15332. }
  15333. this._totalVertices += mesh.getTotalVertices();
  15334. if (!mesh.isReady() || !mesh.isEnabled()) {
  15335. continue;
  15336. }
  15337. mesh.computeWorldMatrix();
  15338. // Intersections
  15339. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15340. this._meshesForIntersections.pushNoDuplicate(mesh);
  15341. }
  15342. // Switch to current LOD
  15343. var meshLOD = mesh.getLOD(this.activeCamera);
  15344. if (!meshLOD) {
  15345. continue;
  15346. }
  15347. mesh._preActivate();
  15348. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15349. this._activeMeshes.push(mesh);
  15350. this.activeCamera._activeMeshes.push(mesh);
  15351. mesh._activate(this._renderId);
  15352. this._activeMesh(meshLOD);
  15353. }
  15354. }
  15355. // Particle systems
  15356. var beforeParticlesDate = BABYLON.Tools.Now;
  15357. if (this.particlesEnabled) {
  15358. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15359. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15360. var particleSystem = this.particleSystems[particleIndex];
  15361. if (!particleSystem.isStarted()) {
  15362. continue;
  15363. }
  15364. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15365. this._activeParticleSystems.push(particleSystem);
  15366. particleSystem.animate();
  15367. }
  15368. }
  15369. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15370. }
  15371. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15372. };
  15373. Scene.prototype._activeMesh = function (mesh) {
  15374. if (mesh.skeleton && this.skeletonsEnabled) {
  15375. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15376. if (!mesh.computeBonesUsingShaders) {
  15377. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15378. }
  15379. }
  15380. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15381. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15382. }
  15383. if (mesh._edgesRenderer) {
  15384. this._edgesRenderers.push(mesh._edgesRenderer);
  15385. }
  15386. if (mesh && mesh.subMeshes) {
  15387. // Submeshes Octrees
  15388. var len;
  15389. var subMeshes;
  15390. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15391. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15392. len = intersections.length;
  15393. subMeshes = intersections.data;
  15394. }
  15395. else {
  15396. subMeshes = mesh.subMeshes;
  15397. len = subMeshes.length;
  15398. }
  15399. for (var subIndex = 0; subIndex < len; subIndex++) {
  15400. var subMesh = subMeshes[subIndex];
  15401. this._evaluateSubMesh(subMesh, mesh);
  15402. }
  15403. }
  15404. };
  15405. Scene.prototype.updateTransformMatrix = function (force) {
  15406. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15407. };
  15408. Scene.prototype._renderForCamera = function (camera) {
  15409. var engine = this._engine;
  15410. this.activeCamera = camera;
  15411. if (!this.activeCamera)
  15412. throw new Error("Active camera not set");
  15413. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15414. // Viewport
  15415. engine.setViewport(this.activeCamera.viewport);
  15416. // Camera
  15417. this.resetCachedMaterial();
  15418. this._renderId++;
  15419. this.updateTransformMatrix();
  15420. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15421. // Meshes
  15422. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15423. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15424. this._evaluateActiveMeshes();
  15425. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15426. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15427. // Skeletons
  15428. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15429. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15430. skeleton.prepare();
  15431. }
  15432. // Software skinning
  15433. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15434. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15435. mesh.applySkeleton(mesh.skeleton);
  15436. }
  15437. // Render targets
  15438. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15439. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15440. this._intermediateRendering = true;
  15441. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15442. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15443. var renderTarget = this._renderTargets.data[renderIndex];
  15444. if (renderTarget._shouldRender()) {
  15445. this._renderId++;
  15446. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15447. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15448. }
  15449. }
  15450. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15451. this._intermediateRendering = false;
  15452. this._renderId++;
  15453. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15454. }
  15455. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15456. // Prepare Frame
  15457. this.postProcessManager._prepareFrame();
  15458. var beforeRenderDate = BABYLON.Tools.Now;
  15459. // Backgrounds
  15460. var layerIndex;
  15461. var layer;
  15462. if (this.layers.length) {
  15463. engine.setDepthBuffer(false);
  15464. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15465. layer = this.layers[layerIndex];
  15466. if (layer.isBackground) {
  15467. layer.render();
  15468. }
  15469. }
  15470. engine.setDepthBuffer(true);
  15471. }
  15472. // Render
  15473. BABYLON.Tools.StartPerformanceCounter("Main render");
  15474. this._renderingManager.render(null, null, true, true);
  15475. BABYLON.Tools.EndPerformanceCounter("Main render");
  15476. // Bounding boxes
  15477. this._boundingBoxRenderer.render();
  15478. // Edges
  15479. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15480. this._edgesRenderers.data[edgesRendererIndex].render();
  15481. }
  15482. // Lens flares
  15483. if (this.lensFlaresEnabled) {
  15484. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15485. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15486. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15487. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15488. lensFlareSystem.render();
  15489. }
  15490. }
  15491. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15492. }
  15493. // Foregrounds
  15494. if (this.layers.length) {
  15495. engine.setDepthBuffer(false);
  15496. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15497. layer = this.layers[layerIndex];
  15498. if (!layer.isBackground) {
  15499. layer.render();
  15500. }
  15501. }
  15502. engine.setDepthBuffer(true);
  15503. }
  15504. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15505. // Finalize frame
  15506. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15507. // Update camera
  15508. this.activeCamera._updateFromScene();
  15509. // Reset some special arrays
  15510. this._renderTargets.reset();
  15511. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15512. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15513. };
  15514. Scene.prototype._processSubCameras = function (camera) {
  15515. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15516. this._renderForCamera(camera);
  15517. return;
  15518. }
  15519. // rig cameras
  15520. for (var index = 0; index < camera._rigCameras.length; index++) {
  15521. this._renderForCamera(camera._rigCameras[index]);
  15522. }
  15523. this.activeCamera = camera;
  15524. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15525. // Update camera
  15526. this.activeCamera._updateFromScene();
  15527. };
  15528. Scene.prototype._checkIntersections = function () {
  15529. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15530. var sourceMesh = this._meshesForIntersections.data[index];
  15531. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15532. var action = sourceMesh.actionManager.actions[actionIndex];
  15533. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15534. var parameters = action.getTriggerParameter();
  15535. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15536. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15537. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15538. if (areIntersecting && currentIntersectionInProgress === -1) {
  15539. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15540. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15541. sourceMesh._intersectionsInProgress.push(otherMesh);
  15542. }
  15543. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15544. sourceMesh._intersectionsInProgress.push(otherMesh);
  15545. }
  15546. }
  15547. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15548. //They intersected, and now they don't.
  15549. //is this trigger an exit trigger? execute an event.
  15550. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15551. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15552. }
  15553. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15554. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15555. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15556. }
  15557. }
  15558. }
  15559. }
  15560. }
  15561. };
  15562. Scene.prototype.render = function () {
  15563. var startDate = BABYLON.Tools.Now;
  15564. this._particlesDuration = 0;
  15565. this._spritesDuration = 0;
  15566. this._activeParticles = 0;
  15567. this._renderDuration = 0;
  15568. this._renderTargetsDuration = 0;
  15569. this._evaluateActiveMeshesDuration = 0;
  15570. this._totalVertices = 0;
  15571. this._activeIndices = 0;
  15572. this._activeBones = 0;
  15573. this.getEngine().resetDrawCalls();
  15574. this._meshesForIntersections.reset();
  15575. this.resetCachedMaterial();
  15576. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15577. // Actions
  15578. if (this.actionManager) {
  15579. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15580. }
  15581. //Simplification Queue
  15582. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15583. this.simplificationQueue.executeNext();
  15584. }
  15585. // Animations
  15586. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15587. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15588. this._animate();
  15589. // Physics
  15590. if (this._physicsEngine) {
  15591. BABYLON.Tools.StartPerformanceCounter("Physics");
  15592. this._physicsEngine._step(deltaTime / 1000.0);
  15593. BABYLON.Tools.EndPerformanceCounter("Physics");
  15594. }
  15595. // Before render
  15596. this.onBeforeRenderObservable.notifyObservers(this);
  15597. // Customs render targets
  15598. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15599. var engine = this.getEngine();
  15600. var currentActiveCamera = this.activeCamera;
  15601. if (this.renderTargetsEnabled) {
  15602. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15603. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15604. var renderTarget = this.customRenderTargets[customIndex];
  15605. if (renderTarget._shouldRender()) {
  15606. this._renderId++;
  15607. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15608. if (!this.activeCamera)
  15609. throw new Error("Active camera not set");
  15610. // Viewport
  15611. engine.setViewport(this.activeCamera.viewport);
  15612. // Camera
  15613. this.updateTransformMatrix();
  15614. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15615. }
  15616. }
  15617. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15618. this._renderId++;
  15619. }
  15620. if (this.customRenderTargets.length > 0) {
  15621. engine.restoreDefaultFramebuffer();
  15622. }
  15623. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15624. this.activeCamera = currentActiveCamera;
  15625. // Procedural textures
  15626. if (this.proceduralTexturesEnabled) {
  15627. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15628. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15629. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15630. if (proceduralTexture._shouldRender()) {
  15631. proceduralTexture.render();
  15632. }
  15633. }
  15634. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15635. }
  15636. // Clear
  15637. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15638. // Shadows
  15639. if (this.shadowsEnabled) {
  15640. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15641. var light = this.lights[lightIndex];
  15642. var shadowGenerator = light.getShadowGenerator();
  15643. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15644. this._renderTargets.push(shadowGenerator.getShadowMap());
  15645. }
  15646. }
  15647. }
  15648. // Depth renderer
  15649. if (this._depthRenderer) {
  15650. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15651. }
  15652. // RenderPipeline
  15653. this.postProcessRenderPipelineManager.update();
  15654. // Multi-cameras?
  15655. if (this.activeCameras.length > 0) {
  15656. var currentRenderId = this._renderId;
  15657. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15658. this._renderId = currentRenderId;
  15659. if (cameraIndex > 0) {
  15660. this._engine.clear(0, false, true);
  15661. }
  15662. this._processSubCameras(this.activeCameras[cameraIndex]);
  15663. }
  15664. }
  15665. else {
  15666. if (!this.activeCamera) {
  15667. throw new Error("No camera defined");
  15668. }
  15669. this._processSubCameras(this.activeCamera);
  15670. }
  15671. // Intersection checks
  15672. this._checkIntersections();
  15673. // Update the audio listener attached to the camera
  15674. if (BABYLON.AudioEngine) {
  15675. this._updateAudioParameters();
  15676. }
  15677. // After render
  15678. if (this.afterRender) {
  15679. this.afterRender();
  15680. }
  15681. this.onAfterRenderObservable.notifyObservers(this);
  15682. // Cleaning
  15683. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15684. this._toBeDisposed.data[index].dispose();
  15685. this._toBeDisposed[index] = null;
  15686. }
  15687. this._toBeDisposed.reset();
  15688. if (this.dumpNextRenderTargets) {
  15689. this.dumpNextRenderTargets = false;
  15690. }
  15691. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15692. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15693. };
  15694. Scene.prototype._updateAudioParameters = function () {
  15695. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15696. return;
  15697. }
  15698. var listeningCamera;
  15699. var audioEngine = BABYLON.Engine.audioEngine;
  15700. if (this.activeCameras.length > 0) {
  15701. listeningCamera = this.activeCameras[0];
  15702. }
  15703. else {
  15704. listeningCamera = this.activeCamera;
  15705. }
  15706. if (listeningCamera && audioEngine.canUseWebAudio) {
  15707. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15708. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15709. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15710. cameraDirection.normalize();
  15711. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15712. var i;
  15713. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15714. var sound = this.mainSoundTrack.soundCollection[i];
  15715. if (sound.useCustomAttenuation) {
  15716. sound.updateDistanceFromListener();
  15717. }
  15718. }
  15719. for (i = 0; i < this.soundTracks.length; i++) {
  15720. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15721. sound = this.soundTracks[i].soundCollection[j];
  15722. if (sound.useCustomAttenuation) {
  15723. sound.updateDistanceFromListener();
  15724. }
  15725. }
  15726. }
  15727. }
  15728. };
  15729. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15730. // Audio
  15731. get: function () {
  15732. return this._audioEnabled;
  15733. },
  15734. set: function (value) {
  15735. this._audioEnabled = value;
  15736. if (BABYLON.AudioEngine) {
  15737. if (this._audioEnabled) {
  15738. this._enableAudio();
  15739. }
  15740. else {
  15741. this._disableAudio();
  15742. }
  15743. }
  15744. },
  15745. enumerable: true,
  15746. configurable: true
  15747. });
  15748. Scene.prototype._disableAudio = function () {
  15749. var i;
  15750. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15751. this.mainSoundTrack.soundCollection[i].pause();
  15752. }
  15753. for (i = 0; i < this.soundTracks.length; i++) {
  15754. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15755. this.soundTracks[i].soundCollection[j].pause();
  15756. }
  15757. }
  15758. };
  15759. Scene.prototype._enableAudio = function () {
  15760. var i;
  15761. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15762. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15763. this.mainSoundTrack.soundCollection[i].play();
  15764. }
  15765. }
  15766. for (i = 0; i < this.soundTracks.length; i++) {
  15767. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15768. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15769. this.soundTracks[i].soundCollection[j].play();
  15770. }
  15771. }
  15772. }
  15773. };
  15774. Object.defineProperty(Scene.prototype, "headphone", {
  15775. get: function () {
  15776. return this._headphone;
  15777. },
  15778. set: function (value) {
  15779. this._headphone = value;
  15780. if (BABYLON.AudioEngine) {
  15781. if (this._headphone) {
  15782. this._switchAudioModeForHeadphones();
  15783. }
  15784. else {
  15785. this._switchAudioModeForNormalSpeakers();
  15786. }
  15787. }
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Scene.prototype._switchAudioModeForHeadphones = function () {
  15793. this.mainSoundTrack.switchPanningModelToHRTF();
  15794. for (var i = 0; i < this.soundTracks.length; i++) {
  15795. this.soundTracks[i].switchPanningModelToHRTF();
  15796. }
  15797. };
  15798. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15799. this.mainSoundTrack.switchPanningModelToEqualPower();
  15800. for (var i = 0; i < this.soundTracks.length; i++) {
  15801. this.soundTracks[i].switchPanningModelToEqualPower();
  15802. }
  15803. };
  15804. Scene.prototype.enableDepthRenderer = function () {
  15805. if (this._depthRenderer) {
  15806. return this._depthRenderer;
  15807. }
  15808. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15809. return this._depthRenderer;
  15810. };
  15811. Scene.prototype.disableDepthRenderer = function () {
  15812. if (!this._depthRenderer) {
  15813. return;
  15814. }
  15815. this._depthRenderer.dispose();
  15816. this._depthRenderer = null;
  15817. };
  15818. Scene.prototype.freezeMaterials = function () {
  15819. for (var i = 0; i < this.materials.length; i++) {
  15820. this.materials[i].freeze();
  15821. }
  15822. };
  15823. Scene.prototype.unfreezeMaterials = function () {
  15824. for (var i = 0; i < this.materials.length; i++) {
  15825. this.materials[i].unfreeze();
  15826. }
  15827. };
  15828. Scene.prototype.dispose = function () {
  15829. this.beforeRender = null;
  15830. this.afterRender = null;
  15831. this.skeletons = [];
  15832. this._boundingBoxRenderer.dispose();
  15833. if (this._depthRenderer) {
  15834. this._depthRenderer.dispose();
  15835. }
  15836. // Debug layer
  15837. this.debugLayer.hide();
  15838. // Events
  15839. if (this.onDispose) {
  15840. this.onDispose();
  15841. }
  15842. this.onBeforeRenderObservable.clear();
  15843. this.onAfterRenderObservable.clear();
  15844. this.detachControl();
  15845. // Release sounds & sounds tracks
  15846. if (BABYLON.AudioEngine) {
  15847. this.disposeSounds();
  15848. }
  15849. // Detach cameras
  15850. var canvas = this._engine.getRenderingCanvas();
  15851. var index;
  15852. for (index = 0; index < this.cameras.length; index++) {
  15853. this.cameras[index].detachControl(canvas);
  15854. }
  15855. // Release lights
  15856. while (this.lights.length) {
  15857. this.lights[0].dispose();
  15858. }
  15859. // Release meshes
  15860. while (this.meshes.length) {
  15861. this.meshes[0].dispose(true);
  15862. }
  15863. // Release cameras
  15864. while (this.cameras.length) {
  15865. this.cameras[0].dispose();
  15866. }
  15867. // Release materials
  15868. while (this.materials.length) {
  15869. this.materials[0].dispose();
  15870. }
  15871. // Release particles
  15872. while (this.particleSystems.length) {
  15873. this.particleSystems[0].dispose();
  15874. }
  15875. // Release sprites
  15876. while (this.spriteManagers.length) {
  15877. this.spriteManagers[0].dispose();
  15878. }
  15879. // Release layers
  15880. while (this.layers.length) {
  15881. this.layers[0].dispose();
  15882. }
  15883. // Release textures
  15884. while (this.textures.length) {
  15885. this.textures[0].dispose();
  15886. }
  15887. // Post-processes
  15888. this.postProcessManager.dispose();
  15889. // Physics
  15890. if (this._physicsEngine) {
  15891. this.disablePhysicsEngine();
  15892. }
  15893. // Remove from engine
  15894. index = this._engine.scenes.indexOf(this);
  15895. if (index > -1) {
  15896. this._engine.scenes.splice(index, 1);
  15897. }
  15898. this._engine.wipeCaches();
  15899. };
  15900. // Release sounds & sounds tracks
  15901. Scene.prototype.disposeSounds = function () {
  15902. this.mainSoundTrack.dispose();
  15903. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15904. this.soundTracks[scIndex].dispose();
  15905. }
  15906. };
  15907. // Octrees
  15908. Scene.prototype.getWorldExtends = function () {
  15909. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15910. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15911. for (var index = 0; index < this.meshes.length; index++) {
  15912. var mesh = this.meshes[index];
  15913. mesh.computeWorldMatrix(true);
  15914. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15915. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15916. BABYLON.Tools.CheckExtends(minBox, min, max);
  15917. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15918. }
  15919. return {
  15920. min: min,
  15921. max: max
  15922. };
  15923. };
  15924. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  15925. if (maxCapacity === void 0) { maxCapacity = 64; }
  15926. if (maxDepth === void 0) { maxDepth = 2; }
  15927. if (!this._selectionOctree) {
  15928. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  15929. }
  15930. var worldExtends = this.getWorldExtends();
  15931. // Update octree
  15932. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  15933. return this._selectionOctree;
  15934. };
  15935. // Picking
  15936. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  15937. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  15938. var engine = this._engine;
  15939. if (!camera) {
  15940. if (!this.activeCamera)
  15941. throw new Error("Active camera not set");
  15942. camera = this.activeCamera;
  15943. }
  15944. var cameraViewport = camera.viewport;
  15945. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15946. // Moving coordinates to local viewport world
  15947. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15948. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15949. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  15950. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  15951. };
  15952. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  15953. var engine = this._engine;
  15954. if (!camera) {
  15955. if (!this.activeCamera)
  15956. throw new Error("Active camera not set");
  15957. camera = this.activeCamera;
  15958. }
  15959. var cameraViewport = camera.viewport;
  15960. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15961. var identity = BABYLON.Matrix.Identity();
  15962. // Moving coordinates to local viewport world
  15963. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  15964. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  15965. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  15966. };
  15967. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  15968. var pickingInfo = null;
  15969. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  15970. var mesh = this.meshes[meshIndex];
  15971. if (predicate) {
  15972. if (!predicate(mesh)) {
  15973. continue;
  15974. }
  15975. }
  15976. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  15977. continue;
  15978. }
  15979. var world = mesh.getWorldMatrix();
  15980. var ray = rayFunction(world);
  15981. var result = mesh.intersects(ray, fastCheck);
  15982. if (!result || !result.hit)
  15983. continue;
  15984. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  15985. continue;
  15986. pickingInfo = result;
  15987. if (fastCheck) {
  15988. break;
  15989. }
  15990. }
  15991. return pickingInfo || new BABYLON.PickingInfo();
  15992. };
  15993. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  15994. var pickingInfo = null;
  15995. camera = camera || this.activeCamera;
  15996. if (this.spriteManagers.length > 0) {
  15997. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  15998. var spriteManager = this.spriteManagers[spriteIndex];
  15999. if (!spriteManager.isPickable) {
  16000. continue;
  16001. }
  16002. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16003. if (!result || !result.hit)
  16004. continue;
  16005. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16006. continue;
  16007. pickingInfo = result;
  16008. if (fastCheck) {
  16009. break;
  16010. }
  16011. }
  16012. }
  16013. return pickingInfo || new BABYLON.PickingInfo();
  16014. };
  16015. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16016. var _this = this;
  16017. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16018. /// <param name="x">X position on screen</param>
  16019. /// <param name="y">Y position on screen</param>
  16020. /// <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>
  16021. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16022. /// <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>
  16023. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16024. };
  16025. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16026. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16027. /// <param name="x">X position on screen</param>
  16028. /// <param name="y">Y position on screen</param>
  16029. /// <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>
  16030. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16031. /// <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>
  16032. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16033. };
  16034. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16035. var _this = this;
  16036. return this._internalPick(function (world) {
  16037. if (!_this._pickWithRayInverseMatrix) {
  16038. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16039. }
  16040. world.invertToRef(_this._pickWithRayInverseMatrix);
  16041. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16042. }, predicate, fastCheck);
  16043. };
  16044. Scene.prototype.setPointerOverMesh = function (mesh) {
  16045. if (this._pointerOverMesh === mesh) {
  16046. return;
  16047. }
  16048. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16049. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16050. }
  16051. this._pointerOverMesh = mesh;
  16052. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16053. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16054. }
  16055. };
  16056. Scene.prototype.getPointerOverMesh = function () {
  16057. return this._pointerOverMesh;
  16058. };
  16059. Scene.prototype.setPointerOverSprite = function (sprite) {
  16060. if (this._pointerOverSprite === sprite) {
  16061. return;
  16062. }
  16063. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16064. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16065. }
  16066. this._pointerOverSprite = sprite;
  16067. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16068. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16069. }
  16070. };
  16071. Scene.prototype.getPointerOverSprite = function () {
  16072. return this._pointerOverSprite;
  16073. };
  16074. // Physics
  16075. Scene.prototype.getPhysicsEngine = function () {
  16076. return this._physicsEngine;
  16077. };
  16078. /**
  16079. * Enables physics to the current scene
  16080. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16081. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16082. * @return {boolean} was the physics engine initialized
  16083. */
  16084. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16085. if (this._physicsEngine) {
  16086. return true;
  16087. }
  16088. try {
  16089. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16090. return true;
  16091. }
  16092. catch (e) {
  16093. BABYLON.Tools.Error(e.message);
  16094. return false;
  16095. }
  16096. };
  16097. Scene.prototype.disablePhysicsEngine = function () {
  16098. if (!this._physicsEngine) {
  16099. return;
  16100. }
  16101. this._physicsEngine.dispose();
  16102. this._physicsEngine = undefined;
  16103. };
  16104. Scene.prototype.isPhysicsEnabled = function () {
  16105. return this._physicsEngine !== undefined;
  16106. };
  16107. /**
  16108. *
  16109. * Sets the gravity of the physics engine (and NOT of the scene)
  16110. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16111. */
  16112. Scene.prototype.setGravity = function (gravity) {
  16113. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16114. if (!this._physicsEngine) {
  16115. return;
  16116. }
  16117. this._physicsEngine.setGravity(gravity);
  16118. };
  16119. /**
  16120. * Legacy support, using the new API
  16121. * @Deprecated
  16122. */
  16123. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16124. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16125. if (parts.parts) {
  16126. options = parts;
  16127. parts = parts.parts;
  16128. }
  16129. var mainMesh = parts[0].mesh;
  16130. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16131. for (var index = 1; index < parts.length; index++) {
  16132. var mesh = parts[index].mesh;
  16133. if (mesh.parent !== mainMesh) {
  16134. mesh.position = mesh.position.subtract(mainMesh.position);
  16135. mesh.parent = mainMesh;
  16136. }
  16137. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16138. }
  16139. mainMesh.physicsImpostor.forceUpdate();
  16140. };
  16141. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16142. var mesh = compound.parts[0].mesh;
  16143. mesh.physicsImpostor.dispose();
  16144. mesh.physicsImpostor = null;
  16145. };
  16146. // Misc.
  16147. Scene.prototype.createDefaultCameraOrLight = function () {
  16148. // Light
  16149. if (this.lights.length === 0) {
  16150. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16151. }
  16152. // Camera
  16153. if (!this.activeCamera) {
  16154. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16155. // Compute position
  16156. var worldExtends = this.getWorldExtends();
  16157. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16158. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16159. camera.setTarget(worldCenter);
  16160. this.activeCamera = camera;
  16161. }
  16162. };
  16163. // Tags
  16164. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16165. if (tagsQuery === undefined) {
  16166. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16167. return list;
  16168. }
  16169. var listByTags = [];
  16170. forEach = forEach || (function (item) { return; });
  16171. for (var i in list) {
  16172. var item = list[i];
  16173. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16174. listByTags.push(item);
  16175. forEach(item);
  16176. }
  16177. }
  16178. return listByTags;
  16179. };
  16180. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16181. return this._getByTags(this.meshes, tagsQuery, forEach);
  16182. };
  16183. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16184. return this._getByTags(this.cameras, tagsQuery, forEach);
  16185. };
  16186. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16187. return this._getByTags(this.lights, tagsQuery, forEach);
  16188. };
  16189. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16190. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16191. };
  16192. // Statics
  16193. Scene._FOGMODE_NONE = 0;
  16194. Scene._FOGMODE_EXP = 1;
  16195. Scene._FOGMODE_EXP2 = 2;
  16196. Scene._FOGMODE_LINEAR = 3;
  16197. Scene.MinDeltaTime = 1.0;
  16198. Scene.MaxDeltaTime = 1000.0;
  16199. return Scene;
  16200. }());
  16201. BABYLON.Scene = Scene;
  16202. })(BABYLON || (BABYLON = {}));
  16203. var BABYLON;
  16204. (function (BABYLON) {
  16205. var VertexBuffer = (function () {
  16206. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16207. if (engine instanceof BABYLON.Mesh) {
  16208. this._engine = engine.getScene().getEngine();
  16209. }
  16210. else {
  16211. this._engine = engine;
  16212. }
  16213. this._updatable = updatable;
  16214. this._data = data;
  16215. if (!postponeInternalCreation) {
  16216. this.create();
  16217. }
  16218. this._kind = kind;
  16219. if (stride) {
  16220. this._strideSize = stride;
  16221. return;
  16222. }
  16223. // Deduce stride from kind
  16224. switch (kind) {
  16225. case VertexBuffer.PositionKind:
  16226. this._strideSize = 3;
  16227. break;
  16228. case VertexBuffer.NormalKind:
  16229. this._strideSize = 3;
  16230. break;
  16231. case VertexBuffer.UVKind:
  16232. case VertexBuffer.UV2Kind:
  16233. case VertexBuffer.UV3Kind:
  16234. case VertexBuffer.UV4Kind:
  16235. case VertexBuffer.UV5Kind:
  16236. case VertexBuffer.UV6Kind:
  16237. this._strideSize = 2;
  16238. break;
  16239. case VertexBuffer.ColorKind:
  16240. this._strideSize = 4;
  16241. break;
  16242. case VertexBuffer.MatricesIndicesKind:
  16243. case VertexBuffer.MatricesIndicesExtraKind:
  16244. this._strideSize = 4;
  16245. break;
  16246. case VertexBuffer.MatricesWeightsKind:
  16247. case VertexBuffer.MatricesWeightsExtraKind:
  16248. this._strideSize = 4;
  16249. break;
  16250. }
  16251. }
  16252. // Properties
  16253. VertexBuffer.prototype.isUpdatable = function () {
  16254. return this._updatable;
  16255. };
  16256. VertexBuffer.prototype.getData = function () {
  16257. return this._data;
  16258. };
  16259. VertexBuffer.prototype.getBuffer = function () {
  16260. return this._buffer;
  16261. };
  16262. VertexBuffer.prototype.getStrideSize = function () {
  16263. return this._strideSize;
  16264. };
  16265. // Methods
  16266. VertexBuffer.prototype.create = function (data) {
  16267. if (!data && this._buffer) {
  16268. return; // nothing to do
  16269. }
  16270. data = data || this._data;
  16271. if (!this._buffer) {
  16272. if (this._updatable) {
  16273. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16274. }
  16275. else {
  16276. this._buffer = this._engine.createVertexBuffer(data);
  16277. }
  16278. }
  16279. if (this._updatable) {
  16280. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16281. this._data = data;
  16282. }
  16283. };
  16284. VertexBuffer.prototype.update = function (data) {
  16285. this.create(data);
  16286. };
  16287. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16288. if (!this._buffer) {
  16289. return;
  16290. }
  16291. if (this._updatable) {
  16292. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16293. this._data = null;
  16294. }
  16295. };
  16296. VertexBuffer.prototype.dispose = function () {
  16297. if (!this._buffer) {
  16298. return;
  16299. }
  16300. if (this._engine._releaseBuffer(this._buffer)) {
  16301. this._buffer = null;
  16302. }
  16303. };
  16304. Object.defineProperty(VertexBuffer, "PositionKind", {
  16305. get: function () {
  16306. return VertexBuffer._PositionKind;
  16307. },
  16308. enumerable: true,
  16309. configurable: true
  16310. });
  16311. Object.defineProperty(VertexBuffer, "NormalKind", {
  16312. get: function () {
  16313. return VertexBuffer._NormalKind;
  16314. },
  16315. enumerable: true,
  16316. configurable: true
  16317. });
  16318. Object.defineProperty(VertexBuffer, "UVKind", {
  16319. get: function () {
  16320. return VertexBuffer._UVKind;
  16321. },
  16322. enumerable: true,
  16323. configurable: true
  16324. });
  16325. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16326. get: function () {
  16327. return VertexBuffer._UV2Kind;
  16328. },
  16329. enumerable: true,
  16330. configurable: true
  16331. });
  16332. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16333. get: function () {
  16334. return VertexBuffer._UV3Kind;
  16335. },
  16336. enumerable: true,
  16337. configurable: true
  16338. });
  16339. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16340. get: function () {
  16341. return VertexBuffer._UV4Kind;
  16342. },
  16343. enumerable: true,
  16344. configurable: true
  16345. });
  16346. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16347. get: function () {
  16348. return VertexBuffer._UV5Kind;
  16349. },
  16350. enumerable: true,
  16351. configurable: true
  16352. });
  16353. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16354. get: function () {
  16355. return VertexBuffer._UV6Kind;
  16356. },
  16357. enumerable: true,
  16358. configurable: true
  16359. });
  16360. Object.defineProperty(VertexBuffer, "ColorKind", {
  16361. get: function () {
  16362. return VertexBuffer._ColorKind;
  16363. },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16368. get: function () {
  16369. return VertexBuffer._MatricesIndicesKind;
  16370. },
  16371. enumerable: true,
  16372. configurable: true
  16373. });
  16374. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16375. get: function () {
  16376. return VertexBuffer._MatricesWeightsKind;
  16377. },
  16378. enumerable: true,
  16379. configurable: true
  16380. });
  16381. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16382. get: function () {
  16383. return VertexBuffer._MatricesIndicesExtraKind;
  16384. },
  16385. enumerable: true,
  16386. configurable: true
  16387. });
  16388. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16389. get: function () {
  16390. return VertexBuffer._MatricesWeightsExtraKind;
  16391. },
  16392. enumerable: true,
  16393. configurable: true
  16394. });
  16395. // Enums
  16396. VertexBuffer._PositionKind = "position";
  16397. VertexBuffer._NormalKind = "normal";
  16398. VertexBuffer._UVKind = "uv";
  16399. VertexBuffer._UV2Kind = "uv2";
  16400. VertexBuffer._UV3Kind = "uv3";
  16401. VertexBuffer._UV4Kind = "uv4";
  16402. VertexBuffer._UV5Kind = "uv5";
  16403. VertexBuffer._UV6Kind = "uv6";
  16404. VertexBuffer._ColorKind = "color";
  16405. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16406. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16407. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16408. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16409. return VertexBuffer;
  16410. }());
  16411. BABYLON.VertexBuffer = VertexBuffer;
  16412. })(BABYLON || (BABYLON = {}));
  16413. var BABYLON;
  16414. (function (BABYLON) {
  16415. /**
  16416. * Creates an instance based on a source mesh.
  16417. */
  16418. var InstancedMesh = (function (_super) {
  16419. __extends(InstancedMesh, _super);
  16420. function InstancedMesh(name, source) {
  16421. _super.call(this, name, source.getScene());
  16422. source.instances.push(this);
  16423. this._sourceMesh = source;
  16424. this.position.copyFrom(source.position);
  16425. this.rotation.copyFrom(source.rotation);
  16426. this.scaling.copyFrom(source.scaling);
  16427. if (source.rotationQuaternion) {
  16428. this.rotationQuaternion = source.rotationQuaternion.clone();
  16429. }
  16430. this.infiniteDistance = source.infiniteDistance;
  16431. this.setPivotMatrix(source.getPivotMatrix());
  16432. this.refreshBoundingInfo();
  16433. this._syncSubMeshes();
  16434. }
  16435. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16436. // Methods
  16437. get: function () {
  16438. return this._sourceMesh.receiveShadows;
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(InstancedMesh.prototype, "material", {
  16444. get: function () {
  16445. return this._sourceMesh.material;
  16446. },
  16447. enumerable: true,
  16448. configurable: true
  16449. });
  16450. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16451. get: function () {
  16452. return this._sourceMesh.visibility;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16458. get: function () {
  16459. return this._sourceMesh.skeleton;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16465. get: function () {
  16466. return this._sourceMesh.renderingGroupId;
  16467. },
  16468. enumerable: true,
  16469. configurable: true
  16470. });
  16471. InstancedMesh.prototype.getTotalVertices = function () {
  16472. return this._sourceMesh.getTotalVertices();
  16473. };
  16474. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16475. get: function () {
  16476. return this._sourceMesh;
  16477. },
  16478. enumerable: true,
  16479. configurable: true
  16480. });
  16481. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16482. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16483. };
  16484. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16485. return this._sourceMesh.isVerticesDataPresent(kind);
  16486. };
  16487. InstancedMesh.prototype.getIndices = function () {
  16488. return this._sourceMesh.getIndices();
  16489. };
  16490. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16491. get: function () {
  16492. return this._sourceMesh._positions;
  16493. },
  16494. enumerable: true,
  16495. configurable: true
  16496. });
  16497. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16498. var meshBB = this._sourceMesh.getBoundingInfo();
  16499. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16500. this._updateBoundingInfo();
  16501. };
  16502. InstancedMesh.prototype._preActivate = function () {
  16503. if (this._currentLOD) {
  16504. this._currentLOD._preActivate();
  16505. }
  16506. };
  16507. InstancedMesh.prototype._activate = function (renderId) {
  16508. if (this._currentLOD) {
  16509. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16510. }
  16511. };
  16512. InstancedMesh.prototype.getLOD = function (camera) {
  16513. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16514. if (this._currentLOD === this.sourceMesh) {
  16515. return this;
  16516. }
  16517. return this._currentLOD;
  16518. };
  16519. InstancedMesh.prototype._syncSubMeshes = function () {
  16520. this.releaseSubMeshes();
  16521. if (this._sourceMesh.subMeshes) {
  16522. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16523. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16524. }
  16525. }
  16526. };
  16527. InstancedMesh.prototype._generatePointsArray = function () {
  16528. return this._sourceMesh._generatePointsArray();
  16529. };
  16530. // Clone
  16531. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16532. var result = this._sourceMesh.createInstance(name);
  16533. // Deep copy
  16534. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16535. // Bounding info
  16536. this.refreshBoundingInfo();
  16537. // Parent
  16538. if (newParent) {
  16539. result.parent = newParent;
  16540. }
  16541. if (!doNotCloneChildren) {
  16542. // Children
  16543. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16544. var mesh = this.getScene().meshes[index];
  16545. if (mesh.parent === this) {
  16546. mesh.clone(mesh.name, result);
  16547. }
  16548. }
  16549. }
  16550. result.computeWorldMatrix(true);
  16551. return result;
  16552. };
  16553. // Dispoe
  16554. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16555. // Remove from mesh
  16556. var index = this._sourceMesh.instances.indexOf(this);
  16557. this._sourceMesh.instances.splice(index, 1);
  16558. _super.prototype.dispose.call(this, doNotRecurse);
  16559. };
  16560. return InstancedMesh;
  16561. }(BABYLON.AbstractMesh));
  16562. BABYLON.InstancedMesh = InstancedMesh;
  16563. })(BABYLON || (BABYLON = {}));
  16564. var BABYLON;
  16565. (function (BABYLON) {
  16566. var _InstancesBatch = (function () {
  16567. function _InstancesBatch() {
  16568. this.mustReturn = false;
  16569. this.visibleInstances = new Array();
  16570. this.renderSelf = new Array();
  16571. }
  16572. return _InstancesBatch;
  16573. }());
  16574. BABYLON._InstancesBatch = _InstancesBatch;
  16575. var Mesh = (function (_super) {
  16576. __extends(Mesh, _super);
  16577. /**
  16578. * @constructor
  16579. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16580. * @param {Scene} scene - The scene to add this mesh to.
  16581. * @param {Node} parent - The parent of this mesh, if it has one
  16582. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16583. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16584. * When false, achieved by calling a clone(), also passing False.
  16585. * This will make creation of children, recursive.
  16586. */
  16587. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16588. if (parent === void 0) { parent = null; }
  16589. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16590. _super.call(this, name, scene);
  16591. // Events
  16592. /**
  16593. * An event triggered before rendering the mesh
  16594. * @type {BABYLON.Observable}
  16595. */
  16596. this.onBeforeRenderObservable = new BABYLON.Observable();
  16597. /**
  16598. * An event triggered after rendering the mesh
  16599. * @type {BABYLON.Observable}
  16600. */
  16601. this.onAfterRenderObservable = new BABYLON.Observable();
  16602. /**
  16603. * An event triggered before drawing the mesh
  16604. * @type {BABYLON.Observable}
  16605. */
  16606. this.onBeforeDrawObservable = new BABYLON.Observable();
  16607. // Members
  16608. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16609. this.instances = new Array();
  16610. this._LODLevels = new Array();
  16611. this._visibleInstances = {};
  16612. this._renderIdForInstances = new Array();
  16613. this._batchCache = new _InstancesBatch();
  16614. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16615. this._sideOrientation = Mesh._DEFAULTSIDE;
  16616. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16617. if (source) {
  16618. // Geometry
  16619. if (source._geometry) {
  16620. source._geometry.applyToMesh(this);
  16621. }
  16622. // Deep copy
  16623. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16624. // Pivot
  16625. this.setPivotMatrix(source.getPivotMatrix());
  16626. this.id = name + "." + source.id;
  16627. // Material
  16628. this.material = source.material;
  16629. var index;
  16630. if (!doNotCloneChildren) {
  16631. // Children
  16632. for (index = 0; index < scene.meshes.length; index++) {
  16633. var mesh = scene.meshes[index];
  16634. if (mesh.parent === source) {
  16635. // doNotCloneChildren is always going to be False
  16636. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16637. }
  16638. }
  16639. }
  16640. // Physics clone
  16641. var physicsEngine = this.getScene().getPhysicsEngine();
  16642. if (clonePhysicsImpostor && physicsEngine) {
  16643. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16644. if (impostor) {
  16645. this.physicsImpostor = impostor.clone(this);
  16646. }
  16647. }
  16648. // Particles
  16649. for (index = 0; index < scene.particleSystems.length; index++) {
  16650. var system = scene.particleSystems[index];
  16651. if (system.emitter === source) {
  16652. system.clone(system.name, this);
  16653. }
  16654. }
  16655. this.computeWorldMatrix(true);
  16656. }
  16657. // Parent
  16658. if (parent !== null) {
  16659. this.parent = parent;
  16660. }
  16661. }
  16662. Object.defineProperty(Mesh, "FRONTSIDE", {
  16663. /**
  16664. * Mesh side orientation : usually the external or front surface
  16665. */
  16666. get: function () {
  16667. return Mesh._FRONTSIDE;
  16668. },
  16669. enumerable: true,
  16670. configurable: true
  16671. });
  16672. Object.defineProperty(Mesh, "BACKSIDE", {
  16673. /**
  16674. * Mesh side orientation : usually the internal or back surface
  16675. */
  16676. get: function () {
  16677. return Mesh._BACKSIDE;
  16678. },
  16679. enumerable: true,
  16680. configurable: true
  16681. });
  16682. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16683. /**
  16684. * Mesh side orientation : both internal and external or front and back surfaces
  16685. */
  16686. get: function () {
  16687. return Mesh._DOUBLESIDE;
  16688. },
  16689. enumerable: true,
  16690. configurable: true
  16691. });
  16692. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16693. /**
  16694. * Mesh side orientation : by default, `FRONTSIDE`
  16695. */
  16696. get: function () {
  16697. return Mesh._DEFAULTSIDE;
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. Object.defineProperty(Mesh, "NO_CAP", {
  16703. /**
  16704. * Mesh cap setting : no cap
  16705. */
  16706. get: function () {
  16707. return Mesh._NO_CAP;
  16708. },
  16709. enumerable: true,
  16710. configurable: true
  16711. });
  16712. Object.defineProperty(Mesh, "CAP_START", {
  16713. /**
  16714. * Mesh cap setting : one cap at the beginning of the mesh
  16715. */
  16716. get: function () {
  16717. return Mesh._CAP_START;
  16718. },
  16719. enumerable: true,
  16720. configurable: true
  16721. });
  16722. Object.defineProperty(Mesh, "CAP_END", {
  16723. /**
  16724. * Mesh cap setting : one cap at the end of the mesh
  16725. */
  16726. get: function () {
  16727. return Mesh._CAP_END;
  16728. },
  16729. enumerable: true,
  16730. configurable: true
  16731. });
  16732. Object.defineProperty(Mesh, "CAP_ALL", {
  16733. /**
  16734. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16735. */
  16736. get: function () {
  16737. return Mesh._CAP_ALL;
  16738. },
  16739. enumerable: true,
  16740. configurable: true
  16741. });
  16742. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16743. set: function (callback) {
  16744. if (this._onBeforeDrawObserver) {
  16745. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16746. }
  16747. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. // Methods
  16753. /**
  16754. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16755. */
  16756. Mesh.prototype.toString = function (fullDetails) {
  16757. var ret = _super.prototype.toString.call(this, fullDetails);
  16758. ret += ", n vertices: " + this.getTotalVertices();
  16759. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16760. if (this.animations) {
  16761. for (var i = 0; i < this.animations.length; i++) {
  16762. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16763. }
  16764. }
  16765. if (fullDetails) {
  16766. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16767. }
  16768. return ret;
  16769. };
  16770. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16771. get: function () {
  16772. return this._LODLevels.length > 0;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Mesh.prototype._sortLODLevels = function () {
  16778. this._LODLevels.sort(function (a, b) {
  16779. if (a.distance < b.distance) {
  16780. return 1;
  16781. }
  16782. if (a.distance > b.distance) {
  16783. return -1;
  16784. }
  16785. return 0;
  16786. });
  16787. };
  16788. /**
  16789. * Add a mesh as LOD level triggered at the given distance.
  16790. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16791. * @param {number} distance - the distance from the center of the object to show this level
  16792. * @param {Mesh} mesh - the mesh to be added as LOD level
  16793. * @return {Mesh} this mesh (for chaining)
  16794. */
  16795. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16796. if (mesh && mesh._masterMesh) {
  16797. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16798. return this;
  16799. }
  16800. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16801. this._LODLevels.push(level);
  16802. if (mesh) {
  16803. mesh._masterMesh = this;
  16804. }
  16805. this._sortLODLevels();
  16806. return this;
  16807. };
  16808. /**
  16809. * Returns the LOD level mesh at the passed distance or null if not found.
  16810. * It is related to the method `addLODLevel(distance, mesh)`.
  16811. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16812. */
  16813. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16814. for (var index = 0; index < this._LODLevels.length; index++) {
  16815. var level = this._LODLevels[index];
  16816. if (level.distance === distance) {
  16817. return level.mesh;
  16818. }
  16819. }
  16820. return null;
  16821. };
  16822. /**
  16823. * Remove a mesh from the LOD array
  16824. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16825. * @param {Mesh} mesh - the mesh to be removed.
  16826. * @return {Mesh} this mesh (for chaining)
  16827. */
  16828. Mesh.prototype.removeLODLevel = function (mesh) {
  16829. for (var index = 0; index < this._LODLevels.length; index++) {
  16830. if (this._LODLevels[index].mesh === mesh) {
  16831. this._LODLevels.splice(index, 1);
  16832. if (mesh) {
  16833. mesh._masterMesh = null;
  16834. }
  16835. }
  16836. }
  16837. this._sortLODLevels();
  16838. return this;
  16839. };
  16840. /**
  16841. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  16842. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16843. */
  16844. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16845. if (!this._LODLevels || this._LODLevels.length === 0) {
  16846. return this;
  16847. }
  16848. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16849. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16850. if (this.onLODLevelSelection) {
  16851. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16852. }
  16853. return this;
  16854. }
  16855. for (var index = 0; index < this._LODLevels.length; index++) {
  16856. var level = this._LODLevels[index];
  16857. if (level.distance < distanceToCamera) {
  16858. if (level.mesh) {
  16859. level.mesh._preActivate();
  16860. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16861. }
  16862. if (this.onLODLevelSelection) {
  16863. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16864. }
  16865. return level.mesh;
  16866. }
  16867. }
  16868. if (this.onLODLevelSelection) {
  16869. this.onLODLevelSelection(distanceToCamera, this, this);
  16870. }
  16871. return this;
  16872. };
  16873. Object.defineProperty(Mesh.prototype, "geometry", {
  16874. /**
  16875. * Returns the mesh internal `Geometry` object.
  16876. */
  16877. get: function () {
  16878. return this._geometry;
  16879. },
  16880. enumerable: true,
  16881. configurable: true
  16882. });
  16883. /**
  16884. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  16885. */
  16886. Mesh.prototype.getTotalVertices = function () {
  16887. if (!this._geometry) {
  16888. return 0;
  16889. }
  16890. return this._geometry.getTotalVertices();
  16891. };
  16892. /**
  16893. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  16894. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  16895. * Returns null if the mesh has no geometry or no vertex buffer.
  16896. * Possible `kind` values :
  16897. * - BABYLON.VertexBuffer.PositionKind
  16898. * - BABYLON.VertexBuffer.UVKind
  16899. * - BABYLON.VertexBuffer.UV2Kind
  16900. * - BABYLON.VertexBuffer.UV3Kind
  16901. * - BABYLON.VertexBuffer.UV4Kind
  16902. * - BABYLON.VertexBuffer.UV5Kind
  16903. * - BABYLON.VertexBuffer.UV6Kind
  16904. * - BABYLON.VertexBuffer.ColorKind
  16905. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16906. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16907. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16908. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16909. */
  16910. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16911. if (!this._geometry) {
  16912. return null;
  16913. }
  16914. return this._geometry.getVerticesData(kind, copyWhenShared);
  16915. };
  16916. /**
  16917. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  16918. * Returns `undefined` if the mesh has no geometry.
  16919. * Possible `kind` values :
  16920. * - BABYLON.VertexBuffer.PositionKind
  16921. * - BABYLON.VertexBuffer.UVKind
  16922. * - BABYLON.VertexBuffer.UV2Kind
  16923. * - BABYLON.VertexBuffer.UV3Kind
  16924. * - BABYLON.VertexBuffer.UV4Kind
  16925. * - BABYLON.VertexBuffer.UV5Kind
  16926. * - BABYLON.VertexBuffer.UV6Kind
  16927. * - BABYLON.VertexBuffer.ColorKind
  16928. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16929. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16930. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16931. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16932. */
  16933. Mesh.prototype.getVertexBuffer = function (kind) {
  16934. if (!this._geometry) {
  16935. return undefined;
  16936. }
  16937. return this._geometry.getVertexBuffer(kind);
  16938. };
  16939. /**
  16940. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  16941. * Possible `kind` values :
  16942. * - BABYLON.VertexBuffer.PositionKind
  16943. * - BABYLON.VertexBuffer.UVKind
  16944. * - BABYLON.VertexBuffer.UV2Kind
  16945. * - BABYLON.VertexBuffer.UV3Kind
  16946. * - BABYLON.VertexBuffer.UV4Kind
  16947. * - BABYLON.VertexBuffer.UV5Kind
  16948. * - BABYLON.VertexBuffer.UV6Kind
  16949. * - BABYLON.VertexBuffer.ColorKind
  16950. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16951. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16952. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16953. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16954. */
  16955. Mesh.prototype.isVerticesDataPresent = function (kind) {
  16956. if (!this._geometry) {
  16957. if (this._delayInfo) {
  16958. return this._delayInfo.indexOf(kind) !== -1;
  16959. }
  16960. return false;
  16961. }
  16962. return this._geometry.isVerticesDataPresent(kind);
  16963. };
  16964. /**
  16965. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  16966. * Possible `kind` values :
  16967. * - BABYLON.VertexBuffer.PositionKind
  16968. * - BABYLON.VertexBuffer.UVKind
  16969. * - BABYLON.VertexBuffer.UV2Kind
  16970. * - BABYLON.VertexBuffer.UV3Kind
  16971. * - BABYLON.VertexBuffer.UV4Kind
  16972. * - BABYLON.VertexBuffer.UV5Kind
  16973. * - BABYLON.VertexBuffer.UV6Kind
  16974. * - BABYLON.VertexBuffer.ColorKind
  16975. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16976. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16977. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16978. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16979. */
  16980. Mesh.prototype.getVerticesDataKinds = function () {
  16981. if (!this._geometry) {
  16982. var result = [];
  16983. if (this._delayInfo) {
  16984. for (var kind in this._delayInfo) {
  16985. result.push(kind);
  16986. }
  16987. }
  16988. return result;
  16989. }
  16990. return this._geometry.getVerticesDataKinds();
  16991. };
  16992. /**
  16993. * Returns a positive integer : the total number of indices in this mesh geometry.
  16994. * Returns zero if the mesh has no geometry.
  16995. */
  16996. Mesh.prototype.getTotalIndices = function () {
  16997. if (!this._geometry) {
  16998. return 0;
  16999. }
  17000. return this._geometry.getTotalIndices();
  17001. };
  17002. /**
  17003. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17004. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  17005. * Returns an empty array if the mesh has no geometry.
  17006. */
  17007. Mesh.prototype.getIndices = function (copyWhenShared) {
  17008. if (!this._geometry) {
  17009. return [];
  17010. }
  17011. return this._geometry.getIndices(copyWhenShared);
  17012. };
  17013. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17014. get: function () {
  17015. return this._masterMesh !== null && this._masterMesh !== undefined;
  17016. },
  17017. enumerable: true,
  17018. configurable: true
  17019. });
  17020. /**
  17021. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17022. */
  17023. Mesh.prototype.isReady = function () {
  17024. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17025. return false;
  17026. }
  17027. return _super.prototype.isReady.call(this);
  17028. };
  17029. /**
  17030. * Boolean : true if the mesh has been disposed.
  17031. */
  17032. Mesh.prototype.isDisposed = function () {
  17033. return this._isDisposed;
  17034. };
  17035. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17036. get: function () {
  17037. return this._sideOrientation;
  17038. },
  17039. /**
  17040. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17041. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17042. */
  17043. set: function (sideO) {
  17044. this._sideOrientation = sideO;
  17045. },
  17046. enumerable: true,
  17047. configurable: true
  17048. });
  17049. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17050. /**
  17051. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17052. * This property is pertinent only for updatable parametric shapes.
  17053. */
  17054. get: function () {
  17055. return this._areNormalsFrozen;
  17056. },
  17057. enumerable: true,
  17058. configurable: true
  17059. });
  17060. /**
  17061. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17062. * It has no effect at all on other shapes.
  17063. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17064. */
  17065. Mesh.prototype.freezeNormals = function () {
  17066. this._areNormalsFrozen = true;
  17067. };
  17068. /**
  17069. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17070. * It has no effect at all on other shapes.
  17071. * It reactivates the mesh normals computation if it was previously frozen.
  17072. */
  17073. Mesh.prototype.unfreezeNormals = function () {
  17074. this._areNormalsFrozen = false;
  17075. };
  17076. // Methods
  17077. Mesh.prototype._preActivate = function () {
  17078. var sceneRenderId = this.getScene().getRenderId();
  17079. if (this._preActivateId === sceneRenderId) {
  17080. return;
  17081. }
  17082. this._preActivateId = sceneRenderId;
  17083. this._visibleInstances = null;
  17084. };
  17085. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17086. if (this._visibleInstances) {
  17087. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17088. }
  17089. };
  17090. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17091. if (!this._visibleInstances) {
  17092. this._visibleInstances = {};
  17093. this._visibleInstances.defaultRenderId = renderId;
  17094. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17095. }
  17096. if (!this._visibleInstances[renderId]) {
  17097. this._visibleInstances[renderId] = new Array();
  17098. }
  17099. this._visibleInstances[renderId].push(instance);
  17100. };
  17101. /**
  17102. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17103. * This means the mesh underlying bounding box and shpere are recomputed.
  17104. */
  17105. Mesh.prototype.refreshBoundingInfo = function () {
  17106. if (this._boundingInfo.isLocked) {
  17107. return;
  17108. }
  17109. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17110. if (data) {
  17111. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17112. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17113. }
  17114. if (this.subMeshes) {
  17115. for (var index = 0; index < this.subMeshes.length; index++) {
  17116. this.subMeshes[index].refreshBoundingInfo();
  17117. }
  17118. }
  17119. this._updateBoundingInfo();
  17120. };
  17121. Mesh.prototype._createGlobalSubMesh = function () {
  17122. var totalVertices = this.getTotalVertices();
  17123. if (!totalVertices || !this.getIndices()) {
  17124. return null;
  17125. }
  17126. this.releaseSubMeshes();
  17127. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17128. };
  17129. Mesh.prototype.subdivide = function (count) {
  17130. if (count < 1) {
  17131. return;
  17132. }
  17133. var totalIndices = this.getTotalIndices();
  17134. var subdivisionSize = (totalIndices / count) | 0;
  17135. var offset = 0;
  17136. // Ensure that subdivisionSize is a multiple of 3
  17137. while (subdivisionSize % 3 !== 0) {
  17138. subdivisionSize++;
  17139. }
  17140. this.releaseSubMeshes();
  17141. for (var index = 0; index < count; index++) {
  17142. if (offset >= totalIndices) {
  17143. break;
  17144. }
  17145. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17146. offset += subdivisionSize;
  17147. }
  17148. this.synchronizeInstances();
  17149. };
  17150. /**
  17151. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17152. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17153. * The `data` are either a numeric array either a Float32Array.
  17154. * 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).
  17155. * Note that a new underlying `VertexBuffer` object is created each call.
  17156. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17157. * The same for the mesh submeshes if any.
  17158. *
  17159. * Possible `kind` values :
  17160. * - BABYLON.VertexBuffer.PositionKind
  17161. * - BABYLON.VertexBuffer.UVKind
  17162. * - BABYLON.VertexBuffer.UV2Kind
  17163. * - BABYLON.VertexBuffer.UV3Kind
  17164. * - BABYLON.VertexBuffer.UV4Kind
  17165. * - BABYLON.VertexBuffer.UV5Kind
  17166. * - BABYLON.VertexBuffer.UV6Kind
  17167. * - BABYLON.VertexBuffer.ColorKind
  17168. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17169. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17170. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17171. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17172. */
  17173. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17174. if (!this._geometry) {
  17175. var vertexData = new BABYLON.VertexData();
  17176. vertexData.set(data, kind);
  17177. var scene = this.getScene();
  17178. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17179. }
  17180. else {
  17181. this._geometry.setVerticesData(kind, data, updatable, stride);
  17182. }
  17183. };
  17184. /**
  17185. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17186. * If the mesh has no geometry, it is simply returned as it is.
  17187. * The `data` are either a numeric array either a Float32Array.
  17188. * No new underlying `VertexBuffer` object is created.
  17189. * 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.
  17190. * The same for the mesh submeshes if any.
  17191. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17192. *
  17193. * Possible `kind` values :
  17194. * - BABYLON.VertexBuffer.PositionKind
  17195. * - BABYLON.VertexBuffer.UVKind
  17196. * - BABYLON.VertexBuffer.UV2Kind
  17197. * - BABYLON.VertexBuffer.UV3Kind
  17198. * - BABYLON.VertexBuffer.UV4Kind
  17199. * - BABYLON.VertexBuffer.UV5Kind
  17200. * - BABYLON.VertexBuffer.UV6Kind
  17201. * - BABYLON.VertexBuffer.ColorKind
  17202. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17203. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17204. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17205. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17206. */
  17207. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17208. if (!this._geometry) {
  17209. return;
  17210. }
  17211. if (!makeItUnique) {
  17212. this._geometry.updateVerticesData(kind, data, updateExtends);
  17213. }
  17214. else {
  17215. this.makeGeometryUnique();
  17216. this.updateVerticesData(kind, data, updateExtends, false);
  17217. }
  17218. };
  17219. /**
  17220. * Deprecated since BabylonJS v2.3
  17221. */
  17222. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17223. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17224. if (!this._geometry) {
  17225. return;
  17226. }
  17227. if (!makeItUnique) {
  17228. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17229. }
  17230. else {
  17231. this.makeGeometryUnique();
  17232. this.updateVerticesDataDirectly(kind, data, offset, false);
  17233. }
  17234. };
  17235. /**
  17236. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17237. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17238. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17239. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17240. */
  17241. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17242. if (computeNormals === void 0) { computeNormals = true; }
  17243. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17244. positionFunction(positions);
  17245. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17246. if (computeNormals) {
  17247. var indices = this.getIndices();
  17248. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17249. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17250. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17251. }
  17252. };
  17253. Mesh.prototype.makeGeometryUnique = function () {
  17254. if (!this._geometry) {
  17255. return;
  17256. }
  17257. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17258. geometry.applyToMesh(this);
  17259. };
  17260. /**
  17261. * Sets the mesh indices.
  17262. * Expects an array populated with integers or a Int32Array.
  17263. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17264. * This method creates a new index buffer each call.
  17265. */
  17266. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17267. if (!this._geometry) {
  17268. var vertexData = new BABYLON.VertexData();
  17269. vertexData.indices = indices;
  17270. var scene = this.getScene();
  17271. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17272. }
  17273. else {
  17274. this._geometry.setIndices(indices, totalVertices);
  17275. }
  17276. };
  17277. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17278. var engine = this.getScene().getEngine();
  17279. // Wireframe
  17280. var indexToBind;
  17281. if (this._unIndexed) {
  17282. indexToBind = null;
  17283. }
  17284. else {
  17285. switch (fillMode) {
  17286. case BABYLON.Material.PointFillMode:
  17287. indexToBind = null;
  17288. break;
  17289. case BABYLON.Material.WireFrameFillMode:
  17290. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17291. break;
  17292. default:
  17293. case BABYLON.Material.TriangleFillMode:
  17294. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17295. break;
  17296. }
  17297. }
  17298. // VBOs
  17299. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17300. };
  17301. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17302. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17303. return;
  17304. }
  17305. this.onBeforeDrawObservable.notifyObservers(this);
  17306. var engine = this.getScene().getEngine();
  17307. // Draw order
  17308. switch (fillMode) {
  17309. case BABYLON.Material.PointFillMode:
  17310. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17311. break;
  17312. case BABYLON.Material.WireFrameFillMode:
  17313. if (this._unIndexed) {
  17314. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17315. }
  17316. else {
  17317. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17318. }
  17319. break;
  17320. default:
  17321. if (this._unIndexed) {
  17322. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17323. }
  17324. else {
  17325. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17326. }
  17327. }
  17328. };
  17329. /**
  17330. * Registers a javascript function for this mesh that will be called just before the rendering process.
  17331. * This function is passed the current mesh and doesn't return anything.
  17332. */
  17333. Mesh.prototype.registerBeforeRender = function (func) {
  17334. this.onBeforeRenderObservable.add(func);
  17335. };
  17336. /**
  17337. * Disposes a previously registered javascript function called before the rendering.
  17338. * This function is passed the current mesh and doesn't return anything.
  17339. */
  17340. Mesh.prototype.unregisterBeforeRender = function (func) {
  17341. this.onBeforeRenderObservable.removeCallback(func);
  17342. };
  17343. /**
  17344. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  17345. * This function is passed the current mesh and doesn't return anything.
  17346. */
  17347. Mesh.prototype.registerAfterRender = function (func) {
  17348. this.onAfterRenderObservable.add(func);
  17349. };
  17350. /**
  17351. * Disposes a previously registered javascript function called after the rendering.
  17352. * This function is passed the current mesh and doesn't return anything.
  17353. */
  17354. Mesh.prototype.unregisterAfterRender = function (func) {
  17355. this.onAfterRenderObservable.removeCallback(func);
  17356. };
  17357. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17358. var scene = this.getScene();
  17359. this._batchCache.mustReturn = false;
  17360. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17361. this._batchCache.visibleInstances[subMeshId] = null;
  17362. if (this._visibleInstances) {
  17363. var currentRenderId = scene.getRenderId();
  17364. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17365. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17366. var selfRenderId = this._renderId;
  17367. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17368. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17369. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17370. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17371. }
  17372. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17373. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17374. this._batchCache.mustReturn = true;
  17375. return this._batchCache;
  17376. }
  17377. if (currentRenderId !== selfRenderId) {
  17378. this._batchCache.renderSelf[subMeshId] = false;
  17379. }
  17380. }
  17381. this._renderIdForInstances[subMeshId] = currentRenderId;
  17382. }
  17383. return this._batchCache;
  17384. };
  17385. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17386. var visibleInstances = batch.visibleInstances[subMesh._id];
  17387. var matricesCount = visibleInstances.length + 1;
  17388. var bufferSize = matricesCount * 16 * 4;
  17389. while (this._instancesBufferSize < bufferSize) {
  17390. this._instancesBufferSize *= 2;
  17391. }
  17392. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17393. if (this._worldMatricesInstancesBuffer) {
  17394. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17395. }
  17396. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17397. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17398. }
  17399. var offset = 0;
  17400. var instancesCount = 0;
  17401. var world = this.getWorldMatrix();
  17402. if (batch.renderSelf[subMesh._id]) {
  17403. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17404. offset += 16;
  17405. instancesCount++;
  17406. }
  17407. if (visibleInstances) {
  17408. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17409. var instance = visibleInstances[instanceIndex];
  17410. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17411. offset += 16;
  17412. instancesCount++;
  17413. }
  17414. }
  17415. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17416. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17417. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17418. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17419. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17420. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17421. this._draw(subMesh, fillMode, instancesCount);
  17422. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17423. };
  17424. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17425. var scene = this.getScene();
  17426. var engine = scene.getEngine();
  17427. if (hardwareInstancedRendering) {
  17428. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17429. }
  17430. else {
  17431. if (batch.renderSelf[subMesh._id]) {
  17432. // Draw
  17433. if (onBeforeDraw) {
  17434. onBeforeDraw(false, this.getWorldMatrix());
  17435. }
  17436. this._draw(subMesh, fillMode);
  17437. }
  17438. if (batch.visibleInstances[subMesh._id]) {
  17439. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17440. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17441. // World
  17442. var world = instance.getWorldMatrix();
  17443. if (onBeforeDraw) {
  17444. onBeforeDraw(true, world);
  17445. }
  17446. // Draw
  17447. this._draw(subMesh, fillMode);
  17448. }
  17449. }
  17450. }
  17451. };
  17452. /**
  17453. * Triggers the draw call for the mesh.
  17454. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  17455. */
  17456. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17457. var scene = this.getScene();
  17458. // Managing instances
  17459. var batch = this._getInstancesRenderList(subMesh._id);
  17460. if (batch.mustReturn) {
  17461. return;
  17462. }
  17463. // Checking geometry state
  17464. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17465. return;
  17466. }
  17467. var callbackIndex;
  17468. this.onBeforeRenderObservable.notifyObservers(this);
  17469. var engine = scene.getEngine();
  17470. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17471. // Material
  17472. var effectiveMaterial = subMesh.getMaterial();
  17473. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17474. return;
  17475. }
  17476. // Outline - step 1
  17477. var savedDepthWrite = engine.getDepthWrite();
  17478. if (this.renderOutline) {
  17479. engine.setDepthWrite(false);
  17480. scene.getOutlineRenderer().render(subMesh, batch);
  17481. engine.setDepthWrite(savedDepthWrite);
  17482. }
  17483. effectiveMaterial._preBind();
  17484. var effect = effectiveMaterial.getEffect();
  17485. // Bind
  17486. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17487. this._bind(subMesh, effect, fillMode);
  17488. var world = this.getWorldMatrix();
  17489. effectiveMaterial.bind(world, this);
  17490. // Alpha mode
  17491. if (enableAlphaMode) {
  17492. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17493. }
  17494. // Draw
  17495. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17496. if (isInstance) {
  17497. effectiveMaterial.bindOnlyWorldMatrix(world);
  17498. }
  17499. });
  17500. // Unbind
  17501. effectiveMaterial.unbind();
  17502. // Outline - step 2
  17503. if (this.renderOutline && savedDepthWrite) {
  17504. engine.setDepthWrite(true);
  17505. engine.setColorWrite(false);
  17506. scene.getOutlineRenderer().render(subMesh, batch);
  17507. engine.setColorWrite(true);
  17508. }
  17509. // Overlay
  17510. if (this.renderOverlay) {
  17511. var currentMode = engine.getAlphaMode();
  17512. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17513. scene.getOutlineRenderer().render(subMesh, batch, true);
  17514. engine.setAlphaMode(currentMode);
  17515. }
  17516. this.onAfterRenderObservable.notifyObservers(this);
  17517. };
  17518. /**
  17519. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17520. */
  17521. Mesh.prototype.getEmittedParticleSystems = function () {
  17522. var results = new Array();
  17523. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17524. var particleSystem = this.getScene().particleSystems[index];
  17525. if (particleSystem.emitter === this) {
  17526. results.push(particleSystem);
  17527. }
  17528. }
  17529. return results;
  17530. };
  17531. /**
  17532. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17533. */
  17534. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17535. var results = new Array();
  17536. var descendants = this.getDescendants();
  17537. descendants.push(this);
  17538. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17539. var particleSystem = this.getScene().particleSystems[index];
  17540. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17541. results.push(particleSystem);
  17542. }
  17543. }
  17544. return results;
  17545. };
  17546. Mesh.prototype._checkDelayState = function () {
  17547. var _this = this;
  17548. var that = this;
  17549. var scene = this.getScene();
  17550. if (this._geometry) {
  17551. this._geometry.load(scene);
  17552. }
  17553. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17554. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17555. scene._addPendingData(that);
  17556. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17557. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17558. if (data instanceof ArrayBuffer) {
  17559. _this._delayLoadingFunction(data, _this);
  17560. }
  17561. else {
  17562. _this._delayLoadingFunction(JSON.parse(data), _this);
  17563. }
  17564. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17565. scene._removePendingData(_this);
  17566. }, function () { }, scene.database, getBinaryData);
  17567. }
  17568. };
  17569. /**
  17570. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17571. */
  17572. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17573. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17574. return false;
  17575. }
  17576. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17577. return false;
  17578. }
  17579. this._checkDelayState();
  17580. return true;
  17581. };
  17582. Mesh.prototype.setMaterialByID = function (id) {
  17583. var materials = this.getScene().materials;
  17584. var index;
  17585. for (index = 0; index < materials.length; index++) {
  17586. if (materials[index].id === id) {
  17587. this.material = materials[index];
  17588. return;
  17589. }
  17590. }
  17591. // Multi
  17592. var multiMaterials = this.getScene().multiMaterials;
  17593. for (index = 0; index < multiMaterials.length; index++) {
  17594. if (multiMaterials[index].id === id) {
  17595. this.material = multiMaterials[index];
  17596. return;
  17597. }
  17598. }
  17599. };
  17600. Mesh.prototype.getAnimatables = function () {
  17601. var results = [];
  17602. if (this.material) {
  17603. results.push(this.material);
  17604. }
  17605. if (this.skeleton) {
  17606. results.push(this.skeleton);
  17607. }
  17608. return results;
  17609. };
  17610. // Geometry
  17611. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17612. // Position
  17613. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17614. return;
  17615. }
  17616. this._resetPointsArrayCache();
  17617. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17618. var temp = [];
  17619. var index;
  17620. for (index = 0; index < data.length; index += 3) {
  17621. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17622. }
  17623. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17624. // Normals
  17625. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17626. return;
  17627. }
  17628. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17629. temp = [];
  17630. for (index = 0; index < data.length; index += 3) {
  17631. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17632. }
  17633. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17634. // flip faces?
  17635. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17636. this.flipFaces();
  17637. }
  17638. };
  17639. // Will apply current transform to mesh and reset world matrix
  17640. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17641. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17642. this.scaling.copyFromFloats(1, 1, 1);
  17643. this.position.copyFromFloats(0, 0, 0);
  17644. this.rotation.copyFromFloats(0, 0, 0);
  17645. //only if quaternion is already set
  17646. if (this.rotationQuaternion) {
  17647. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17648. }
  17649. this._worldMatrix = BABYLON.Matrix.Identity();
  17650. };
  17651. // Cache
  17652. Mesh.prototype._resetPointsArrayCache = function () {
  17653. this._positions = null;
  17654. };
  17655. Mesh.prototype._generatePointsArray = function () {
  17656. if (this._positions)
  17657. return true;
  17658. this._positions = [];
  17659. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17660. if (!data) {
  17661. return false;
  17662. }
  17663. for (var index = 0; index < data.length; index += 3) {
  17664. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17665. }
  17666. return true;
  17667. };
  17668. // Clone
  17669. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17670. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17671. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17672. };
  17673. // Dispose
  17674. Mesh.prototype.dispose = function (doNotRecurse) {
  17675. if (this._geometry) {
  17676. this._geometry.releaseForMesh(this, true);
  17677. }
  17678. // Instances
  17679. if (this._worldMatricesInstancesBuffer) {
  17680. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17681. this._worldMatricesInstancesBuffer = null;
  17682. }
  17683. while (this.instances.length) {
  17684. this.instances[0].dispose();
  17685. }
  17686. _super.prototype.dispose.call(this, doNotRecurse);
  17687. };
  17688. // Geometric tools
  17689. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17690. var _this = this;
  17691. var scene = this.getScene();
  17692. var onload = function (img) {
  17693. // Getting height map data
  17694. var canvas = document.createElement("canvas");
  17695. var context = canvas.getContext("2d");
  17696. var heightMapWidth = img.width;
  17697. var heightMapHeight = img.height;
  17698. canvas.width = heightMapWidth;
  17699. canvas.height = heightMapHeight;
  17700. context.drawImage(img, 0, 0);
  17701. // Create VertexData from map data
  17702. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17703. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17704. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17705. //execute success callback, if set
  17706. if (onSuccess) {
  17707. onSuccess(_this);
  17708. }
  17709. };
  17710. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17711. };
  17712. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17714. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17715. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17716. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17717. return;
  17718. }
  17719. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17720. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17721. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17722. var position = BABYLON.Vector3.Zero();
  17723. var normal = BABYLON.Vector3.Zero();
  17724. var uv = BABYLON.Vector2.Zero();
  17725. for (var index = 0; index < positions.length; index += 3) {
  17726. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17727. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17728. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17729. // Compute height
  17730. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17731. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17732. var pos = (u + v * heightMapWidth) * 4;
  17733. var r = buffer[pos] / 255.0;
  17734. var g = buffer[pos + 1] / 255.0;
  17735. var b = buffer[pos + 2] / 255.0;
  17736. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17737. normal.normalize();
  17738. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17739. position = position.add(normal);
  17740. position.toArray(positions, index);
  17741. }
  17742. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17743. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17744. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17745. };
  17746. /**
  17747. * Modify the mesh to get a flat shading rendering.
  17748. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17749. * Warning : the mesh is really modified.
  17750. */
  17751. Mesh.prototype.convertToFlatShadedMesh = function () {
  17752. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17753. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17754. var kinds = this.getVerticesDataKinds();
  17755. var vbs = [];
  17756. var data = [];
  17757. var newdata = [];
  17758. var updatableNormals = false;
  17759. var kindIndex;
  17760. var kind;
  17761. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17762. kind = kinds[kindIndex];
  17763. var vertexBuffer = this.getVertexBuffer(kind);
  17764. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17765. updatableNormals = vertexBuffer.isUpdatable();
  17766. kinds.splice(kindIndex, 1);
  17767. kindIndex--;
  17768. continue;
  17769. }
  17770. vbs[kind] = vertexBuffer;
  17771. data[kind] = vbs[kind].getData();
  17772. newdata[kind] = [];
  17773. }
  17774. // Save previous submeshes
  17775. var previousSubmeshes = this.subMeshes.slice(0);
  17776. var indices = this.getIndices();
  17777. var totalIndices = this.getTotalIndices();
  17778. // Generating unique vertices per face
  17779. var index;
  17780. for (index = 0; index < totalIndices; index++) {
  17781. var vertexIndex = indices[index];
  17782. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17783. kind = kinds[kindIndex];
  17784. var stride = vbs[kind].getStrideSize();
  17785. for (var offset = 0; offset < stride; offset++) {
  17786. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17787. }
  17788. }
  17789. }
  17790. // Updating faces & normal
  17791. var normals = [];
  17792. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17793. for (index = 0; index < totalIndices; index += 3) {
  17794. indices[index] = index;
  17795. indices[index + 1] = index + 1;
  17796. indices[index + 2] = index + 2;
  17797. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17798. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17799. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17800. var p1p2 = p1.subtract(p2);
  17801. var p3p2 = p3.subtract(p2);
  17802. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17803. // Store same normals for every vertex
  17804. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17805. normals.push(normal.x);
  17806. normals.push(normal.y);
  17807. normals.push(normal.z);
  17808. }
  17809. }
  17810. this.setIndices(indices);
  17811. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17812. // Updating vertex buffers
  17813. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17814. kind = kinds[kindIndex];
  17815. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17816. }
  17817. // Updating submeshes
  17818. this.releaseSubMeshes();
  17819. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17820. var previousOne = previousSubmeshes[submeshIndex];
  17821. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17822. }
  17823. this.synchronizeInstances();
  17824. };
  17825. /**
  17826. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17827. * In other words, more vertices, no more indices and a single bigger VBO.
  17828. */
  17829. Mesh.prototype.convertToUnIndexedMesh = function () {
  17830. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17831. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17832. var kinds = this.getVerticesDataKinds();
  17833. var vbs = [];
  17834. var data = [];
  17835. var newdata = [];
  17836. var updatableNormals = false;
  17837. var kindIndex;
  17838. var kind;
  17839. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17840. kind = kinds[kindIndex];
  17841. var vertexBuffer = this.getVertexBuffer(kind);
  17842. vbs[kind] = vertexBuffer;
  17843. data[kind] = vbs[kind].getData();
  17844. newdata[kind] = [];
  17845. }
  17846. // Save previous submeshes
  17847. var previousSubmeshes = this.subMeshes.slice(0);
  17848. var indices = this.getIndices();
  17849. var totalIndices = this.getTotalIndices();
  17850. // Generating unique vertices per face
  17851. var index;
  17852. for (index = 0; index < totalIndices; index++) {
  17853. var vertexIndex = indices[index];
  17854. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17855. kind = kinds[kindIndex];
  17856. var stride = vbs[kind].getStrideSize();
  17857. for (var offset = 0; offset < stride; offset++) {
  17858. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17859. }
  17860. }
  17861. }
  17862. // Updating indices
  17863. for (index = 0; index < totalIndices; index += 3) {
  17864. indices[index] = index;
  17865. indices[index + 1] = index + 1;
  17866. indices[index + 2] = index + 2;
  17867. }
  17868. this.setIndices(indices);
  17869. // Updating vertex buffers
  17870. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17871. kind = kinds[kindIndex];
  17872. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17873. }
  17874. // Updating submeshes
  17875. this.releaseSubMeshes();
  17876. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17877. var previousOne = previousSubmeshes[submeshIndex];
  17878. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17879. }
  17880. this._unIndexed = true;
  17881. this.synchronizeInstances();
  17882. };
  17883. /**
  17884. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  17885. * Warning : the mesh is really modified.
  17886. */
  17887. Mesh.prototype.flipFaces = function (flipNormals) {
  17888. if (flipNormals === void 0) { flipNormals = false; }
  17889. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17890. var i;
  17891. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17892. for (i = 0; i < vertex_data.normals.length; i++) {
  17893. vertex_data.normals[i] *= -1;
  17894. }
  17895. }
  17896. var temp;
  17897. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17898. // reassign indices
  17899. temp = vertex_data.indices[i + 1];
  17900. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17901. vertex_data.indices[i + 2] = temp;
  17902. }
  17903. vertex_data.applyToMesh(this);
  17904. };
  17905. // Instances
  17906. /**
  17907. * Creates a new `InstancedMesh` object from the mesh model.
  17908. */
  17909. Mesh.prototype.createInstance = function (name) {
  17910. return new BABYLON.InstancedMesh(name, this);
  17911. };
  17912. Mesh.prototype.synchronizeInstances = function () {
  17913. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17914. var instance = this.instances[instanceIndex];
  17915. instance._syncSubMeshes();
  17916. }
  17917. };
  17918. /**
  17919. * Simplify the mesh according to the given array of settings.
  17920. * Function will return immediately and will simplify async.
  17921. * @param settings a collection of simplification settings.
  17922. * @param parallelProcessing should all levels calculate parallel or one after the other.
  17923. * @param type the type of simplification to run.
  17924. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  17925. */
  17926. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  17927. if (parallelProcessing === void 0) { parallelProcessing = true; }
  17928. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  17929. this.getScene().simplificationQueue.addTask({
  17930. settings: settings,
  17931. parallelProcessing: parallelProcessing,
  17932. mesh: this,
  17933. simplificationType: simplificationType,
  17934. successCallback: successCallback
  17935. });
  17936. };
  17937. /**
  17938. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  17939. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  17940. * This should be used together with the simplification to avoid disappearing triangles.
  17941. * @param successCallback an optional success callback to be called after the optimization finished.
  17942. */
  17943. Mesh.prototype.optimizeIndices = function (successCallback) {
  17944. var _this = this;
  17945. var indices = this.getIndices();
  17946. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17947. var vectorPositions = [];
  17948. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  17949. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  17950. }
  17951. var dupes = [];
  17952. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  17953. var realPos = vectorPositions.length - 1 - iteration;
  17954. var testedPosition = vectorPositions[realPos];
  17955. for (var j = 0; j < realPos; ++j) {
  17956. var againstPosition = vectorPositions[j];
  17957. if (testedPosition.equals(againstPosition)) {
  17958. dupes[realPos] = j;
  17959. break;
  17960. }
  17961. }
  17962. }, function () {
  17963. for (var i = 0; i < indices.length; ++i) {
  17964. indices[i] = dupes[indices[i]] || indices[i];
  17965. }
  17966. //indices are now reordered
  17967. var originalSubMeshes = _this.subMeshes.slice(0);
  17968. _this.setIndices(indices);
  17969. _this.subMeshes = originalSubMeshes;
  17970. if (successCallback) {
  17971. successCallback(_this);
  17972. }
  17973. });
  17974. };
  17975. // Statics
  17976. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  17977. var mesh = new Mesh(parsedMesh.name, scene);
  17978. mesh.id = parsedMesh.id;
  17979. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17980. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17981. if (parsedMesh.rotationQuaternion) {
  17982. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17983. }
  17984. else if (parsedMesh.rotation) {
  17985. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17986. }
  17987. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17988. if (parsedMesh.localMatrix) {
  17989. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17990. }
  17991. else if (parsedMesh.pivotMatrix) {
  17992. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17993. }
  17994. mesh.setEnabled(parsedMesh.isEnabled);
  17995. mesh.isVisible = parsedMesh.isVisible;
  17996. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17997. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17998. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17999. if (parsedMesh.applyFog !== undefined) {
  18000. mesh.applyFog = parsedMesh.applyFog;
  18001. }
  18002. if (parsedMesh.pickable !== undefined) {
  18003. mesh.isPickable = parsedMesh.pickable;
  18004. }
  18005. if (parsedMesh.alphaIndex !== undefined) {
  18006. mesh.alphaIndex = parsedMesh.alphaIndex;
  18007. }
  18008. mesh.receiveShadows = parsedMesh.receiveShadows;
  18009. mesh.billboardMode = parsedMesh.billboardMode;
  18010. if (parsedMesh.visibility !== undefined) {
  18011. mesh.visibility = parsedMesh.visibility;
  18012. }
  18013. mesh.checkCollisions = parsedMesh.checkCollisions;
  18014. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18015. // freezeWorldMatrix
  18016. if (parsedMesh.freezeWorldMatrix) {
  18017. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18018. }
  18019. // Parent
  18020. if (parsedMesh.parentId) {
  18021. mesh._waitingParentId = parsedMesh.parentId;
  18022. }
  18023. // Actions
  18024. if (parsedMesh.actions !== undefined) {
  18025. mesh._waitingActions = parsedMesh.actions;
  18026. }
  18027. // Geometry
  18028. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18029. if (parsedMesh.delayLoadingFile) {
  18030. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18031. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18032. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18033. if (parsedMesh._binaryInfo) {
  18034. mesh._binaryInfo = parsedMesh._binaryInfo;
  18035. }
  18036. mesh._delayInfo = [];
  18037. if (parsedMesh.hasUVs) {
  18038. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18039. }
  18040. if (parsedMesh.hasUVs2) {
  18041. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18042. }
  18043. if (parsedMesh.hasUVs3) {
  18044. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18045. }
  18046. if (parsedMesh.hasUVs4) {
  18047. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18048. }
  18049. if (parsedMesh.hasUVs5) {
  18050. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18051. }
  18052. if (parsedMesh.hasUVs6) {
  18053. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18054. }
  18055. if (parsedMesh.hasColors) {
  18056. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18057. }
  18058. if (parsedMesh.hasMatricesIndices) {
  18059. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18060. }
  18061. if (parsedMesh.hasMatricesWeights) {
  18062. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18063. }
  18064. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18065. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18066. mesh._checkDelayState();
  18067. }
  18068. }
  18069. else {
  18070. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18071. }
  18072. // Material
  18073. if (parsedMesh.materialId) {
  18074. mesh.setMaterialByID(parsedMesh.materialId);
  18075. }
  18076. else {
  18077. mesh.material = null;
  18078. }
  18079. // Skeleton
  18080. if (parsedMesh.skeletonId > -1) {
  18081. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18082. if (parsedMesh.numBoneInfluencers) {
  18083. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18084. }
  18085. }
  18086. // Animations
  18087. if (parsedMesh.animations) {
  18088. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18089. var parsedAnimation = parsedMesh.animations[animationIndex];
  18090. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18091. }
  18092. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18093. }
  18094. if (parsedMesh.autoAnimate) {
  18095. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18096. }
  18097. // Layer Mask
  18098. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18099. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18100. }
  18101. else {
  18102. mesh.layerMask = 0x0FFFFFFF;
  18103. }
  18104. //(Deprecated) physics
  18105. if (parsedMesh.physicsImpostor) {
  18106. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18107. mass: parsedMesh.physicsMass,
  18108. friction: parsedMesh.physicsFriction,
  18109. restitution: parsedMesh.physicsRestitution
  18110. }, scene);
  18111. }
  18112. // Instances
  18113. if (parsedMesh.instances) {
  18114. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18115. var parsedInstance = parsedMesh.instances[index];
  18116. var instance = mesh.createInstance(parsedInstance.name);
  18117. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18118. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18119. if (parsedInstance.rotationQuaternion) {
  18120. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18121. }
  18122. else if (parsedInstance.rotation) {
  18123. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18124. }
  18125. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18126. instance.checkCollisions = mesh.checkCollisions;
  18127. if (parsedMesh.animations) {
  18128. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18129. parsedAnimation = parsedMesh.animations[animationIndex];
  18130. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18131. }
  18132. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18133. }
  18134. }
  18135. }
  18136. return mesh;
  18137. };
  18138. /**
  18139. * Creates a ribbon mesh.
  18140. * Please consider using the same method from the `MeshBuilder` class instead.
  18141. * 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.
  18142. *
  18143. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18144. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18145. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18146. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18147. * 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.
  18148. * 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.
  18149. * 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
  18150. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18153. */
  18154. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18155. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18156. pathArray: pathArray,
  18157. closeArray: closeArray,
  18158. closePath: closePath,
  18159. offset: offset,
  18160. updatable: updatable,
  18161. sideOrientation: sideOrientation,
  18162. instance: instance
  18163. }, scene);
  18164. };
  18165. /**
  18166. * Creates a plane polygonal mesh. By default, this is a disc.
  18167. * Please consider using the same method from the `MeshBuilder` class instead.
  18168. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18169. * 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.
  18170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18173. */
  18174. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18175. var options = {
  18176. radius: radius,
  18177. tessellation: tessellation,
  18178. sideOrientation: sideOrientation,
  18179. updatable: updatable
  18180. };
  18181. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18182. };
  18183. /**
  18184. * Creates a box mesh.
  18185. * Please consider using the same method from the `MeshBuilder` class instead.
  18186. * The parameter `size` sets the size (float) of each box side (default 1).
  18187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18188. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18190. */
  18191. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18192. var options = {
  18193. size: size,
  18194. sideOrientation: sideOrientation,
  18195. updatable: updatable
  18196. };
  18197. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18198. };
  18199. /**
  18200. * Creates a sphere mesh.
  18201. * Please consider using the same method from the `MeshBuilder` class instead.
  18202. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18203. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18207. */
  18208. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18209. var options = {
  18210. segments: segments,
  18211. diameterX: diameter,
  18212. diameterY: diameter,
  18213. diameterZ: diameter,
  18214. sideOrientation: sideOrientation,
  18215. updatable: updatable
  18216. };
  18217. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18218. };
  18219. /**
  18220. * Creates a cylinder or a cone mesh.
  18221. * Please consider using the same method from the `MeshBuilder` class instead.
  18222. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18223. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18224. * 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.
  18225. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18226. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18227. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18228. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18230. */
  18231. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18232. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18233. if (scene !== undefined) {
  18234. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18235. updatable = scene;
  18236. }
  18237. scene = subdivisions;
  18238. subdivisions = 1;
  18239. }
  18240. var options = {
  18241. height: height,
  18242. diameterTop: diameterTop,
  18243. diameterBottom: diameterBottom,
  18244. tessellation: tessellation,
  18245. subdivisions: subdivisions,
  18246. sideOrientation: sideOrientation,
  18247. updatable: updatable
  18248. };
  18249. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18250. };
  18251. // Torus (Code from SharpDX.org)
  18252. /**
  18253. * Creates a torus mesh.
  18254. * Please consider using the same method from the `MeshBuilder` class instead.
  18255. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18256. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18257. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18258. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18259. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18260. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18261. */
  18262. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18263. var options = {
  18264. diameter: diameter,
  18265. thickness: thickness,
  18266. tessellation: tessellation,
  18267. sideOrientation: sideOrientation,
  18268. updatable: updatable
  18269. };
  18270. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18271. };
  18272. /**
  18273. * Creates a torus knot mesh.
  18274. * Please consider using the same method from the `MeshBuilder` class instead.
  18275. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18276. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18277. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18278. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18279. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18280. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18282. */
  18283. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18284. var options = {
  18285. radius: radius,
  18286. tube: tube,
  18287. radialSegments: radialSegments,
  18288. tubularSegments: tubularSegments,
  18289. p: p,
  18290. q: q,
  18291. sideOrientation: sideOrientation,
  18292. updatable: updatable
  18293. };
  18294. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18295. };
  18296. /**
  18297. * Creates a line mesh.
  18298. * Please consider using the same method from the `MeshBuilder` class instead.
  18299. * 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.
  18300. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18301. * The parameter `points` is an array successive Vector3.
  18302. * 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
  18303. * When updating an instance, remember that only point positions can change, not the number of points.
  18304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18305. */
  18306. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18307. var options = {
  18308. points: points,
  18309. updatable: updatable,
  18310. instance: instance
  18311. };
  18312. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18313. };
  18314. /**
  18315. * Creates a dashed line mesh.
  18316. * Please consider using the same method from the `MeshBuilder` class instead.
  18317. * 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.
  18318. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18319. * The parameter `points` is an array successive Vector3.
  18320. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18321. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18322. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18323. * 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
  18324. * When updating an instance, remember that only point positions can change, not the number of points.
  18325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18326. */
  18327. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18328. var options = {
  18329. points: points,
  18330. dashSize: dashSize,
  18331. gapSize: gapSize,
  18332. dashNb: dashNb,
  18333. updatable: updatable
  18334. };
  18335. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18336. };
  18337. /**
  18338. * Creates an extruded shape mesh.
  18339. * 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.
  18340. * Please consider using the same method from the `MeshBuilder` class instead.
  18341. *
  18342. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18343. * 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
  18344. * extruded along the Z axis.
  18345. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18346. * 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.
  18347. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18348. * 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
  18349. * 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
  18350. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18351. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18352. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18354. */
  18355. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18356. var options = {
  18357. shape: shape,
  18358. path: path,
  18359. scale: scale,
  18360. rotation: rotation,
  18361. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18362. sideOrientation: sideOrientation,
  18363. instance: instance,
  18364. updatable: updatable
  18365. };
  18366. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18367. };
  18368. /**
  18369. * Creates an custom extruded shape mesh.
  18370. * 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.
  18371. * Please consider using the same method from the `MeshBuilder` class instead.
  18372. *
  18373. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18374. * 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
  18375. * extruded along the Z axis.
  18376. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18377. * 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
  18378. * and the distance of this point from the begining of the path :
  18379. * ```rotationFunction = function(i, distance) {
  18380. * // do things
  18381. * return rotationValue; }```
  18382. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18383. * 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
  18384. * and the distance of this point from the begining of the path :
  18385. * ````scaleFunction = function(i, distance) {
  18386. * // do things
  18387. * return scaleValue;}```
  18388. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18389. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18390. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18391. * 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
  18392. * 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
  18393. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18397. */
  18398. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18399. var options = {
  18400. shape: shape,
  18401. path: path,
  18402. scaleFunction: scaleFunction,
  18403. rotationFunction: rotationFunction,
  18404. ribbonCloseArray: ribbonCloseArray,
  18405. ribbonClosePath: ribbonClosePath,
  18406. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18407. sideOrientation: sideOrientation,
  18408. instance: instance,
  18409. updatable: updatable
  18410. };
  18411. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18412. };
  18413. /**
  18414. * Creates lathe mesh.
  18415. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18416. * Please consider using the same method from the `MeshBuilder` class instead.
  18417. *
  18418. * 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
  18419. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18420. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18421. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18425. */
  18426. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18427. var options = {
  18428. shape: shape,
  18429. radius: radius,
  18430. tessellation: tessellation,
  18431. sideOrientation: sideOrientation,
  18432. updatable: updatable
  18433. };
  18434. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18435. };
  18436. /**
  18437. * Creates a plane mesh.
  18438. * Please consider using the same method from the `MeshBuilder` class instead.
  18439. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18443. */
  18444. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18445. var options = {
  18446. size: size,
  18447. width: size,
  18448. height: size,
  18449. sideOrientation: sideOrientation,
  18450. updatable: updatable
  18451. };
  18452. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18453. };
  18454. /**
  18455. * Creates a ground mesh.
  18456. * Please consider using the same method from the `MeshBuilder` class instead.
  18457. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18458. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18460. */
  18461. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18462. var options = {
  18463. width: width,
  18464. height: height,
  18465. subdivisions: subdivisions,
  18466. updatable: updatable
  18467. };
  18468. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18469. };
  18470. /**
  18471. * Creates a tiled ground mesh.
  18472. * Please consider using the same method from the `MeshBuilder` class instead.
  18473. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18474. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18475. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18476. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18477. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18478. * numbers of subdivisions on the ground width and height of each tile.
  18479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18480. */
  18481. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18482. var options = {
  18483. xmin: xmin,
  18484. zmin: zmin,
  18485. xmax: xmax,
  18486. zmax: zmax,
  18487. subdivisions: subdivisions,
  18488. precision: precision,
  18489. updatable: updatable
  18490. };
  18491. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18492. };
  18493. /**
  18494. * Creates a ground mesh from a height map.
  18495. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18496. * Please consider using the same method from the `MeshBuilder` class instead.
  18497. * The parameter `url` sets the URL of the height map image resource.
  18498. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18499. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18500. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18501. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18502. * 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).
  18503. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18504. * return; }```
  18505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18506. */
  18507. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18508. var options = {
  18509. width: width,
  18510. height: height,
  18511. subdivisions: subdivisions,
  18512. minHeight: minHeight,
  18513. maxHeight: maxHeight,
  18514. updatable: updatable,
  18515. onReady: onReady
  18516. };
  18517. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18518. };
  18519. /**
  18520. * Creates a tube mesh.
  18521. * 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.
  18522. *
  18523. * Please consider using the same method from the `MeshBuilder` class instead.
  18524. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18525. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18526. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18527. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18528. * 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.
  18529. * It must return a radius value (positive float) :
  18530. * ```var radiusFunction = function(i, distance) {
  18531. * // do things
  18532. * return radius; }```
  18533. * 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
  18534. * 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
  18535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18536. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18538. */
  18539. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18540. var options = {
  18541. path: path,
  18542. radius: radius,
  18543. tessellation: tessellation,
  18544. radiusFunction: radiusFunction,
  18545. arc: 1,
  18546. cap: cap,
  18547. updatable: updatable,
  18548. sideOrientation: sideOrientation,
  18549. instance: instance
  18550. };
  18551. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18552. };
  18553. /**
  18554. * Creates a polyhedron mesh.
  18555. *
  18556. * Please consider using the same method from the `MeshBuilder` class instead.
  18557. * 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
  18558. * to choose the wanted type.
  18559. * The parameter `size` (positive float, default 1) sets the polygon size.
  18560. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18561. * 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`.
  18562. * 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
  18563. * 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)`).
  18564. * 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
  18565. * 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.
  18566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18567. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18569. */
  18570. Mesh.CreatePolyhedron = function (name, options, scene) {
  18571. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18572. };
  18573. /**
  18574. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18575. * Please consider using the same method from the `MeshBuilder` class instead.
  18576. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18577. * 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`).
  18578. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18579. * 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.
  18580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18581. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18583. */
  18584. Mesh.CreateIcoSphere = function (name, options, scene) {
  18585. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18586. };
  18587. /**
  18588. * Creates a decal mesh.
  18589. * Please consider using the same method from the `MeshBuilder` class instead.
  18590. * 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.
  18591. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18592. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18593. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18594. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18595. */
  18596. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18597. var options = {
  18598. position: position,
  18599. normal: normal,
  18600. size: size,
  18601. angle: angle
  18602. };
  18603. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18604. };
  18605. // Skeletons
  18606. /**
  18607. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18608. */
  18609. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18610. var source;
  18611. if (!this._sourcePositions) {
  18612. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18613. this._sourcePositions = new Float32Array(source);
  18614. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18615. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18616. }
  18617. }
  18618. return this._sourcePositions;
  18619. };
  18620. /**
  18621. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18622. */
  18623. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18624. var source;
  18625. if (!this._sourceNormals) {
  18626. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18627. this._sourceNormals = new Float32Array(source);
  18628. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18629. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18630. }
  18631. }
  18632. return this._sourceNormals;
  18633. };
  18634. /**
  18635. * Update the vertex buffers by applying transformation from the bones
  18636. * @param {skeleton} skeleton to apply
  18637. */
  18638. Mesh.prototype.applySkeleton = function (skeleton) {
  18639. if (!this.geometry) {
  18640. return;
  18641. }
  18642. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18643. return;
  18644. }
  18645. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18646. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18647. return this;
  18648. }
  18649. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18650. return this;
  18651. }
  18652. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18653. return this;
  18654. }
  18655. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18656. return this;
  18657. }
  18658. if (!this._sourcePositions) {
  18659. this.setPositionsForCPUSkinning();
  18660. }
  18661. if (!this._sourceNormals) {
  18662. this.setNormalsForCPUSkinning();
  18663. }
  18664. // positionsData checks for not being Float32Array will only pass at most once
  18665. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18666. if (!(positionsData instanceof Float32Array)) {
  18667. positionsData = new Float32Array(positionsData);
  18668. }
  18669. // normalsData checks for not being Float32Array will only pass at most once
  18670. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18671. if (!(normalsData instanceof Float32Array)) {
  18672. normalsData = new Float32Array(normalsData);
  18673. }
  18674. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18675. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18676. var needExtras = this.numBoneInfluencers > 4;
  18677. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18678. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18679. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18680. var tempVector3 = BABYLON.Vector3.Zero();
  18681. var finalMatrix = new BABYLON.Matrix();
  18682. var tempMatrix = new BABYLON.Matrix();
  18683. var matWeightIdx = 0;
  18684. var inf;
  18685. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18686. var weight;
  18687. for (inf = 0; inf < 4; inf++) {
  18688. weight = matricesWeightsData[matWeightIdx + inf];
  18689. if (weight > 0) {
  18690. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18691. finalMatrix.addToSelf(tempMatrix);
  18692. }
  18693. else
  18694. break;
  18695. }
  18696. if (needExtras) {
  18697. for (inf = 0; inf < 4; inf++) {
  18698. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18699. if (weight > 0) {
  18700. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18701. finalMatrix.addToSelf(tempMatrix);
  18702. }
  18703. else
  18704. break;
  18705. }
  18706. }
  18707. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18708. tempVector3.toArray(positionsData, index);
  18709. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18710. tempVector3.toArray(normalsData, index);
  18711. finalMatrix.reset();
  18712. }
  18713. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18714. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18715. return this;
  18716. };
  18717. // Tools
  18718. Mesh.MinMax = function (meshes) {
  18719. var minVector = null;
  18720. var maxVector = null;
  18721. for (var i in meshes) {
  18722. var mesh = meshes[i];
  18723. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18724. if (!minVector) {
  18725. minVector = boundingBox.minimumWorld;
  18726. maxVector = boundingBox.maximumWorld;
  18727. continue;
  18728. }
  18729. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18730. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18731. }
  18732. return {
  18733. min: minVector,
  18734. max: maxVector
  18735. };
  18736. };
  18737. Mesh.Center = function (meshesOrMinMaxVector) {
  18738. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18739. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18740. };
  18741. /**
  18742. * Merge the array of meshes into a single mesh for performance reasons.
  18743. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18744. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18745. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18746. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18747. */
  18748. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18749. if (disposeSource === void 0) { disposeSource = true; }
  18750. var index;
  18751. if (!allow32BitsIndices) {
  18752. var totalVertices = 0;
  18753. // Counting vertices
  18754. for (index = 0; index < meshes.length; index++) {
  18755. if (meshes[index]) {
  18756. totalVertices += meshes[index].getTotalVertices();
  18757. if (totalVertices > 65536) {
  18758. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18759. return null;
  18760. }
  18761. }
  18762. }
  18763. }
  18764. // Merge
  18765. var vertexData;
  18766. var otherVertexData;
  18767. var source;
  18768. for (index = 0; index < meshes.length; index++) {
  18769. if (meshes[index]) {
  18770. meshes[index].computeWorldMatrix(true);
  18771. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18772. otherVertexData.transform(meshes[index].getWorldMatrix());
  18773. if (vertexData) {
  18774. vertexData.merge(otherVertexData);
  18775. }
  18776. else {
  18777. vertexData = otherVertexData;
  18778. source = meshes[index];
  18779. }
  18780. }
  18781. }
  18782. if (!meshSubclass) {
  18783. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18784. }
  18785. vertexData.applyToMesh(meshSubclass);
  18786. // Setting properties
  18787. meshSubclass.material = source.material;
  18788. meshSubclass.checkCollisions = source.checkCollisions;
  18789. // Cleaning
  18790. if (disposeSource) {
  18791. for (index = 0; index < meshes.length; index++) {
  18792. if (meshes[index]) {
  18793. meshes[index].dispose();
  18794. }
  18795. }
  18796. }
  18797. return meshSubclass;
  18798. };
  18799. // Consts
  18800. Mesh._FRONTSIDE = 0;
  18801. Mesh._BACKSIDE = 1;
  18802. Mesh._DOUBLESIDE = 2;
  18803. Mesh._DEFAULTSIDE = 0;
  18804. Mesh._NO_CAP = 0;
  18805. Mesh._CAP_START = 1;
  18806. Mesh._CAP_END = 2;
  18807. Mesh._CAP_ALL = 3;
  18808. return Mesh;
  18809. }(BABYLON.AbstractMesh));
  18810. BABYLON.Mesh = Mesh;
  18811. })(BABYLON || (BABYLON = {}));
  18812. var BABYLON;
  18813. (function (BABYLON) {
  18814. var SubMesh = (function () {
  18815. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18816. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18817. this.materialIndex = materialIndex;
  18818. this.verticesStart = verticesStart;
  18819. this.verticesCount = verticesCount;
  18820. this.indexStart = indexStart;
  18821. this.indexCount = indexCount;
  18822. this._renderId = 0;
  18823. this._mesh = mesh;
  18824. this._renderingMesh = renderingMesh || mesh;
  18825. mesh.subMeshes.push(this);
  18826. this._trianglePlanes = [];
  18827. this._id = mesh.subMeshes.length - 1;
  18828. if (createBoundingBox) {
  18829. this.refreshBoundingInfo();
  18830. mesh.computeWorldMatrix(true);
  18831. }
  18832. }
  18833. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18834. get: function () {
  18835. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. SubMesh.prototype.getBoundingInfo = function () {
  18841. if (this.IsGlobal) {
  18842. return this._mesh.getBoundingInfo();
  18843. }
  18844. return this._boundingInfo;
  18845. };
  18846. SubMesh.prototype.getMesh = function () {
  18847. return this._mesh;
  18848. };
  18849. SubMesh.prototype.getRenderingMesh = function () {
  18850. return this._renderingMesh;
  18851. };
  18852. SubMesh.prototype.getMaterial = function () {
  18853. var rootMaterial = this._renderingMesh.material;
  18854. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18855. var multiMaterial = rootMaterial;
  18856. return multiMaterial.getSubMaterial(this.materialIndex);
  18857. }
  18858. if (!rootMaterial) {
  18859. return this._mesh.getScene().defaultMaterial;
  18860. }
  18861. return rootMaterial;
  18862. };
  18863. // Methods
  18864. SubMesh.prototype.refreshBoundingInfo = function () {
  18865. this._lastColliderWorldVertices = null;
  18866. if (this.IsGlobal) {
  18867. return;
  18868. }
  18869. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18870. if (!data) {
  18871. this._boundingInfo = this._mesh._boundingInfo;
  18872. return;
  18873. }
  18874. var indices = this._renderingMesh.getIndices();
  18875. var extend;
  18876. //is this the only submesh?
  18877. if (this.indexStart === 0 && this.indexCount === indices.length) {
  18878. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  18879. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  18880. }
  18881. else {
  18882. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  18883. }
  18884. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18885. };
  18886. SubMesh.prototype._checkCollision = function (collider) {
  18887. return this.getBoundingInfo()._checkCollision(collider);
  18888. };
  18889. SubMesh.prototype.updateBoundingInfo = function (world) {
  18890. if (!this.getBoundingInfo()) {
  18891. this.refreshBoundingInfo();
  18892. }
  18893. this.getBoundingInfo().update(world);
  18894. };
  18895. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  18896. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  18897. };
  18898. SubMesh.prototype.render = function (enableAlphaMode) {
  18899. this._renderingMesh.render(this, enableAlphaMode);
  18900. };
  18901. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  18902. if (!this._linesIndexBuffer) {
  18903. var linesIndices = [];
  18904. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18905. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  18906. }
  18907. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  18908. this.linesIndexCount = linesIndices.length;
  18909. }
  18910. return this._linesIndexBuffer;
  18911. };
  18912. SubMesh.prototype.canIntersects = function (ray) {
  18913. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  18914. };
  18915. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  18916. var intersectInfo = null;
  18917. // LineMesh first as it's also a Mesh...
  18918. if (this._mesh instanceof BABYLON.LinesMesh) {
  18919. var lineMesh = this._mesh;
  18920. // Line test
  18921. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  18922. var p0 = positions[indices[index]];
  18923. var p1 = positions[indices[index + 1]];
  18924. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  18925. if (length < 0) {
  18926. continue;
  18927. }
  18928. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  18929. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  18930. if (fastCheck) {
  18931. break;
  18932. }
  18933. }
  18934. }
  18935. }
  18936. else {
  18937. // Triangles test
  18938. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18939. var p0 = positions[indices[index]];
  18940. var p1 = positions[indices[index + 1]];
  18941. var p2 = positions[indices[index + 2]];
  18942. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  18943. if (currentIntersectInfo) {
  18944. if (currentIntersectInfo.distance < 0) {
  18945. continue;
  18946. }
  18947. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18948. intersectInfo = currentIntersectInfo;
  18949. intersectInfo.faceId = index / 3;
  18950. if (fastCheck) {
  18951. break;
  18952. }
  18953. }
  18954. }
  18955. }
  18956. }
  18957. return intersectInfo;
  18958. };
  18959. // Clone
  18960. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  18961. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  18962. if (!this.IsGlobal) {
  18963. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  18964. }
  18965. return result;
  18966. };
  18967. // Dispose
  18968. SubMesh.prototype.dispose = function () {
  18969. if (this._linesIndexBuffer) {
  18970. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  18971. this._linesIndexBuffer = null;
  18972. }
  18973. // Remove from mesh
  18974. var index = this._mesh.subMeshes.indexOf(this);
  18975. this._mesh.subMeshes.splice(index, 1);
  18976. };
  18977. // Statics
  18978. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  18979. var minVertexIndex = Number.MAX_VALUE;
  18980. var maxVertexIndex = -Number.MAX_VALUE;
  18981. renderingMesh = renderingMesh || mesh;
  18982. var indices = renderingMesh.getIndices();
  18983. for (var index = startIndex; index < startIndex + indexCount; index++) {
  18984. var vertexIndex = indices[index];
  18985. if (vertexIndex < minVertexIndex)
  18986. minVertexIndex = vertexIndex;
  18987. if (vertexIndex > maxVertexIndex)
  18988. maxVertexIndex = vertexIndex;
  18989. }
  18990. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  18991. };
  18992. return SubMesh;
  18993. }());
  18994. BABYLON.SubMesh = SubMesh;
  18995. })(BABYLON || (BABYLON = {}));
  18996. var BABYLON;
  18997. (function (BABYLON) {
  18998. var MeshBuilder = (function () {
  18999. function MeshBuilder() {
  19000. }
  19001. /**
  19002. * Creates a box mesh.
  19003. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19004. * The parameter `size` sets the size (float) of each box side (default 1).
  19005. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19006. * 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).
  19007. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19008. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19009. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19011. */
  19012. MeshBuilder.CreateBox = function (name, options, scene) {
  19013. var box = new BABYLON.Mesh(name, scene);
  19014. var vertexData = BABYLON.VertexData.CreateBox(options);
  19015. vertexData.applyToMesh(box, options.updatable);
  19016. return box;
  19017. };
  19018. /**
  19019. * Creates a sphere mesh.
  19020. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19021. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19022. * 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`).
  19023. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19024. * 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
  19025. * 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).
  19026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19029. */
  19030. MeshBuilder.CreateSphere = function (name, options, scene) {
  19031. var sphere = new BABYLON.Mesh(name, scene);
  19032. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19033. vertexData.applyToMesh(sphere, options.updatable);
  19034. return sphere;
  19035. };
  19036. /**
  19037. * Creates a plane polygonal mesh. By default, this is a disc.
  19038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19039. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19040. * 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.
  19041. * 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
  19042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19045. */
  19046. MeshBuilder.CreateDisc = function (name, options, scene) {
  19047. var disc = new BABYLON.Mesh(name, scene);
  19048. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19049. vertexData.applyToMesh(disc, options.updatable);
  19050. return disc;
  19051. };
  19052. /**
  19053. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19054. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19055. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19056. * 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`).
  19057. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19058. * 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.
  19059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19060. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19064. var sphere = new BABYLON.Mesh(name, scene);
  19065. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19066. vertexData.applyToMesh(sphere, options.updatable);
  19067. return sphere;
  19068. };
  19069. ;
  19070. /**
  19071. * Creates a ribbon mesh.
  19072. * 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.
  19073. *
  19074. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19075. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19076. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19077. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19078. * 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.
  19079. * 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.
  19080. * 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
  19081. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19084. */
  19085. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19086. var pathArray = options.pathArray;
  19087. var closeArray = options.closeArray;
  19088. var closePath = options.closePath;
  19089. var offset = options.offset;
  19090. var sideOrientation = options.sideOrientation;
  19091. var instance = options.instance;
  19092. var updatable = options.updatable;
  19093. if (instance) {
  19094. // positionFunction : ribbon case
  19095. // only pathArray and sideOrientation parameters are taken into account for positions update
  19096. var positionFunction = function (positions) {
  19097. var minlg = pathArray[0].length;
  19098. var i = 0;
  19099. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19100. for (var si = 1; si <= ns; si++) {
  19101. for (var p = 0; p < pathArray.length; p++) {
  19102. var path = pathArray[p];
  19103. var l = path.length;
  19104. minlg = (minlg < l) ? minlg : l;
  19105. var j = 0;
  19106. while (j < minlg) {
  19107. positions[i] = path[j].x;
  19108. positions[i + 1] = path[j].y;
  19109. positions[i + 2] = path[j].z;
  19110. j++;
  19111. i += 3;
  19112. }
  19113. if (instance._closePath) {
  19114. positions[i] = path[0].x;
  19115. positions[i + 1] = path[0].y;
  19116. positions[i + 2] = path[0].z;
  19117. i += 3;
  19118. }
  19119. }
  19120. }
  19121. };
  19122. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19123. positionFunction(positions);
  19124. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19125. if (!(instance.areNormalsFrozen)) {
  19126. var indices = instance.getIndices();
  19127. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19128. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19129. if (instance._closePath) {
  19130. var indexFirst = 0;
  19131. var indexLast = 0;
  19132. for (var p = 0; p < pathArray.length; p++) {
  19133. indexFirst = instance._idx[p] * 3;
  19134. if (p + 1 < pathArray.length) {
  19135. indexLast = (instance._idx[p + 1] - 1) * 3;
  19136. }
  19137. else {
  19138. indexLast = normals.length - 3;
  19139. }
  19140. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19141. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19142. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19143. normals[indexLast] = normals[indexFirst];
  19144. normals[indexLast + 1] = normals[indexFirst + 1];
  19145. normals[indexLast + 2] = normals[indexFirst + 2];
  19146. }
  19147. }
  19148. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19149. }
  19150. return instance;
  19151. }
  19152. else {
  19153. var ribbon = new BABYLON.Mesh(name, scene);
  19154. ribbon.sideOrientation = sideOrientation;
  19155. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19156. if (closePath) {
  19157. ribbon._idx = vertexData._idx;
  19158. }
  19159. ribbon._closePath = closePath;
  19160. ribbon._closeArray = closeArray;
  19161. vertexData.applyToMesh(ribbon, updatable);
  19162. return ribbon;
  19163. }
  19164. };
  19165. /**
  19166. * Creates a cylinder or a cone mesh.
  19167. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19168. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19169. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19170. * 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.
  19171. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19172. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19173. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19174. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19175. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19176. * 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).
  19177. * 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
  19178. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19179. * 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
  19180. * 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.
  19181. * If `enclose` is false, a ring surface is one element.
  19182. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19183. * 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
  19184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19187. */
  19188. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19189. var cylinder = new BABYLON.Mesh(name, scene);
  19190. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19191. vertexData.applyToMesh(cylinder, options.updatable);
  19192. return cylinder;
  19193. };
  19194. /**
  19195. * Creates a torus mesh.
  19196. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19197. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19198. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19199. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19200. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19201. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19203. */
  19204. MeshBuilder.CreateTorus = function (name, options, scene) {
  19205. var torus = new BABYLON.Mesh(name, scene);
  19206. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19207. vertexData.applyToMesh(torus, options.updatable);
  19208. return torus;
  19209. };
  19210. /**
  19211. * Creates a torus knot mesh.
  19212. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19213. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19214. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19215. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19216. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19218. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19220. */
  19221. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19222. var torusKnot = new BABYLON.Mesh(name, scene);
  19223. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19224. vertexData.applyToMesh(torusKnot, options.updatable);
  19225. return torusKnot;
  19226. };
  19227. /**
  19228. * Creates a line system mesh.
  19229. * A line system is a pool of many lines gathered in a single mesh.
  19230. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19231. * 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.
  19232. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19233. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19234. * 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
  19235. * 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
  19236. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19238. */
  19239. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19240. var instance = options.instance;
  19241. var lines = options.lines;
  19242. if (instance) {
  19243. var positionFunction = function (positions) {
  19244. var i = 0;
  19245. for (var l = 0; l < lines.length; l++) {
  19246. var points = lines[l];
  19247. for (var p = 0; p < points.length; p++) {
  19248. positions[i] = points[p].x;
  19249. positions[i + 1] = points[p].y;
  19250. positions[i + 2] = points[p].z;
  19251. i += 3;
  19252. }
  19253. }
  19254. };
  19255. instance.updateMeshPositions(positionFunction, false);
  19256. return instance;
  19257. }
  19258. // line system creation
  19259. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19260. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19261. vertexData.applyToMesh(lineSystem, options.updatable);
  19262. return lineSystem;
  19263. };
  19264. /**
  19265. * Creates a line mesh.
  19266. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19267. * 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.
  19268. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19269. * The parameter `points` is an array successive Vector3.
  19270. * 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
  19271. * When updating an instance, remember that only point positions can change, not the number of points.
  19272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19273. */
  19274. MeshBuilder.CreateLines = function (name, options, scene) {
  19275. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19276. return lines;
  19277. };
  19278. /**
  19279. * Creates a dashed line mesh.
  19280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19281. * 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.
  19282. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19283. * The parameter `points` is an array successive Vector3.
  19284. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19285. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19286. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19287. * 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
  19288. * When updating an instance, remember that only point positions can change, not the number of points.
  19289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19290. */
  19291. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19292. var points = options.points;
  19293. var instance = options.instance;
  19294. var gapSize = options.gapSize;
  19295. var dashNb = options.dashNb;
  19296. var dashSize = options.dashSize;
  19297. if (instance) {
  19298. var positionFunction = function (positions) {
  19299. var curvect = BABYLON.Vector3.Zero();
  19300. var nbSeg = positions.length / 6;
  19301. var lg = 0;
  19302. var nb = 0;
  19303. var shft = 0;
  19304. var dashshft = 0;
  19305. var curshft = 0;
  19306. var p = 0;
  19307. var i = 0;
  19308. var j = 0;
  19309. for (i = 0; i < points.length - 1; i++) {
  19310. points[i + 1].subtractToRef(points[i], curvect);
  19311. lg += curvect.length();
  19312. }
  19313. shft = lg / nbSeg;
  19314. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19315. for (i = 0; i < points.length - 1; i++) {
  19316. points[i + 1].subtractToRef(points[i], curvect);
  19317. nb = Math.floor(curvect.length() / shft);
  19318. curvect.normalize();
  19319. j = 0;
  19320. while (j < nb && p < positions.length) {
  19321. curshft = shft * j;
  19322. positions[p] = points[i].x + curshft * curvect.x;
  19323. positions[p + 1] = points[i].y + curshft * curvect.y;
  19324. positions[p + 2] = points[i].z + curshft * curvect.z;
  19325. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19326. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19327. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19328. p += 6;
  19329. j++;
  19330. }
  19331. }
  19332. while (p < positions.length) {
  19333. positions[p] = points[i].x;
  19334. positions[p + 1] = points[i].y;
  19335. positions[p + 2] = points[i].z;
  19336. p += 3;
  19337. }
  19338. };
  19339. instance.updateMeshPositions(positionFunction, false);
  19340. return instance;
  19341. }
  19342. // dashed lines creation
  19343. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19344. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19345. vertexData.applyToMesh(dashedLines, options.updatable);
  19346. dashedLines.dashSize = dashSize;
  19347. dashedLines.gapSize = gapSize;
  19348. return dashedLines;
  19349. };
  19350. /**
  19351. * Creates an extruded shape mesh.
  19352. * 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.
  19353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19354. *
  19355. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19356. * 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
  19357. * extruded along the Z axis.
  19358. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19359. * 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.
  19360. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19361. * 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
  19362. * 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
  19363. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19367. */
  19368. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19369. var path = options.path;
  19370. var shape = options.shape;
  19371. var scale = options.scale || 1;
  19372. var rotation = options.rotation || 0;
  19373. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19374. var updatable = options.updatable;
  19375. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19376. var instance = options.instance;
  19377. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19378. };
  19379. /**
  19380. * Creates an custom extruded shape mesh.
  19381. * 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.
  19382. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19383. *
  19384. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19385. * 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
  19386. * extruded along the Z axis.
  19387. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19388. * 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
  19389. * and the distance of this point from the begining of the path :
  19390. * ```rotationFunction = function(i, distance) {
  19391. * // do things
  19392. * return rotationValue; }```
  19393. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19394. * 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
  19395. * and the distance of this point from the begining of the path :
  19396. * ````scaleFunction = function(i, distance) {
  19397. * // do things
  19398. * return scaleValue;}```
  19399. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19400. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19401. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19402. * 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
  19403. * 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
  19404. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19405. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19406. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19408. */
  19409. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19410. var path = options.path;
  19411. var shape = options.shape;
  19412. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19413. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19414. var ribbonCloseArray = options.ribbonCloseArray || false;
  19415. var ribbonClosePath = options.ribbonClosePath || false;
  19416. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19417. var updatable = options.updatable;
  19418. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19419. var instance = options.instance;
  19420. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19421. };
  19422. /**
  19423. * Creates lathe mesh.
  19424. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19425. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19426. *
  19427. * 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
  19428. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19429. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19430. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19431. * 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.
  19432. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19433. * 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
  19434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19437. */
  19438. MeshBuilder.CreateLathe = function (name, options, scene) {
  19439. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19440. var closed = (options.closed === undefined) ? true : options.closed;
  19441. var shape = options.shape;
  19442. var radius = options.radius || 1;
  19443. var tessellation = options.tessellation || 64;
  19444. var updatable = options.updatable;
  19445. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19446. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19447. var pi2 = Math.PI * 2;
  19448. var paths = new Array();
  19449. var i = 0;
  19450. var p = 0;
  19451. var step = pi2 / tessellation * arc;
  19452. var rotated;
  19453. var path = new Array();
  19454. ;
  19455. for (i = 0; i <= tessellation; i++) {
  19456. var path = [];
  19457. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19458. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19459. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19460. }
  19461. for (p = 0; p < shape.length; p++) {
  19462. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19463. path.push(rotated);
  19464. }
  19465. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19466. 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));
  19467. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19468. }
  19469. paths.push(path);
  19470. }
  19471. // lathe ribbon
  19472. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19473. return lathe;
  19474. };
  19475. /**
  19476. * Creates a plane mesh.
  19477. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19478. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19479. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19480. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19484. */
  19485. MeshBuilder.CreatePlane = function (name, options, scene) {
  19486. var plane = new BABYLON.Mesh(name, scene);
  19487. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19488. vertexData.applyToMesh(plane, options.updatable);
  19489. if (options.sourcePlane) {
  19490. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19491. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19492. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19493. plane.rotate(vectorProduct, product);
  19494. }
  19495. return plane;
  19496. };
  19497. /**
  19498. * Creates a ground mesh.
  19499. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19500. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19501. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19503. */
  19504. MeshBuilder.CreateGround = function (name, options, scene) {
  19505. var ground = new BABYLON.GroundMesh(name, scene);
  19506. ground._setReady(false);
  19507. ground._subdivisions = options.subdivisions || 1;
  19508. ground._width = options.width || 1;
  19509. ground._height = options.height || 1;
  19510. ground._maxX = ground._width / 2;
  19511. ground._maxZ = ground._height / 2;
  19512. ground._minX = -ground._maxX;
  19513. ground._minZ = -ground._maxZ;
  19514. var vertexData = BABYLON.VertexData.CreateGround(options);
  19515. vertexData.applyToMesh(ground, options.updatable);
  19516. ground._setReady(true);
  19517. return ground;
  19518. };
  19519. /**
  19520. * Creates a tiled ground mesh.
  19521. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19522. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19523. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19524. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19525. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19526. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19527. * numbers of subdivisions on the ground width and height of each tile.
  19528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19529. */
  19530. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19531. var tiledGround = new BABYLON.Mesh(name, scene);
  19532. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19533. vertexData.applyToMesh(tiledGround, options.updatable);
  19534. return tiledGround;
  19535. };
  19536. /**
  19537. * Creates a ground mesh from a height map.
  19538. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19539. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19540. * The parameter `url` sets the URL of the height map image resource.
  19541. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19542. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19543. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19544. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19545. * 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).
  19546. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19547. * return; }```
  19548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19549. */
  19550. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19551. var width = options.width || 10;
  19552. var height = options.height || 10;
  19553. var subdivisions = options.subdivisions || 1;
  19554. var minHeight = options.minHeight;
  19555. var maxHeight = options.maxHeight || 10;
  19556. var updatable = options.updatable;
  19557. var onReady = options.onReady;
  19558. var ground = new BABYLON.GroundMesh(name, scene);
  19559. ground._subdivisions = subdivisions;
  19560. ground._width = width;
  19561. ground._height = height;
  19562. ground._maxX = ground._width / 2;
  19563. ground._maxZ = ground._height / 2;
  19564. ground._minX = -ground._maxX;
  19565. ground._minZ = -ground._maxZ;
  19566. ground._setReady(false);
  19567. var onload = function (img) {
  19568. // Getting height map data
  19569. var canvas = document.createElement("canvas");
  19570. var context = canvas.getContext("2d");
  19571. var bufferWidth = img.width;
  19572. var bufferHeight = img.height;
  19573. canvas.width = bufferWidth;
  19574. canvas.height = bufferHeight;
  19575. context.drawImage(img, 0, 0);
  19576. // Create VertexData from map data
  19577. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19578. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19579. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19580. width: width, height: height,
  19581. subdivisions: subdivisions,
  19582. minHeight: minHeight, maxHeight: maxHeight,
  19583. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19584. });
  19585. vertexData.applyToMesh(ground, updatable);
  19586. ground._setReady(true);
  19587. //execute ready callback, if set
  19588. if (onReady) {
  19589. onReady(ground);
  19590. }
  19591. };
  19592. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19593. return ground;
  19594. };
  19595. /**
  19596. * Creates a tube mesh.
  19597. * 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.
  19598. *
  19599. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19600. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19601. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19602. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19603. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19604. * 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.
  19605. * It must return a radius value (positive float) :
  19606. * ```var radiusFunction = function(i, distance) {
  19607. * // do things
  19608. * return radius; }```
  19609. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19610. * 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
  19611. * 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
  19612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19615. */
  19616. MeshBuilder.CreateTube = function (name, options, scene) {
  19617. var path = options.path;
  19618. var radius = options.radius || 1;
  19619. var tessellation = options.tessellation || 64;
  19620. var radiusFunction = options.radiusFunction;
  19621. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19622. var updatable = options.updatable;
  19623. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19624. var instance = options.instance;
  19625. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19626. // tube geometry
  19627. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19628. var tangents = path3D.getTangents();
  19629. var normals = path3D.getNormals();
  19630. var distances = path3D.getDistances();
  19631. var pi2 = Math.PI * 2;
  19632. var step = pi2 / tessellation * arc;
  19633. var returnRadius = function () { return radius; };
  19634. var radiusFunctionFinal = radiusFunction || returnRadius;
  19635. var circlePath;
  19636. var rad;
  19637. var normal;
  19638. var rotated;
  19639. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19640. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19641. for (var i = 0; i < path.length; i++) {
  19642. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19643. circlePath = Array(); // current circle array
  19644. normal = normals[i]; // current normal
  19645. for (var t = 0; t < tessellation; t++) {
  19646. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19647. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19648. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19649. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19650. circlePath[t] = rotated;
  19651. }
  19652. circlePaths[index] = circlePath;
  19653. index++;
  19654. }
  19655. // cap
  19656. var capPath = function (nbPoints, pathIndex) {
  19657. var pointCap = Array();
  19658. for (var i = 0; i < nbPoints; i++) {
  19659. pointCap.push(path[pathIndex]);
  19660. }
  19661. return pointCap;
  19662. };
  19663. switch (cap) {
  19664. case BABYLON.Mesh.NO_CAP:
  19665. break;
  19666. case BABYLON.Mesh.CAP_START:
  19667. circlePaths[0] = capPath(tessellation, 0);
  19668. circlePaths[1] = circlePaths[2].slice(0);
  19669. break;
  19670. case BABYLON.Mesh.CAP_END:
  19671. circlePaths[index] = circlePaths[index - 1].slice(0);
  19672. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19673. break;
  19674. case BABYLON.Mesh.CAP_ALL:
  19675. circlePaths[0] = capPath(tessellation, 0);
  19676. circlePaths[1] = circlePaths[2].slice(0);
  19677. circlePaths[index] = circlePaths[index - 1].slice(0);
  19678. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19679. break;
  19680. default:
  19681. break;
  19682. }
  19683. return circlePaths;
  19684. };
  19685. var path3D;
  19686. var pathArray;
  19687. if (instance) {
  19688. var arc = options.arc || instance.arc;
  19689. path3D = (instance.path3D).update(path);
  19690. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19691. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19692. instance.path3D = path3D;
  19693. instance.pathArray = pathArray;
  19694. instance.arc = arc;
  19695. return instance;
  19696. }
  19697. // tube creation
  19698. path3D = new BABYLON.Path3D(path);
  19699. var newPathArray = new Array();
  19700. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19701. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19702. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19703. tube.pathArray = pathArray;
  19704. tube.path3D = path3D;
  19705. tube.tessellation = tessellation;
  19706. tube.cap = cap;
  19707. tube.arc = options.arc;
  19708. return tube;
  19709. };
  19710. /**
  19711. * Creates a polyhedron mesh.
  19712. *
  19713. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19714. * 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
  19715. * to choose the wanted type.
  19716. * The parameter `size` (positive float, default 1) sets the polygon size.
  19717. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19718. * 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`.
  19719. * 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
  19720. * 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)`).
  19721. * 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
  19722. * 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.
  19723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19726. */
  19727. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19728. var polyhedron = new BABYLON.Mesh(name, scene);
  19729. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19730. vertexData.applyToMesh(polyhedron, options.updatable);
  19731. return polyhedron;
  19732. };
  19733. /**
  19734. * Creates a decal mesh.
  19735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19736. * 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.
  19737. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19738. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19739. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19740. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19741. */
  19742. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19743. var indices = sourceMesh.getIndices();
  19744. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19745. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19746. var position = options.position || BABYLON.Vector3.Zero();
  19747. var normal = options.normal || BABYLON.Vector3.Up();
  19748. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19749. var angle = options.angle || 0;
  19750. // Getting correct rotation
  19751. if (!normal) {
  19752. var target = new BABYLON.Vector3(0, 0, 1);
  19753. var camera = sourceMesh.getScene().activeCamera;
  19754. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19755. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19756. }
  19757. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19758. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19759. var pitch = Math.atan2(normal.y, len);
  19760. // Matrix
  19761. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19762. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19763. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19764. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19765. var vertexData = new BABYLON.VertexData();
  19766. vertexData.indices = [];
  19767. vertexData.positions = [];
  19768. vertexData.normals = [];
  19769. vertexData.uvs = [];
  19770. var currentVertexDataIndex = 0;
  19771. var extractDecalVector3 = function (indexId) {
  19772. var vertexId = indices[indexId];
  19773. var result = new BABYLON.PositionNormalVertex();
  19774. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19775. // Send vector to decal local world
  19776. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19777. // Get normal
  19778. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19779. return result;
  19780. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19781. var clip = function (vertices, axis) {
  19782. if (vertices.length === 0) {
  19783. return vertices;
  19784. }
  19785. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19786. var clipVertices = function (v0, v1) {
  19787. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19788. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19789. };
  19790. var result = new Array();
  19791. for (var index = 0; index < vertices.length; index += 3) {
  19792. var v1Out;
  19793. var v2Out;
  19794. var v3Out;
  19795. var total = 0;
  19796. var nV1, nV2, nV3, nV4;
  19797. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19798. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19799. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19800. v1Out = d1 > 0;
  19801. v2Out = d2 > 0;
  19802. v3Out = d3 > 0;
  19803. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19804. switch (total) {
  19805. case 0:
  19806. result.push(vertices[index]);
  19807. result.push(vertices[index + 1]);
  19808. result.push(vertices[index + 2]);
  19809. break;
  19810. case 1:
  19811. if (v1Out) {
  19812. nV1 = vertices[index + 1];
  19813. nV2 = vertices[index + 2];
  19814. nV3 = clipVertices(vertices[index], nV1);
  19815. nV4 = clipVertices(vertices[index], nV2);
  19816. }
  19817. if (v2Out) {
  19818. nV1 = vertices[index];
  19819. nV2 = vertices[index + 2];
  19820. nV3 = clipVertices(vertices[index + 1], nV1);
  19821. nV4 = clipVertices(vertices[index + 1], nV2);
  19822. result.push(nV3);
  19823. result.push(nV2.clone());
  19824. result.push(nV1.clone());
  19825. result.push(nV2.clone());
  19826. result.push(nV3.clone());
  19827. result.push(nV4);
  19828. break;
  19829. }
  19830. if (v3Out) {
  19831. nV1 = vertices[index];
  19832. nV2 = vertices[index + 1];
  19833. nV3 = clipVertices(vertices[index + 2], nV1);
  19834. nV4 = clipVertices(vertices[index + 2], nV2);
  19835. }
  19836. result.push(nV1.clone());
  19837. result.push(nV2.clone());
  19838. result.push(nV3);
  19839. result.push(nV4);
  19840. result.push(nV3.clone());
  19841. result.push(nV2.clone());
  19842. break;
  19843. case 2:
  19844. if (!v1Out) {
  19845. nV1 = vertices[index].clone();
  19846. nV2 = clipVertices(nV1, vertices[index + 1]);
  19847. nV3 = clipVertices(nV1, vertices[index + 2]);
  19848. result.push(nV1);
  19849. result.push(nV2);
  19850. result.push(nV3);
  19851. }
  19852. if (!v2Out) {
  19853. nV1 = vertices[index + 1].clone();
  19854. nV2 = clipVertices(nV1, vertices[index + 2]);
  19855. nV3 = clipVertices(nV1, vertices[index]);
  19856. result.push(nV1);
  19857. result.push(nV2);
  19858. result.push(nV3);
  19859. }
  19860. if (!v3Out) {
  19861. nV1 = vertices[index + 2].clone();
  19862. nV2 = clipVertices(nV1, vertices[index]);
  19863. nV3 = clipVertices(nV1, vertices[index + 1]);
  19864. result.push(nV1);
  19865. result.push(nV2);
  19866. result.push(nV3);
  19867. }
  19868. break;
  19869. case 3:
  19870. break;
  19871. }
  19872. }
  19873. return result;
  19874. };
  19875. for (var index = 0; index < indices.length; index += 3) {
  19876. var faceVertices = new Array();
  19877. faceVertices.push(extractDecalVector3(index));
  19878. faceVertices.push(extractDecalVector3(index + 1));
  19879. faceVertices.push(extractDecalVector3(index + 2));
  19880. // Clip
  19881. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  19882. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  19883. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  19884. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  19885. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  19886. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  19887. if (faceVertices.length === 0) {
  19888. continue;
  19889. }
  19890. // Add UVs and get back to world
  19891. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  19892. var vertex = faceVertices[vIndex];
  19893. //TODO check for Int32Array
  19894. vertexData.indices.push(currentVertexDataIndex);
  19895. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  19896. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  19897. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  19898. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  19899. currentVertexDataIndex++;
  19900. }
  19901. }
  19902. // Return mesh
  19903. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  19904. vertexData.applyToMesh(decal);
  19905. decal.position = position.clone();
  19906. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  19907. return decal;
  19908. };
  19909. // Privates
  19910. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  19911. // extrusion geometry
  19912. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  19913. var tangents = path3D.getTangents();
  19914. var normals = path3D.getNormals();
  19915. var binormals = path3D.getBinormals();
  19916. var distances = path3D.getDistances();
  19917. var angle = 0;
  19918. var returnScale = function () { return scale; };
  19919. var returnRotation = function () { return rotation; };
  19920. var rotate = custom ? rotateFunction : returnRotation;
  19921. var scl = custom ? scaleFunction : returnScale;
  19922. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19923. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19924. for (var i = 0; i < curve.length; i++) {
  19925. var shapePath = new Array();
  19926. var angleStep = rotate(i, distances[i]);
  19927. var scaleRatio = scl(i, distances[i]);
  19928. for (var p = 0; p < shape.length; p++) {
  19929. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  19930. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  19931. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  19932. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  19933. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  19934. shapePath[p] = rotated;
  19935. }
  19936. shapePaths[index] = shapePath;
  19937. angle += angleStep;
  19938. index++;
  19939. }
  19940. // cap
  19941. var capPath = function (shapePath) {
  19942. var pointCap = Array();
  19943. var barycenter = BABYLON.Vector3.Zero();
  19944. var i;
  19945. for (i = 0; i < shapePath.length; i++) {
  19946. barycenter.addInPlace(shapePath[i]);
  19947. }
  19948. barycenter.scaleInPlace(1 / shapePath.length);
  19949. for (i = 0; i < shapePath.length; i++) {
  19950. pointCap.push(barycenter);
  19951. }
  19952. return pointCap;
  19953. };
  19954. switch (cap) {
  19955. case BABYLON.Mesh.NO_CAP:
  19956. break;
  19957. case BABYLON.Mesh.CAP_START:
  19958. shapePaths[0] = capPath(shapePaths[2]);
  19959. shapePaths[1] = shapePaths[2].slice(0);
  19960. break;
  19961. case BABYLON.Mesh.CAP_END:
  19962. shapePaths[index] = shapePaths[index - 1];
  19963. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  19964. break;
  19965. case BABYLON.Mesh.CAP_ALL:
  19966. shapePaths[0] = capPath(shapePaths[2]);
  19967. shapePaths[1] = shapePaths[2].slice(0);
  19968. shapePaths[index] = shapePaths[index - 1];
  19969. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  19970. break;
  19971. default:
  19972. break;
  19973. }
  19974. return shapePaths;
  19975. };
  19976. var path3D;
  19977. var pathArray;
  19978. if (instance) {
  19979. path3D = (instance.path3D).update(curve);
  19980. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  19981. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  19982. return instance;
  19983. }
  19984. // extruded shape creation
  19985. path3D = new BABYLON.Path3D(curve);
  19986. var newShapePaths = new Array();
  19987. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19988. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  19989. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  19990. extrudedGeneric.pathArray = pathArray;
  19991. extrudedGeneric.path3D = path3D;
  19992. extrudedGeneric.cap = cap;
  19993. return extrudedGeneric;
  19994. };
  19995. return MeshBuilder;
  19996. }());
  19997. BABYLON.MeshBuilder = MeshBuilder;
  19998. })(BABYLON || (BABYLON = {}));
  19999. var BABYLON;
  20000. (function (BABYLON) {
  20001. var BaseTexture = (function () {
  20002. function BaseTexture(scene) {
  20003. this.hasAlpha = false;
  20004. this.getAlphaFromRGB = false;
  20005. this.level = 1;
  20006. this.coordinatesIndex = 0;
  20007. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20008. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20009. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20010. this.anisotropicFilteringLevel = 4;
  20011. this.isCube = false;
  20012. this.isRenderTarget = false;
  20013. this.animations = new Array();
  20014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20015. this._scene = scene;
  20016. this._scene.textures.push(this);
  20017. }
  20018. BaseTexture.prototype.getScene = function () {
  20019. return this._scene;
  20020. };
  20021. BaseTexture.prototype.getTextureMatrix = function () {
  20022. return null;
  20023. };
  20024. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20025. return null;
  20026. };
  20027. BaseTexture.prototype.getInternalTexture = function () {
  20028. return this._texture;
  20029. };
  20030. BaseTexture.prototype.isReady = function () {
  20031. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20032. return true;
  20033. }
  20034. if (this._texture) {
  20035. return this._texture.isReady;
  20036. }
  20037. return false;
  20038. };
  20039. BaseTexture.prototype.getSize = function () {
  20040. if (this._texture._width) {
  20041. return { width: this._texture._width, height: this._texture._height };
  20042. }
  20043. if (this._texture._size) {
  20044. return { width: this._texture._size, height: this._texture._size };
  20045. }
  20046. return { width: 0, height: 0 };
  20047. };
  20048. BaseTexture.prototype.getBaseSize = function () {
  20049. if (!this.isReady() || !this._texture)
  20050. return { width: 0, height: 0 };
  20051. if (this._texture._size) {
  20052. return { width: this._texture._size, height: this._texture._size };
  20053. }
  20054. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20055. };
  20056. BaseTexture.prototype.scale = function (ratio) {
  20057. };
  20058. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20059. get: function () {
  20060. return false;
  20061. },
  20062. enumerable: true,
  20063. configurable: true
  20064. });
  20065. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20066. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20067. for (var index = 0; index < texturesCache.length; index++) {
  20068. var texturesCacheEntry = texturesCache[index];
  20069. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20070. texturesCache.splice(index, 1);
  20071. return;
  20072. }
  20073. }
  20074. };
  20075. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20076. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20077. for (var index = 0; index < texturesCache.length; index++) {
  20078. var texturesCacheEntry = texturesCache[index];
  20079. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20080. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20081. texturesCacheEntry.references++;
  20082. return texturesCacheEntry;
  20083. }
  20084. }
  20085. }
  20086. return null;
  20087. };
  20088. BaseTexture.prototype.delayLoad = function () {
  20089. };
  20090. BaseTexture.prototype.clone = function () {
  20091. return null;
  20092. };
  20093. BaseTexture.prototype.releaseInternalTexture = function () {
  20094. if (this._texture) {
  20095. this._scene.getEngine().releaseInternalTexture(this._texture);
  20096. delete this._texture;
  20097. }
  20098. };
  20099. BaseTexture.prototype.dispose = function () {
  20100. // Animations
  20101. this.getScene().stopAnimation(this);
  20102. // Remove from scene
  20103. var index = this._scene.textures.indexOf(this);
  20104. if (index >= 0) {
  20105. this._scene.textures.splice(index, 1);
  20106. }
  20107. if (this._texture === undefined) {
  20108. return;
  20109. }
  20110. // Release
  20111. this.releaseInternalTexture();
  20112. // Callback
  20113. if (this.onDispose) {
  20114. this.onDispose();
  20115. }
  20116. };
  20117. BaseTexture.prototype.serialize = function () {
  20118. if (!this.name) {
  20119. return null;
  20120. }
  20121. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20122. // Animations
  20123. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20124. return serializationObject;
  20125. };
  20126. __decorate([
  20127. BABYLON.serialize()
  20128. ], BaseTexture.prototype, "name", void 0);
  20129. __decorate([
  20130. BABYLON.serialize()
  20131. ], BaseTexture.prototype, "hasAlpha", void 0);
  20132. __decorate([
  20133. BABYLON.serialize()
  20134. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20135. __decorate([
  20136. BABYLON.serialize()
  20137. ], BaseTexture.prototype, "level", void 0);
  20138. __decorate([
  20139. BABYLON.serialize()
  20140. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20141. __decorate([
  20142. BABYLON.serialize()
  20143. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20144. __decorate([
  20145. BABYLON.serialize()
  20146. ], BaseTexture.prototype, "wrapU", void 0);
  20147. __decorate([
  20148. BABYLON.serialize()
  20149. ], BaseTexture.prototype, "wrapV", void 0);
  20150. __decorate([
  20151. BABYLON.serialize()
  20152. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20153. __decorate([
  20154. BABYLON.serialize()
  20155. ], BaseTexture.prototype, "isCube", void 0);
  20156. __decorate([
  20157. BABYLON.serialize()
  20158. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20159. return BaseTexture;
  20160. }());
  20161. BABYLON.BaseTexture = BaseTexture;
  20162. })(BABYLON || (BABYLON = {}));
  20163. var BABYLON;
  20164. (function (BABYLON) {
  20165. var Texture = (function (_super) {
  20166. __extends(Texture, _super);
  20167. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20168. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20169. if (onLoad === void 0) { onLoad = null; }
  20170. if (onError === void 0) { onError = null; }
  20171. if (buffer === void 0) { buffer = null; }
  20172. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20173. _super.call(this, scene);
  20174. this.uOffset = 0;
  20175. this.vOffset = 0;
  20176. this.uScale = 1.0;
  20177. this.vScale = 1.0;
  20178. this.uAng = 0;
  20179. this.vAng = 0;
  20180. this.wAng = 0;
  20181. this.name = url;
  20182. this.url = url;
  20183. this._noMipmap = noMipmap;
  20184. this._invertY = invertY;
  20185. this._samplingMode = samplingMode;
  20186. this._buffer = buffer;
  20187. this._deleteBuffer = deleteBuffer;
  20188. if (!url) {
  20189. return;
  20190. }
  20191. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20192. if (!this._texture) {
  20193. if (!scene.useDelayedTextureLoading) {
  20194. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20195. if (deleteBuffer) {
  20196. delete this._buffer;
  20197. }
  20198. }
  20199. else {
  20200. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20201. this._delayedOnLoad = onLoad;
  20202. this._delayedOnError = onError;
  20203. }
  20204. }
  20205. else {
  20206. BABYLON.Tools.SetImmediate(function () {
  20207. if (onLoad) {
  20208. onLoad();
  20209. }
  20210. });
  20211. }
  20212. }
  20213. Texture.prototype.delayLoad = function () {
  20214. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20215. return;
  20216. }
  20217. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20218. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20219. if (!this._texture) {
  20220. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20221. if (this._deleteBuffer) {
  20222. delete this._buffer;
  20223. }
  20224. }
  20225. };
  20226. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20227. if (!this._texture) {
  20228. return;
  20229. }
  20230. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20231. };
  20232. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20233. x *= this.uScale;
  20234. y *= this.vScale;
  20235. x -= 0.5 * this.uScale;
  20236. y -= 0.5 * this.vScale;
  20237. z -= 0.5;
  20238. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20239. t.x += 0.5 * this.uScale + this.uOffset;
  20240. t.y += 0.5 * this.vScale + this.vOffset;
  20241. t.z += 0.5;
  20242. };
  20243. Texture.prototype.getTextureMatrix = function () {
  20244. if (this.uOffset === this._cachedUOffset &&
  20245. this.vOffset === this._cachedVOffset &&
  20246. this.uScale === this._cachedUScale &&
  20247. this.vScale === this._cachedVScale &&
  20248. this.uAng === this._cachedUAng &&
  20249. this.vAng === this._cachedVAng &&
  20250. this.wAng === this._cachedWAng) {
  20251. return this._cachedTextureMatrix;
  20252. }
  20253. this._cachedUOffset = this.uOffset;
  20254. this._cachedVOffset = this.vOffset;
  20255. this._cachedUScale = this.uScale;
  20256. this._cachedVScale = this.vScale;
  20257. this._cachedUAng = this.uAng;
  20258. this._cachedVAng = this.vAng;
  20259. this._cachedWAng = this.wAng;
  20260. if (!this._cachedTextureMatrix) {
  20261. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20262. this._rowGenerationMatrix = new BABYLON.Matrix();
  20263. this._t0 = BABYLON.Vector3.Zero();
  20264. this._t1 = BABYLON.Vector3.Zero();
  20265. this._t2 = BABYLON.Vector3.Zero();
  20266. }
  20267. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20268. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20269. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20270. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20271. this._t1.subtractInPlace(this._t0);
  20272. this._t2.subtractInPlace(this._t0);
  20273. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20274. this._cachedTextureMatrix.m[0] = this._t1.x;
  20275. this._cachedTextureMatrix.m[1] = this._t1.y;
  20276. this._cachedTextureMatrix.m[2] = this._t1.z;
  20277. this._cachedTextureMatrix.m[4] = this._t2.x;
  20278. this._cachedTextureMatrix.m[5] = this._t2.y;
  20279. this._cachedTextureMatrix.m[6] = this._t2.z;
  20280. this._cachedTextureMatrix.m[8] = this._t0.x;
  20281. this._cachedTextureMatrix.m[9] = this._t0.y;
  20282. this._cachedTextureMatrix.m[10] = this._t0.z;
  20283. return this._cachedTextureMatrix;
  20284. };
  20285. Texture.prototype.getReflectionTextureMatrix = function () {
  20286. if (this.uOffset === this._cachedUOffset &&
  20287. this.vOffset === this._cachedVOffset &&
  20288. this.uScale === this._cachedUScale &&
  20289. this.vScale === this._cachedVScale &&
  20290. this.coordinatesMode === this._cachedCoordinatesMode) {
  20291. return this._cachedTextureMatrix;
  20292. }
  20293. if (!this._cachedTextureMatrix) {
  20294. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20295. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20296. }
  20297. this._cachedCoordinatesMode = this.coordinatesMode;
  20298. switch (this.coordinatesMode) {
  20299. case Texture.PLANAR_MODE:
  20300. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20301. this._cachedTextureMatrix[0] = this.uScale;
  20302. this._cachedTextureMatrix[5] = this.vScale;
  20303. this._cachedTextureMatrix[12] = this.uOffset;
  20304. this._cachedTextureMatrix[13] = this.vOffset;
  20305. break;
  20306. case Texture.PROJECTION_MODE:
  20307. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20308. this._projectionModeMatrix.m[0] = 0.5;
  20309. this._projectionModeMatrix.m[5] = -0.5;
  20310. this._projectionModeMatrix.m[10] = 0.0;
  20311. this._projectionModeMatrix.m[12] = 0.5;
  20312. this._projectionModeMatrix.m[13] = 0.5;
  20313. this._projectionModeMatrix.m[14] = 1.0;
  20314. this._projectionModeMatrix.m[15] = 1.0;
  20315. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20316. break;
  20317. default:
  20318. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20319. break;
  20320. }
  20321. return this._cachedTextureMatrix;
  20322. };
  20323. Texture.prototype.clone = function () {
  20324. var _this = this;
  20325. return BABYLON.SerializationHelper.Clone(function () {
  20326. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20327. }, this);
  20328. };
  20329. // Statics
  20330. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20331. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20332. if (onLoad === void 0) { onLoad = null; }
  20333. if (onError === void 0) { onError = null; }
  20334. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20335. };
  20336. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20337. if (parsedTexture.isCube) {
  20338. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20339. }
  20340. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20341. return null;
  20342. }
  20343. var texture = BABYLON.SerializationHelper.Parse(function () {
  20344. if (parsedTexture.mirrorPlane) {
  20345. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20346. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20347. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20348. return mirrorTexture;
  20349. }
  20350. else if (parsedTexture.isRenderTarget) {
  20351. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20352. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20353. return renderTargetTexture;
  20354. }
  20355. else {
  20356. var texture;
  20357. if (parsedTexture.base64String) {
  20358. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20359. }
  20360. else {
  20361. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20362. }
  20363. return texture;
  20364. }
  20365. }, parsedTexture, scene);
  20366. // Animations
  20367. if (parsedTexture.animations) {
  20368. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20369. var parsedAnimation = parsedTexture.animations[animationIndex];
  20370. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20371. }
  20372. }
  20373. return texture;
  20374. };
  20375. // Constants
  20376. Texture.NEAREST_SAMPLINGMODE = 1;
  20377. Texture.BILINEAR_SAMPLINGMODE = 2;
  20378. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20379. Texture.EXPLICIT_MODE = 0;
  20380. Texture.SPHERICAL_MODE = 1;
  20381. Texture.PLANAR_MODE = 2;
  20382. Texture.CUBIC_MODE = 3;
  20383. Texture.PROJECTION_MODE = 4;
  20384. Texture.SKYBOX_MODE = 5;
  20385. Texture.INVCUBIC_MODE = 6;
  20386. Texture.EQUIRECTANGULAR_MODE = 7;
  20387. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20388. Texture.CLAMP_ADDRESSMODE = 0;
  20389. Texture.WRAP_ADDRESSMODE = 1;
  20390. Texture.MIRROR_ADDRESSMODE = 2;
  20391. __decorate([
  20392. BABYLON.serialize()
  20393. ], Texture.prototype, "url", void 0);
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], Texture.prototype, "uOffset", void 0);
  20397. __decorate([
  20398. BABYLON.serialize()
  20399. ], Texture.prototype, "vOffset", void 0);
  20400. __decorate([
  20401. BABYLON.serialize()
  20402. ], Texture.prototype, "uScale", void 0);
  20403. __decorate([
  20404. BABYLON.serialize()
  20405. ], Texture.prototype, "vScale", void 0);
  20406. __decorate([
  20407. BABYLON.serialize()
  20408. ], Texture.prototype, "uAng", void 0);
  20409. __decorate([
  20410. BABYLON.serialize()
  20411. ], Texture.prototype, "vAng", void 0);
  20412. __decorate([
  20413. BABYLON.serialize()
  20414. ], Texture.prototype, "wAng", void 0);
  20415. return Texture;
  20416. }(BABYLON.BaseTexture));
  20417. BABYLON.Texture = Texture;
  20418. })(BABYLON || (BABYLON = {}));
  20419. var BABYLON;
  20420. (function (BABYLON) {
  20421. var CubeTexture = (function (_super) {
  20422. __extends(CubeTexture, _super);
  20423. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20424. _super.call(this, scene);
  20425. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20426. this.name = rootUrl;
  20427. this.url = rootUrl;
  20428. this._noMipmap = noMipmap;
  20429. this.hasAlpha = false;
  20430. if (!rootUrl && !files) {
  20431. return;
  20432. }
  20433. this._texture = this._getFromCache(rootUrl, noMipmap);
  20434. if (!files) {
  20435. if (!extensions) {
  20436. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20437. }
  20438. files = [];
  20439. for (var index = 0; index < extensions.length; index++) {
  20440. files.push(rootUrl + extensions[index]);
  20441. }
  20442. this._extensions = extensions;
  20443. }
  20444. this._files = files;
  20445. if (!this._texture) {
  20446. if (!scene.useDelayedTextureLoading) {
  20447. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20448. }
  20449. else {
  20450. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20451. }
  20452. }
  20453. this.isCube = true;
  20454. this._textureMatrix = BABYLON.Matrix.Identity();
  20455. }
  20456. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20457. return new CubeTexture("", scene, null, noMipmap, files);
  20458. };
  20459. // Methods
  20460. CubeTexture.prototype.delayLoad = function () {
  20461. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20462. return;
  20463. }
  20464. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20465. this._texture = this._getFromCache(this.url, this._noMipmap);
  20466. if (!this._texture) {
  20467. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20468. }
  20469. };
  20470. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20471. return this._textureMatrix;
  20472. };
  20473. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20474. var texture = BABYLON.SerializationHelper.Parse(function () {
  20475. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20476. }, parsedTexture, scene);
  20477. // Animations
  20478. if (parsedTexture.animations) {
  20479. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20480. var parsedAnimation = parsedTexture.animations[animationIndex];
  20481. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20482. }
  20483. }
  20484. return texture;
  20485. };
  20486. CubeTexture.prototype.clone = function () {
  20487. var _this = this;
  20488. return BABYLON.SerializationHelper.Clone(function () {
  20489. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20490. }, this);
  20491. };
  20492. return CubeTexture;
  20493. }(BABYLON.BaseTexture));
  20494. BABYLON.CubeTexture = CubeTexture;
  20495. })(BABYLON || (BABYLON = {}));
  20496. var BABYLON;
  20497. (function (BABYLON) {
  20498. var RenderTargetTexture = (function (_super) {
  20499. __extends(RenderTargetTexture, _super);
  20500. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20501. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20502. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20503. if (isCube === void 0) { isCube = false; }
  20504. _super.call(this, null, scene, !generateMipMaps);
  20505. this.isCube = isCube;
  20506. this.renderList = new Array();
  20507. this.renderParticles = true;
  20508. this.renderSprites = false;
  20509. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20510. this._currentRefreshId = -1;
  20511. this._refreshRate = 1;
  20512. this.name = name;
  20513. this.isRenderTarget = true;
  20514. this._size = size;
  20515. this._generateMipMaps = generateMipMaps;
  20516. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20517. if (isCube) {
  20518. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20519. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20520. this._textureMatrix = BABYLON.Matrix.Identity();
  20521. }
  20522. else {
  20523. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20524. }
  20525. // Rendering groups
  20526. this._renderingManager = new BABYLON.RenderingManager(scene);
  20527. }
  20528. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20529. get: function () {
  20530. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20531. },
  20532. enumerable: true,
  20533. configurable: true
  20534. });
  20535. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20536. get: function () {
  20537. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20538. },
  20539. enumerable: true,
  20540. configurable: true
  20541. });
  20542. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20543. get: function () {
  20544. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20545. },
  20546. enumerable: true,
  20547. configurable: true
  20548. });
  20549. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20550. this._currentRefreshId = -1;
  20551. };
  20552. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20553. get: function () {
  20554. return this._refreshRate;
  20555. },
  20556. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20557. set: function (value) {
  20558. this._refreshRate = value;
  20559. this.resetRefreshCounter();
  20560. },
  20561. enumerable: true,
  20562. configurable: true
  20563. });
  20564. RenderTargetTexture.prototype._shouldRender = function () {
  20565. if (this._currentRefreshId === -1) {
  20566. this._currentRefreshId = 1;
  20567. return true;
  20568. }
  20569. if (this.refreshRate === this._currentRefreshId) {
  20570. this._currentRefreshId = 1;
  20571. return true;
  20572. }
  20573. this._currentRefreshId++;
  20574. return false;
  20575. };
  20576. RenderTargetTexture.prototype.isReady = function () {
  20577. if (!this.getScene().renderTargetsEnabled) {
  20578. return false;
  20579. }
  20580. return _super.prototype.isReady.call(this);
  20581. };
  20582. RenderTargetTexture.prototype.getRenderSize = function () {
  20583. return this._size;
  20584. };
  20585. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20586. get: function () {
  20587. return true;
  20588. },
  20589. enumerable: true,
  20590. configurable: true
  20591. });
  20592. RenderTargetTexture.prototype.scale = function (ratio) {
  20593. var newSize = this._size * ratio;
  20594. this.resize(newSize, this._generateMipMaps);
  20595. };
  20596. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20597. if (this.isCube) {
  20598. return this._textureMatrix;
  20599. }
  20600. return _super.prototype.getReflectionTextureMatrix.call(this);
  20601. };
  20602. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20603. this.releaseInternalTexture();
  20604. if (this.isCube) {
  20605. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20606. }
  20607. else {
  20608. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20609. }
  20610. };
  20611. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20612. var scene = this.getScene();
  20613. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20614. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20615. }
  20616. if (this._waitingRenderList) {
  20617. this.renderList = [];
  20618. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20619. var id = this._waitingRenderList[index];
  20620. this.renderList.push(scene.getMeshByID(id));
  20621. }
  20622. delete this._waitingRenderList;
  20623. }
  20624. if (this.renderList && this.renderList.length === 0) {
  20625. return;
  20626. }
  20627. // Prepare renderingManager
  20628. this._renderingManager.reset();
  20629. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20630. var sceneRenderId = scene.getRenderId();
  20631. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20632. var mesh = currentRenderList[meshIndex];
  20633. if (mesh) {
  20634. if (!mesh.isReady()) {
  20635. // Reset _currentRefreshId
  20636. this.resetRefreshCounter();
  20637. continue;
  20638. }
  20639. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20640. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20641. mesh._activate(sceneRenderId);
  20642. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20643. var subMesh = mesh.subMeshes[subIndex];
  20644. scene._activeIndices += subMesh.indexCount;
  20645. this._renderingManager.dispatch(subMesh);
  20646. }
  20647. }
  20648. }
  20649. }
  20650. if (this.isCube) {
  20651. for (var face = 0; face < 6; face++) {
  20652. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20653. scene.incrementRenderId();
  20654. scene.resetCachedMaterial();
  20655. }
  20656. }
  20657. else {
  20658. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20659. }
  20660. if (this.onAfterUnbind) {
  20661. this.onAfterUnbind();
  20662. }
  20663. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20664. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20665. }
  20666. scene.resetCachedMaterial();
  20667. };
  20668. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20669. var scene = this.getScene();
  20670. var engine = scene.getEngine();
  20671. // Bind
  20672. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20673. if (this.isCube) {
  20674. engine.bindFramebuffer(this._texture, faceIndex);
  20675. }
  20676. else {
  20677. engine.bindFramebuffer(this._texture);
  20678. }
  20679. }
  20680. if (this.onBeforeRender) {
  20681. this.onBeforeRender(faceIndex);
  20682. }
  20683. // Clear
  20684. if (this.onClear) {
  20685. this.onClear(engine);
  20686. }
  20687. else {
  20688. engine.clear(scene.clearColor, true, true);
  20689. }
  20690. if (!this._doNotChangeAspectRatio) {
  20691. scene.updateTransformMatrix(true);
  20692. }
  20693. // Render
  20694. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20695. if (useCameraPostProcess) {
  20696. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20697. }
  20698. if (!this._doNotChangeAspectRatio) {
  20699. scene.updateTransformMatrix(true);
  20700. }
  20701. if (this.onAfterRender) {
  20702. this.onAfterRender(faceIndex);
  20703. }
  20704. // Dump ?
  20705. if (dumpForDebug) {
  20706. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20707. }
  20708. // Unbind
  20709. if (!this.isCube || faceIndex === 5) {
  20710. if (this.isCube) {
  20711. if (faceIndex === 5) {
  20712. engine.generateMipMapsForCubemap(this._texture);
  20713. }
  20714. }
  20715. engine.unBindFramebuffer(this._texture, this.isCube);
  20716. }
  20717. };
  20718. RenderTargetTexture.prototype.clone = function () {
  20719. var textureSize = this.getSize();
  20720. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20721. // Base texture
  20722. newTexture.hasAlpha = this.hasAlpha;
  20723. newTexture.level = this.level;
  20724. // RenderTarget Texture
  20725. newTexture.coordinatesMode = this.coordinatesMode;
  20726. newTexture.renderList = this.renderList.slice(0);
  20727. return newTexture;
  20728. };
  20729. RenderTargetTexture.prototype.serialize = function () {
  20730. if (!this.name) {
  20731. return null;
  20732. }
  20733. var serializationObject = _super.prototype.serialize.call(this);
  20734. serializationObject.renderTargetSize = this.getRenderSize();
  20735. serializationObject.renderList = [];
  20736. for (var index = 0; index < this.renderList.length; index++) {
  20737. serializationObject.renderList.push(this.renderList[index].id);
  20738. }
  20739. return serializationObject;
  20740. };
  20741. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20742. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20743. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20744. return RenderTargetTexture;
  20745. }(BABYLON.Texture));
  20746. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20747. })(BABYLON || (BABYLON = {}));
  20748. var BABYLON;
  20749. (function (BABYLON) {
  20750. var ProceduralTexture = (function (_super) {
  20751. __extends(ProceduralTexture, _super);
  20752. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20753. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20754. if (isCube === void 0) { isCube = false; }
  20755. _super.call(this, null, scene, !generateMipMaps);
  20756. this.isCube = isCube;
  20757. this.isEnabled = true;
  20758. this._currentRefreshId = -1;
  20759. this._refreshRate = 1;
  20760. this._vertexDeclaration = [2];
  20761. this._vertexStrideSize = 2 * 4;
  20762. this._uniforms = new Array();
  20763. this._samplers = new Array();
  20764. this._textures = new Array();
  20765. this._floats = new Array();
  20766. this._floatsArrays = {};
  20767. this._colors3 = new Array();
  20768. this._colors4 = new Array();
  20769. this._vectors2 = new Array();
  20770. this._vectors3 = new Array();
  20771. this._matrices = new Array();
  20772. this._fallbackTextureUsed = false;
  20773. scene._proceduralTextures.push(this);
  20774. this.name = name;
  20775. this.isRenderTarget = true;
  20776. this._size = size;
  20777. this._generateMipMaps = generateMipMaps;
  20778. this.setFragment(fragment);
  20779. this._fallbackTexture = fallbackTexture;
  20780. if (isCube) {
  20781. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20782. this.setFloat("face", 0);
  20783. }
  20784. else {
  20785. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20786. }
  20787. // VBO
  20788. var vertices = [];
  20789. vertices.push(1, 1);
  20790. vertices.push(-1, 1);
  20791. vertices.push(-1, -1);
  20792. vertices.push(1, -1);
  20793. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20794. // Indices
  20795. var indices = [];
  20796. indices.push(0);
  20797. indices.push(1);
  20798. indices.push(2);
  20799. indices.push(0);
  20800. indices.push(2);
  20801. indices.push(3);
  20802. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20803. }
  20804. ProceduralTexture.prototype.reset = function () {
  20805. if (this._effect === undefined) {
  20806. return;
  20807. }
  20808. var engine = this.getScene().getEngine();
  20809. engine._releaseEffect(this._effect);
  20810. };
  20811. ProceduralTexture.prototype.isReady = function () {
  20812. var _this = this;
  20813. var engine = this.getScene().getEngine();
  20814. var shaders;
  20815. if (!this._fragment) {
  20816. return false;
  20817. }
  20818. if (this._fallbackTextureUsed) {
  20819. return true;
  20820. }
  20821. if (this._fragment.fragmentElement !== undefined) {
  20822. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20823. }
  20824. else {
  20825. shaders = { vertex: "procedural", fragment: this._fragment };
  20826. }
  20827. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20828. _this.releaseInternalTexture();
  20829. if (_this._fallbackTexture) {
  20830. _this._texture = _this._fallbackTexture._texture;
  20831. _this._texture.references++;
  20832. }
  20833. _this._fallbackTextureUsed = true;
  20834. });
  20835. return this._effect.isReady();
  20836. };
  20837. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20838. this._currentRefreshId = -1;
  20839. };
  20840. ProceduralTexture.prototype.setFragment = function (fragment) {
  20841. this._fragment = fragment;
  20842. };
  20843. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20844. get: function () {
  20845. return this._refreshRate;
  20846. },
  20847. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20848. set: function (value) {
  20849. this._refreshRate = value;
  20850. this.resetRefreshCounter();
  20851. },
  20852. enumerable: true,
  20853. configurable: true
  20854. });
  20855. ProceduralTexture.prototype._shouldRender = function () {
  20856. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20857. return false;
  20858. }
  20859. if (this._fallbackTextureUsed) {
  20860. return false;
  20861. }
  20862. if (this._currentRefreshId === -1) {
  20863. this._currentRefreshId = 1;
  20864. return true;
  20865. }
  20866. if (this.refreshRate === this._currentRefreshId) {
  20867. this._currentRefreshId = 1;
  20868. return true;
  20869. }
  20870. this._currentRefreshId++;
  20871. return false;
  20872. };
  20873. ProceduralTexture.prototype.getRenderSize = function () {
  20874. return this._size;
  20875. };
  20876. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  20877. if (this._fallbackTextureUsed) {
  20878. return;
  20879. }
  20880. this.releaseInternalTexture();
  20881. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20882. };
  20883. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  20884. if (this._uniforms.indexOf(uniformName) === -1) {
  20885. this._uniforms.push(uniformName);
  20886. }
  20887. };
  20888. ProceduralTexture.prototype.setTexture = function (name, texture) {
  20889. if (this._samplers.indexOf(name) === -1) {
  20890. this._samplers.push(name);
  20891. }
  20892. this._textures[name] = texture;
  20893. return this;
  20894. };
  20895. ProceduralTexture.prototype.setFloat = function (name, value) {
  20896. this._checkUniform(name);
  20897. this._floats[name] = value;
  20898. return this;
  20899. };
  20900. ProceduralTexture.prototype.setFloats = function (name, value) {
  20901. this._checkUniform(name);
  20902. this._floatsArrays[name] = value;
  20903. return this;
  20904. };
  20905. ProceduralTexture.prototype.setColor3 = function (name, value) {
  20906. this._checkUniform(name);
  20907. this._colors3[name] = value;
  20908. return this;
  20909. };
  20910. ProceduralTexture.prototype.setColor4 = function (name, value) {
  20911. this._checkUniform(name);
  20912. this._colors4[name] = value;
  20913. return this;
  20914. };
  20915. ProceduralTexture.prototype.setVector2 = function (name, value) {
  20916. this._checkUniform(name);
  20917. this._vectors2[name] = value;
  20918. return this;
  20919. };
  20920. ProceduralTexture.prototype.setVector3 = function (name, value) {
  20921. this._checkUniform(name);
  20922. this._vectors3[name] = value;
  20923. return this;
  20924. };
  20925. ProceduralTexture.prototype.setMatrix = function (name, value) {
  20926. this._checkUniform(name);
  20927. this._matrices[name] = value;
  20928. return this;
  20929. };
  20930. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  20931. var scene = this.getScene();
  20932. var engine = scene.getEngine();
  20933. // Render
  20934. engine.enableEffect(this._effect);
  20935. engine.setState(false);
  20936. // Texture
  20937. for (var name in this._textures) {
  20938. this._effect.setTexture(name, this._textures[name]);
  20939. }
  20940. // Float
  20941. for (name in this._floats) {
  20942. this._effect.setFloat(name, this._floats[name]);
  20943. }
  20944. // Floats
  20945. for (name in this._floatsArrays) {
  20946. this._effect.setArray(name, this._floatsArrays[name]);
  20947. }
  20948. // Color3
  20949. for (name in this._colors3) {
  20950. this._effect.setColor3(name, this._colors3[name]);
  20951. }
  20952. // Color4
  20953. for (name in this._colors4) {
  20954. var color = this._colors4[name];
  20955. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20956. }
  20957. // Vector2
  20958. for (name in this._vectors2) {
  20959. this._effect.setVector2(name, this._vectors2[name]);
  20960. }
  20961. // Vector3
  20962. for (name in this._vectors3) {
  20963. this._effect.setVector3(name, this._vectors3[name]);
  20964. }
  20965. // Matrix
  20966. for (name in this._matrices) {
  20967. this._effect.setMatrix(name, this._matrices[name]);
  20968. }
  20969. // VBOs
  20970. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20971. if (this.isCube) {
  20972. for (var face = 0; face < 6; face++) {
  20973. engine.bindFramebuffer(this._texture, face);
  20974. this._effect.setFloat("face", face);
  20975. // Clear
  20976. engine.clear(scene.clearColor, true, true);
  20977. // Draw order
  20978. engine.draw(true, 0, 6);
  20979. // Mipmaps
  20980. if (face === 5) {
  20981. engine.generateMipMapsForCubemap(this._texture);
  20982. }
  20983. }
  20984. }
  20985. else {
  20986. engine.bindFramebuffer(this._texture);
  20987. // Clear
  20988. engine.clear(scene.clearColor, true, true);
  20989. // Draw order
  20990. engine.draw(true, 0, 6);
  20991. }
  20992. // Unbind
  20993. engine.unBindFramebuffer(this._texture, this.isCube);
  20994. if (this.onGenerated) {
  20995. this.onGenerated();
  20996. }
  20997. };
  20998. ProceduralTexture.prototype.clone = function () {
  20999. var textureSize = this.getSize();
  21000. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21001. // Base texture
  21002. newTexture.hasAlpha = this.hasAlpha;
  21003. newTexture.level = this.level;
  21004. // RenderTarget Texture
  21005. newTexture.coordinatesMode = this.coordinatesMode;
  21006. return newTexture;
  21007. };
  21008. ProceduralTexture.prototype.dispose = function () {
  21009. var index = this.getScene()._proceduralTextures.indexOf(this);
  21010. if (index >= 0) {
  21011. this.getScene()._proceduralTextures.splice(index, 1);
  21012. }
  21013. _super.prototype.dispose.call(this);
  21014. };
  21015. return ProceduralTexture;
  21016. }(BABYLON.Texture));
  21017. BABYLON.ProceduralTexture = ProceduralTexture;
  21018. })(BABYLON || (BABYLON = {}));
  21019. var BABYLON;
  21020. (function (BABYLON) {
  21021. var MirrorTexture = (function (_super) {
  21022. __extends(MirrorTexture, _super);
  21023. function MirrorTexture(name, size, scene, generateMipMaps) {
  21024. var _this = this;
  21025. _super.call(this, name, size, scene, generateMipMaps, true);
  21026. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21027. this._transformMatrix = BABYLON.Matrix.Zero();
  21028. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21029. this.onBeforeRender = function () {
  21030. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21031. _this._savedViewMatrix = scene.getViewMatrix();
  21032. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21033. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21034. scene.clipPlane = _this.mirrorPlane;
  21035. scene.getEngine().cullBackFaces = false;
  21036. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21037. };
  21038. this.onAfterRender = function () {
  21039. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21040. scene.getEngine().cullBackFaces = true;
  21041. scene._mirroredCameraPosition = null;
  21042. delete scene.clipPlane;
  21043. };
  21044. }
  21045. MirrorTexture.prototype.clone = function () {
  21046. var textureSize = this.getSize();
  21047. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21048. // Base texture
  21049. newTexture.hasAlpha = this.hasAlpha;
  21050. newTexture.level = this.level;
  21051. // Mirror Texture
  21052. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21053. newTexture.renderList = this.renderList.slice(0);
  21054. return newTexture;
  21055. };
  21056. MirrorTexture.prototype.serialize = function () {
  21057. if (!this.name) {
  21058. return null;
  21059. }
  21060. var serializationObject = _super.prototype.serialize.call(this);
  21061. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21062. return serializationObject;
  21063. };
  21064. return MirrorTexture;
  21065. }(BABYLON.RenderTargetTexture));
  21066. BABYLON.MirrorTexture = MirrorTexture;
  21067. })(BABYLON || (BABYLON = {}));
  21068. var BABYLON;
  21069. (function (BABYLON) {
  21070. /**
  21071. * Creates a refraction texture used by refraction channel of the standard material.
  21072. * @param name the texture name
  21073. * @param size size of the underlying texture
  21074. * @param scene root scene
  21075. */
  21076. var RefractionTexture = (function (_super) {
  21077. __extends(RefractionTexture, _super);
  21078. function RefractionTexture(name, size, scene, generateMipMaps) {
  21079. var _this = this;
  21080. _super.call(this, name, size, scene, generateMipMaps, true);
  21081. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21082. this.depth = 2.0;
  21083. this.onBeforeRender = function () {
  21084. scene.clipPlane = _this.refractionPlane;
  21085. };
  21086. this.onAfterRender = function () {
  21087. delete scene.clipPlane;
  21088. };
  21089. }
  21090. RefractionTexture.prototype.clone = function () {
  21091. var textureSize = this.getSize();
  21092. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21093. // Base texture
  21094. newTexture.hasAlpha = this.hasAlpha;
  21095. newTexture.level = this.level;
  21096. // Refraction Texture
  21097. newTexture.refractionPlane = this.refractionPlane.clone();
  21098. newTexture.renderList = this.renderList.slice(0);
  21099. newTexture.depth = this.depth;
  21100. return newTexture;
  21101. };
  21102. RefractionTexture.prototype.serialize = function () {
  21103. if (!this.name) {
  21104. return null;
  21105. }
  21106. var serializationObject = _super.prototype.serialize.call(this);
  21107. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21108. serializationObject.depth = this.depth;
  21109. return serializationObject;
  21110. };
  21111. return RefractionTexture;
  21112. }(BABYLON.RenderTargetTexture));
  21113. BABYLON.RefractionTexture = RefractionTexture;
  21114. })(BABYLON || (BABYLON = {}));
  21115. var BABYLON;
  21116. (function (BABYLON) {
  21117. var DynamicTexture = (function (_super) {
  21118. __extends(DynamicTexture, _super);
  21119. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21121. _super.call(this, null, scene, !generateMipMaps);
  21122. this.name = name;
  21123. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21124. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21125. this._generateMipMaps = generateMipMaps;
  21126. if (options.getContext) {
  21127. this._canvas = options;
  21128. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21129. }
  21130. else {
  21131. this._canvas = document.createElement("canvas");
  21132. if (options.width) {
  21133. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21134. }
  21135. else {
  21136. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21137. }
  21138. }
  21139. var textureSize = this.getSize();
  21140. this._canvas.width = textureSize.width;
  21141. this._canvas.height = textureSize.height;
  21142. this._context = this._canvas.getContext("2d");
  21143. }
  21144. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21145. get: function () {
  21146. return true;
  21147. },
  21148. enumerable: true,
  21149. configurable: true
  21150. });
  21151. DynamicTexture.prototype.scale = function (ratio) {
  21152. var textureSize = this.getSize();
  21153. textureSize.width *= ratio;
  21154. textureSize.height *= ratio;
  21155. this._canvas.width = textureSize.width;
  21156. this._canvas.height = textureSize.height;
  21157. this.releaseInternalTexture();
  21158. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21159. };
  21160. DynamicTexture.prototype.getContext = function () {
  21161. return this._context;
  21162. };
  21163. DynamicTexture.prototype.clear = function () {
  21164. var size = this.getSize();
  21165. this._context.fillRect(0, 0, size.width, size.height);
  21166. };
  21167. DynamicTexture.prototype.update = function (invertY) {
  21168. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21169. };
  21170. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21171. if (update === void 0) { update = true; }
  21172. var size = this.getSize();
  21173. if (clearColor) {
  21174. this._context.fillStyle = clearColor;
  21175. this._context.fillRect(0, 0, size.width, size.height);
  21176. }
  21177. this._context.font = font;
  21178. if (x === null) {
  21179. var textSize = this._context.measureText(text);
  21180. x = (size.width - textSize.width) / 2;
  21181. }
  21182. this._context.fillStyle = color;
  21183. this._context.fillText(text, x, y);
  21184. if (update) {
  21185. this.update(invertY);
  21186. }
  21187. };
  21188. DynamicTexture.prototype.clone = function () {
  21189. var textureSize = this.getSize();
  21190. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21191. // Base texture
  21192. newTexture.hasAlpha = this.hasAlpha;
  21193. newTexture.level = this.level;
  21194. // Dynamic Texture
  21195. newTexture.wrapU = this.wrapU;
  21196. newTexture.wrapV = this.wrapV;
  21197. return newTexture;
  21198. };
  21199. return DynamicTexture;
  21200. }(BABYLON.Texture));
  21201. BABYLON.DynamicTexture = DynamicTexture;
  21202. })(BABYLON || (BABYLON = {}));
  21203. var BABYLON;
  21204. (function (BABYLON) {
  21205. var VideoTexture = (function (_super) {
  21206. __extends(VideoTexture, _super);
  21207. /**
  21208. * Creates a video texture.
  21209. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21210. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21211. * @param {BABYLON.Scene} scene is obviously the current scene.
  21212. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21213. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21214. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21215. */
  21216. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21217. var _this = this;
  21218. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21219. if (invertY === void 0) { invertY = false; }
  21220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21221. _super.call(this, null, scene, !generateMipMaps, invertY);
  21222. this._autoLaunch = true;
  21223. var urls;
  21224. this.name = name;
  21225. if (urlsOrVideo instanceof HTMLVideoElement) {
  21226. this.video = urlsOrVideo;
  21227. }
  21228. else {
  21229. urls = urlsOrVideo;
  21230. this.video = document.createElement("video");
  21231. this.video.autoplay = false;
  21232. this.video.loop = true;
  21233. }
  21234. this._generateMipMaps = generateMipMaps;
  21235. this._samplingMode = samplingMode;
  21236. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21237. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21238. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21239. }
  21240. else {
  21241. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21242. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21243. this._generateMipMaps = false;
  21244. }
  21245. if (urls) {
  21246. this.video.addEventListener("canplaythrough", function () {
  21247. _this._createTexture();
  21248. });
  21249. urls.forEach(function (url) {
  21250. var source = document.createElement("source");
  21251. source.src = url;
  21252. _this.video.appendChild(source);
  21253. });
  21254. }
  21255. else {
  21256. this._createTexture();
  21257. }
  21258. this._lastUpdate = BABYLON.Tools.Now;
  21259. }
  21260. VideoTexture.prototype._createTexture = function () {
  21261. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21262. this._texture.isReady = true;
  21263. };
  21264. VideoTexture.prototype.update = function () {
  21265. if (this._autoLaunch) {
  21266. this._autoLaunch = false;
  21267. this.video.play();
  21268. }
  21269. var now = BABYLON.Tools.Now;
  21270. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21271. return false;
  21272. }
  21273. this._lastUpdate = now;
  21274. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21275. return true;
  21276. };
  21277. return VideoTexture;
  21278. }(BABYLON.Texture));
  21279. BABYLON.VideoTexture = VideoTexture;
  21280. })(BABYLON || (BABYLON = {}));
  21281. var BABYLON;
  21282. (function (BABYLON) {
  21283. var CustomProceduralTexture = (function (_super) {
  21284. __extends(CustomProceduralTexture, _super);
  21285. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21286. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21287. this._animate = true;
  21288. this._time = 0;
  21289. this._texturePath = texturePath;
  21290. //Try to load json
  21291. this.loadJson(texturePath);
  21292. this.refreshRate = 1;
  21293. }
  21294. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21295. var _this = this;
  21296. var that = this;
  21297. function noConfigFile() {
  21298. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21299. try {
  21300. that.setFragment(that._texturePath);
  21301. }
  21302. catch (ex) {
  21303. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21304. }
  21305. }
  21306. var configFileUrl = jsonUrl + "/config.json";
  21307. var xhr = new XMLHttpRequest();
  21308. xhr.open("GET", configFileUrl, true);
  21309. xhr.addEventListener("load", function () {
  21310. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21311. try {
  21312. _this._config = JSON.parse(xhr.response);
  21313. _this.updateShaderUniforms();
  21314. _this.updateTextures();
  21315. _this.setFragment(_this._texturePath + "/custom");
  21316. _this._animate = _this._config.animate;
  21317. _this.refreshRate = _this._config.refreshrate;
  21318. }
  21319. catch (ex) {
  21320. noConfigFile();
  21321. }
  21322. }
  21323. else {
  21324. noConfigFile();
  21325. }
  21326. }, false);
  21327. xhr.addEventListener("error", function () {
  21328. noConfigFile();
  21329. }, false);
  21330. try {
  21331. xhr.send();
  21332. }
  21333. catch (ex) {
  21334. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21335. }
  21336. };
  21337. CustomProceduralTexture.prototype.isReady = function () {
  21338. if (!_super.prototype.isReady.call(this)) {
  21339. return false;
  21340. }
  21341. for (var name in this._textures) {
  21342. var texture = this._textures[name];
  21343. if (!texture.isReady()) {
  21344. return false;
  21345. }
  21346. }
  21347. return true;
  21348. };
  21349. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21350. if (this._animate) {
  21351. this._time += this.getScene().getAnimationRatio() * 0.03;
  21352. this.updateShaderUniforms();
  21353. }
  21354. _super.prototype.render.call(this, useCameraPostProcess);
  21355. };
  21356. CustomProceduralTexture.prototype.updateTextures = function () {
  21357. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21358. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21359. }
  21360. };
  21361. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21362. if (this._config) {
  21363. for (var j = 0; j < this._config.uniforms.length; j++) {
  21364. var uniform = this._config.uniforms[j];
  21365. switch (uniform.type) {
  21366. case "float":
  21367. this.setFloat(uniform.name, uniform.value);
  21368. break;
  21369. case "color3":
  21370. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21371. break;
  21372. case "color4":
  21373. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21374. break;
  21375. case "vector2":
  21376. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21377. break;
  21378. case "vector3":
  21379. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21380. break;
  21381. }
  21382. }
  21383. }
  21384. this.setFloat("time", this._time);
  21385. };
  21386. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21387. get: function () {
  21388. return this._animate;
  21389. },
  21390. set: function (value) {
  21391. this._animate = value;
  21392. },
  21393. enumerable: true,
  21394. configurable: true
  21395. });
  21396. return CustomProceduralTexture;
  21397. }(BABYLON.ProceduralTexture));
  21398. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21399. })(BABYLON || (BABYLON = {}));
  21400. var BABYLON;
  21401. (function (BABYLON) {
  21402. var EffectFallbacks = (function () {
  21403. function EffectFallbacks() {
  21404. this._defines = {};
  21405. this._currentRank = 32;
  21406. this._maxRank = -1;
  21407. }
  21408. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21409. if (!this._defines[rank]) {
  21410. if (rank < this._currentRank) {
  21411. this._currentRank = rank;
  21412. }
  21413. if (rank > this._maxRank) {
  21414. this._maxRank = rank;
  21415. }
  21416. this._defines[rank] = new Array();
  21417. }
  21418. this._defines[rank].push(define);
  21419. };
  21420. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21421. this._meshRank = rank;
  21422. this._mesh = mesh;
  21423. if (rank > this._maxRank) {
  21424. this._maxRank = rank;
  21425. }
  21426. };
  21427. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21428. get: function () {
  21429. return this._currentRank <= this._maxRank;
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21435. var currentFallbacks = this._defines[this._currentRank];
  21436. for (var index = 0; index < currentFallbacks.length; index++) {
  21437. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21438. }
  21439. if (this._mesh && this._currentRank === this._meshRank) {
  21440. this._mesh.computeBonesUsingShaders = false;
  21441. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21442. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21443. }
  21444. this._currentRank++;
  21445. return currentDefines;
  21446. };
  21447. return EffectFallbacks;
  21448. }());
  21449. BABYLON.EffectFallbacks = EffectFallbacks;
  21450. var Effect = (function () {
  21451. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21452. var _this = this;
  21453. this._isReady = false;
  21454. this._compilationError = "";
  21455. this._valueCache = [];
  21456. this._engine = engine;
  21457. this.name = baseName;
  21458. this.defines = defines;
  21459. this._uniformsNames = uniformsNames.concat(samplers);
  21460. this._samplers = samplers;
  21461. this._attributesNames = attributesNames;
  21462. this.onError = onError;
  21463. this.onCompiled = onCompiled;
  21464. var vertexSource;
  21465. var fragmentSource;
  21466. if (baseName.vertexElement) {
  21467. vertexSource = document.getElementById(baseName.vertexElement);
  21468. if (!vertexSource) {
  21469. vertexSource = baseName.vertexElement;
  21470. }
  21471. }
  21472. else {
  21473. vertexSource = baseName.vertex || baseName;
  21474. }
  21475. if (baseName.fragmentElement) {
  21476. fragmentSource = document.getElementById(baseName.fragmentElement);
  21477. if (!fragmentSource) {
  21478. fragmentSource = baseName.fragmentElement;
  21479. }
  21480. }
  21481. else {
  21482. fragmentSource = baseName.fragment || baseName;
  21483. }
  21484. this._loadVertexShader(vertexSource, function (vertexCode) {
  21485. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21486. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21487. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21488. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21489. });
  21490. });
  21491. });
  21492. });
  21493. }
  21494. // Properties
  21495. Effect.prototype.isReady = function () {
  21496. return this._isReady;
  21497. };
  21498. Effect.prototype.getProgram = function () {
  21499. return this._program;
  21500. };
  21501. Effect.prototype.getAttributesNames = function () {
  21502. return this._attributesNames;
  21503. };
  21504. Effect.prototype.getAttributeLocation = function (index) {
  21505. return this._attributes[index];
  21506. };
  21507. Effect.prototype.getAttributeLocationByName = function (name) {
  21508. var index = this._attributesNames.indexOf(name);
  21509. return this._attributes[index];
  21510. };
  21511. Effect.prototype.getAttributesCount = function () {
  21512. return this._attributes.length;
  21513. };
  21514. Effect.prototype.getUniformIndex = function (uniformName) {
  21515. return this._uniformsNames.indexOf(uniformName);
  21516. };
  21517. Effect.prototype.getUniform = function (uniformName) {
  21518. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21519. };
  21520. Effect.prototype.getSamplers = function () {
  21521. return this._samplers;
  21522. };
  21523. Effect.prototype.getCompilationError = function () {
  21524. return this._compilationError;
  21525. };
  21526. // Methods
  21527. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21528. // DOM element ?
  21529. if (vertex instanceof HTMLElement) {
  21530. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21531. callback(vertexCode);
  21532. return;
  21533. }
  21534. // Is in local store ?
  21535. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21536. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21537. return;
  21538. }
  21539. var vertexShaderUrl;
  21540. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21541. vertexShaderUrl = vertex;
  21542. }
  21543. else {
  21544. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21545. }
  21546. // Vertex shader
  21547. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21548. };
  21549. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21550. // DOM element ?
  21551. if (fragment instanceof HTMLElement) {
  21552. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21553. callback(fragmentCode);
  21554. return;
  21555. }
  21556. // Is in local store ?
  21557. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21558. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21559. return;
  21560. }
  21561. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21562. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21563. return;
  21564. }
  21565. var fragmentShaderUrl;
  21566. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21567. fragmentShaderUrl = fragment;
  21568. }
  21569. else {
  21570. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21571. }
  21572. // Fragment shader
  21573. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21574. };
  21575. Effect.prototype._dumpShadersName = function () {
  21576. if (this.name.vertexElement) {
  21577. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21578. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21579. }
  21580. else if (this.name.vertex) {
  21581. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21582. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21583. }
  21584. else {
  21585. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21586. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21587. }
  21588. };
  21589. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21590. var _this = this;
  21591. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21592. var match = regex.exec(sourceCode);
  21593. var returnValue = new String(sourceCode);
  21594. while (match != null) {
  21595. var includeFile = match[1];
  21596. if (Effect.IncludesShadersStore[includeFile]) {
  21597. // Substitution
  21598. var includeContent = Effect.IncludesShadersStore[includeFile];
  21599. if (match[2]) {
  21600. var splits = match[3].split(",");
  21601. for (var index = 0; index < splits.length; index += 2) {
  21602. var source = new RegExp(splits[index], "g");
  21603. var dest = splits[index + 1];
  21604. includeContent = includeContent.replace(source, dest);
  21605. }
  21606. }
  21607. if (match[4]) {
  21608. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21609. }
  21610. // Replace
  21611. returnValue = returnValue.replace(match[0], includeContent);
  21612. }
  21613. else {
  21614. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21615. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21616. Effect.IncludesShadersStore[includeFile] = fileContent;
  21617. _this._processIncludes(returnValue, callback);
  21618. });
  21619. return;
  21620. }
  21621. match = regex.exec(sourceCode);
  21622. }
  21623. callback(returnValue);
  21624. };
  21625. Effect.prototype._processPrecision = function (source) {
  21626. if (source.indexOf("precision highp float") === -1) {
  21627. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21628. source = "precision mediump float;\n" + source;
  21629. }
  21630. else {
  21631. source = "precision highp float;\n" + source;
  21632. }
  21633. }
  21634. else {
  21635. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21636. source = source.replace("precision highp float", "precision mediump float");
  21637. }
  21638. }
  21639. return source;
  21640. };
  21641. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21642. try {
  21643. var engine = this._engine;
  21644. // Precision
  21645. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21646. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21647. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21648. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21649. this._attributes = engine.getAttributes(this._program, attributesNames);
  21650. for (var index = 0; index < this._samplers.length; index++) {
  21651. var sampler = this.getUniform(this._samplers[index]);
  21652. if (sampler == null) {
  21653. this._samplers.splice(index, 1);
  21654. index--;
  21655. }
  21656. }
  21657. engine.bindSamplers(this);
  21658. this._isReady = true;
  21659. if (this.onCompiled) {
  21660. this.onCompiled(this);
  21661. }
  21662. }
  21663. catch (e) {
  21664. // Is it a problem with precision?
  21665. if (e.message.indexOf("highp") !== -1) {
  21666. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21667. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21668. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21669. return;
  21670. }
  21671. // Let's go through fallbacks then
  21672. if (fallbacks && fallbacks.isMoreFallbacks) {
  21673. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21674. this._dumpShadersName();
  21675. defines = fallbacks.reduce(defines);
  21676. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21677. }
  21678. else {
  21679. BABYLON.Tools.Error("Unable to compile effect: ");
  21680. this._dumpShadersName();
  21681. BABYLON.Tools.Error("Defines: " + defines);
  21682. BABYLON.Tools.Error("Error: " + e.message);
  21683. this._compilationError = e.message;
  21684. if (this.onError) {
  21685. this.onError(this, this._compilationError);
  21686. }
  21687. }
  21688. }
  21689. };
  21690. Object.defineProperty(Effect.prototype, "isSupported", {
  21691. get: function () {
  21692. return this._compilationError === "";
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Effect.prototype._bindTexture = function (channel, texture) {
  21698. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21699. };
  21700. Effect.prototype.setTexture = function (channel, texture) {
  21701. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21702. };
  21703. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21704. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21705. };
  21706. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21707. if (!this._valueCache[uniformName]) {
  21708. this._valueCache[uniformName] = new BABYLON.Matrix();
  21709. }
  21710. for (var index = 0; index < 16; index++) {
  21711. this._valueCache[uniformName].m[index] = matrix.m[index];
  21712. }
  21713. };
  21714. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21715. if (!this._valueCache[uniformName]) {
  21716. this._valueCache[uniformName] = [x, y];
  21717. return;
  21718. }
  21719. this._valueCache[uniformName][0] = x;
  21720. this._valueCache[uniformName][1] = y;
  21721. };
  21722. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21723. if (!this._valueCache[uniformName]) {
  21724. this._valueCache[uniformName] = [x, y, z];
  21725. return;
  21726. }
  21727. this._valueCache[uniformName][0] = x;
  21728. this._valueCache[uniformName][1] = y;
  21729. this._valueCache[uniformName][2] = z;
  21730. };
  21731. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21732. if (!this._valueCache[uniformName]) {
  21733. this._valueCache[uniformName] = [x, y, z, w];
  21734. return;
  21735. }
  21736. this._valueCache[uniformName][0] = x;
  21737. this._valueCache[uniformName][1] = y;
  21738. this._valueCache[uniformName][2] = z;
  21739. this._valueCache[uniformName][3] = w;
  21740. };
  21741. Effect.prototype.setArray = function (uniformName, array) {
  21742. this._engine.setArray(this.getUniform(uniformName), array);
  21743. return this;
  21744. };
  21745. Effect.prototype.setArray2 = function (uniformName, array) {
  21746. this._engine.setArray2(this.getUniform(uniformName), array);
  21747. return this;
  21748. };
  21749. Effect.prototype.setArray3 = function (uniformName, array) {
  21750. this._engine.setArray3(this.getUniform(uniformName), array);
  21751. return this;
  21752. };
  21753. Effect.prototype.setArray4 = function (uniformName, array) {
  21754. this._engine.setArray4(this.getUniform(uniformName), array);
  21755. return this;
  21756. };
  21757. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21758. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21759. return this;
  21760. };
  21761. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21762. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21763. // return this;
  21764. // this._cacheMatrix(uniformName, matrix);
  21765. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21766. return this;
  21767. };
  21768. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21769. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21770. return this;
  21771. };
  21772. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21773. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21774. return this;
  21775. };
  21776. Effect.prototype.setFloat = function (uniformName, value) {
  21777. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21778. return this;
  21779. this._valueCache[uniformName] = value;
  21780. this._engine.setFloat(this.getUniform(uniformName), value);
  21781. return this;
  21782. };
  21783. Effect.prototype.setBool = function (uniformName, bool) {
  21784. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21785. return this;
  21786. this._valueCache[uniformName] = bool;
  21787. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21788. return this;
  21789. };
  21790. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21791. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21792. return this;
  21793. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21794. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21795. return this;
  21796. };
  21797. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21798. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21799. return this;
  21800. this._cacheFloat2(uniformName, x, y);
  21801. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21802. return this;
  21803. };
  21804. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21805. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21806. return this;
  21807. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21808. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21809. return this;
  21810. };
  21811. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21812. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21813. return this;
  21814. this._cacheFloat3(uniformName, x, y, z);
  21815. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21816. return this;
  21817. };
  21818. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21819. 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)
  21820. return this;
  21821. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21822. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21823. return this;
  21824. };
  21825. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21826. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21827. return this;
  21828. this._cacheFloat4(uniformName, x, y, z, w);
  21829. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21830. return this;
  21831. };
  21832. Effect.prototype.setColor3 = function (uniformName, color3) {
  21833. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21834. return this;
  21835. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21836. this._engine.setColor3(this.getUniform(uniformName), color3);
  21837. return this;
  21838. };
  21839. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21840. 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)
  21841. return this;
  21842. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21843. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21844. return this;
  21845. };
  21846. // Statics
  21847. Effect.ShadersStore = {};
  21848. Effect.IncludesShadersStore = {};
  21849. return Effect;
  21850. }());
  21851. BABYLON.Effect = Effect;
  21852. })(BABYLON || (BABYLON = {}));
  21853. var BABYLON;
  21854. (function (BABYLON) {
  21855. var maxSimultaneousLights = 4;
  21856. var MaterialHelper = (function () {
  21857. function MaterialHelper() {
  21858. }
  21859. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21860. var lightIndex = 0;
  21861. var needNormals = false;
  21862. for (var index = 0; index < scene.lights.length; index++) {
  21863. var light = scene.lights[index];
  21864. if (!light.isEnabled()) {
  21865. continue;
  21866. }
  21867. // Excluded check
  21868. if (light._excludedMeshesIds.length > 0) {
  21869. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21870. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21871. if (excludedMesh) {
  21872. light.excludedMeshes.push(excludedMesh);
  21873. }
  21874. }
  21875. light._excludedMeshesIds = [];
  21876. }
  21877. // Included check
  21878. if (light._includedOnlyMeshesIds.length > 0) {
  21879. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  21880. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  21881. if (includedOnlyMesh) {
  21882. light.includedOnlyMeshes.push(includedOnlyMesh);
  21883. }
  21884. }
  21885. light._includedOnlyMeshesIds = [];
  21886. }
  21887. if (!light.canAffectMesh(mesh)) {
  21888. continue;
  21889. }
  21890. needNormals = true;
  21891. defines["LIGHT" + lightIndex] = true;
  21892. var type;
  21893. if (light instanceof BABYLON.SpotLight) {
  21894. type = "SPOTLIGHT" + lightIndex;
  21895. }
  21896. else if (light instanceof BABYLON.HemisphericLight) {
  21897. type = "HEMILIGHT" + lightIndex;
  21898. }
  21899. else if (light instanceof BABYLON.PointLight) {
  21900. type = "POINTLIGHT" + lightIndex;
  21901. }
  21902. else {
  21903. type = "DIRLIGHT" + lightIndex;
  21904. }
  21905. defines[type] = true;
  21906. // Specular
  21907. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  21908. defines["SPECULARTERM"] = true;
  21909. }
  21910. // Shadows
  21911. if (scene.shadowsEnabled) {
  21912. var shadowGenerator = light.getShadowGenerator();
  21913. if (mesh && mesh.receiveShadows && shadowGenerator) {
  21914. defines["SHADOW" + lightIndex] = true;
  21915. defines["SHADOWS"] = true;
  21916. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  21917. defines["SHADOWVSM" + lightIndex] = true;
  21918. }
  21919. if (shadowGenerator.usePoissonSampling) {
  21920. defines["SHADOWPCF" + lightIndex] = true;
  21921. }
  21922. }
  21923. }
  21924. lightIndex++;
  21925. if (lightIndex === maxSimultaneousLights)
  21926. break;
  21927. }
  21928. return needNormals;
  21929. };
  21930. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  21931. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  21932. if (!defines["LIGHT" + lightIndex]) {
  21933. continue;
  21934. }
  21935. if (lightIndex > 0) {
  21936. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  21937. }
  21938. if (defines["SHADOW" + lightIndex]) {
  21939. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  21940. }
  21941. if (defines["SHADOWPCF" + lightIndex]) {
  21942. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  21943. }
  21944. if (defines["SHADOWVSM" + lightIndex]) {
  21945. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  21946. }
  21947. }
  21948. };
  21949. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  21950. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  21951. fallbacks.addCPUSkinningFallback(0, mesh);
  21952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21954. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  21955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  21956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  21957. }
  21958. }
  21959. };
  21960. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  21961. if (defines["INSTANCES"]) {
  21962. attribs.push("world0");
  21963. attribs.push("world1");
  21964. attribs.push("world2");
  21965. attribs.push("world3");
  21966. }
  21967. };
  21968. // Bindings
  21969. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  21970. var shadowGenerator = light.getShadowGenerator();
  21971. if (mesh.receiveShadows && shadowGenerator) {
  21972. if (!light.needCube()) {
  21973. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  21974. }
  21975. else {
  21976. if (!depthValuesAlreadySet) {
  21977. depthValuesAlreadySet = true;
  21978. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  21979. }
  21980. }
  21981. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  21982. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  21983. }
  21984. return depthValuesAlreadySet;
  21985. };
  21986. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  21987. if (light instanceof BABYLON.PointLight) {
  21988. // Point Light
  21989. light.transferToEffect(effect, "vLightData" + lightIndex);
  21990. }
  21991. else if (light instanceof BABYLON.DirectionalLight) {
  21992. // Directional Light
  21993. light.transferToEffect(effect, "vLightData" + lightIndex);
  21994. }
  21995. else if (light instanceof BABYLON.SpotLight) {
  21996. // Spot Light
  21997. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  21998. }
  21999. else if (light instanceof BABYLON.HemisphericLight) {
  22000. // Hemispheric Light
  22001. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22002. }
  22003. };
  22004. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  22005. var lightIndex = 0;
  22006. var depthValuesAlreadySet = false;
  22007. for (var index = 0; index < scene.lights.length; index++) {
  22008. var light = scene.lights[index];
  22009. if (!light.isEnabled()) {
  22010. continue;
  22011. }
  22012. if (!light.canAffectMesh(mesh)) {
  22013. continue;
  22014. }
  22015. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22016. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22017. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22018. if (defines["SPECULARTERM"]) {
  22019. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22020. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22021. }
  22022. // Shadows
  22023. if (scene.shadowsEnabled) {
  22024. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22025. }
  22026. lightIndex++;
  22027. if (lightIndex === maxSimultaneousLights)
  22028. break;
  22029. }
  22030. };
  22031. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22032. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22033. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22034. effect.setColor3("vFogColor", scene.fogColor);
  22035. }
  22036. };
  22037. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22038. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22039. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22040. }
  22041. };
  22042. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22043. if (defines["LOGARITHMICDEPTH"]) {
  22044. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22045. }
  22046. };
  22047. MaterialHelper.BindClipPlane = function (effect, scene) {
  22048. if (scene.clipPlane) {
  22049. var clipPlane = scene.clipPlane;
  22050. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22051. }
  22052. };
  22053. return MaterialHelper;
  22054. }());
  22055. BABYLON.MaterialHelper = MaterialHelper;
  22056. })(BABYLON || (BABYLON = {}));
  22057. var BABYLON;
  22058. (function (BABYLON) {
  22059. var FresnelParameters = (function () {
  22060. function FresnelParameters() {
  22061. this.isEnabled = true;
  22062. this.leftColor = BABYLON.Color3.White();
  22063. this.rightColor = BABYLON.Color3.Black();
  22064. this.bias = 0;
  22065. this.power = 1;
  22066. }
  22067. FresnelParameters.prototype.clone = function () {
  22068. var newFresnelParameters = new FresnelParameters();
  22069. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22070. return new FresnelParameters;
  22071. };
  22072. FresnelParameters.prototype.serialize = function () {
  22073. var serializationObject = {};
  22074. serializationObject.isEnabled = this.isEnabled;
  22075. serializationObject.leftColor = this.leftColor;
  22076. serializationObject.rightColor = this.rightColor;
  22077. serializationObject.bias = this.bias;
  22078. serializationObject.power = this.power;
  22079. return serializationObject;
  22080. };
  22081. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22082. var fresnelParameters = new FresnelParameters();
  22083. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22084. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22085. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22086. fresnelParameters.bias = parsedFresnelParameters.bias;
  22087. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22088. return fresnelParameters;
  22089. };
  22090. return FresnelParameters;
  22091. }());
  22092. BABYLON.FresnelParameters = FresnelParameters;
  22093. })(BABYLON || (BABYLON = {}));
  22094. var BABYLON;
  22095. (function (BABYLON) {
  22096. var MaterialDefines = (function () {
  22097. function MaterialDefines() {
  22098. }
  22099. MaterialDefines.prototype.isEqual = function (other) {
  22100. for (var index = 0; index < this._keys.length; index++) {
  22101. var prop = this._keys[index];
  22102. if (this[prop] !== other[prop]) {
  22103. return false;
  22104. }
  22105. }
  22106. return true;
  22107. };
  22108. MaterialDefines.prototype.cloneTo = function (other) {
  22109. for (var index = 0; index < this._keys.length; index++) {
  22110. var prop = this._keys[index];
  22111. other[prop] = this[prop];
  22112. }
  22113. };
  22114. MaterialDefines.prototype.reset = function () {
  22115. for (var index = 0; index < this._keys.length; index++) {
  22116. var prop = this._keys[index];
  22117. if (typeof (this[prop]) === "number") {
  22118. this[prop] = 0;
  22119. }
  22120. else {
  22121. this[prop] = false;
  22122. }
  22123. }
  22124. };
  22125. MaterialDefines.prototype.toString = function () {
  22126. var result = "";
  22127. for (var index = 0; index < this._keys.length; index++) {
  22128. var prop = this._keys[index];
  22129. if (typeof (this[prop]) === "number") {
  22130. result += "#define " + prop + " " + this[prop] + "\n";
  22131. }
  22132. else if (this[prop]) {
  22133. result += "#define " + prop + "\n";
  22134. }
  22135. }
  22136. return result;
  22137. };
  22138. return MaterialDefines;
  22139. }());
  22140. BABYLON.MaterialDefines = MaterialDefines;
  22141. var Material = (function () {
  22142. function Material(name, scene, doNotAdd) {
  22143. this.name = name;
  22144. this.checkReadyOnEveryCall = false;
  22145. this.checkReadyOnlyOnce = false;
  22146. this.state = "";
  22147. this.alpha = 1.0;
  22148. this.backFaceCulling = true;
  22149. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22150. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22151. this.disableDepthWrite = false;
  22152. this.fogEnabled = true;
  22153. this.pointSize = 1.0;
  22154. this.zOffset = 0;
  22155. this._wasPreviouslyReady = false;
  22156. this._fillMode = Material.TriangleFillMode;
  22157. this.id = name;
  22158. this._scene = scene;
  22159. if (!doNotAdd) {
  22160. scene.materials.push(this);
  22161. }
  22162. }
  22163. Object.defineProperty(Material, "TriangleFillMode", {
  22164. get: function () {
  22165. return Material._TriangleFillMode;
  22166. },
  22167. enumerable: true,
  22168. configurable: true
  22169. });
  22170. Object.defineProperty(Material, "WireFrameFillMode", {
  22171. get: function () {
  22172. return Material._WireFrameFillMode;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Object.defineProperty(Material, "PointFillMode", {
  22178. get: function () {
  22179. return Material._PointFillMode;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22185. get: function () {
  22186. return Material._ClockWiseSideOrientation;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22192. get: function () {
  22193. return Material._CounterClockWiseSideOrientation;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(Material.prototype, "wireframe", {
  22199. get: function () {
  22200. return this._fillMode === Material.WireFrameFillMode;
  22201. },
  22202. set: function (value) {
  22203. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Material.prototype, "pointsCloud", {
  22209. get: function () {
  22210. return this._fillMode === Material.PointFillMode;
  22211. },
  22212. set: function (value) {
  22213. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22214. },
  22215. enumerable: true,
  22216. configurable: true
  22217. });
  22218. Object.defineProperty(Material.prototype, "fillMode", {
  22219. get: function () {
  22220. return this._fillMode;
  22221. },
  22222. set: function (value) {
  22223. this._fillMode = value;
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. /**
  22229. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22230. * subclasses should override adding information pertainent to themselves
  22231. */
  22232. Material.prototype.toString = function (fullDetails) {
  22233. var ret = "Name: " + this.name;
  22234. if (fullDetails) {
  22235. }
  22236. return ret;
  22237. };
  22238. Object.defineProperty(Material.prototype, "isFrozen", {
  22239. get: function () {
  22240. return this.checkReadyOnlyOnce;
  22241. },
  22242. enumerable: true,
  22243. configurable: true
  22244. });
  22245. Material.prototype.freeze = function () {
  22246. this.checkReadyOnlyOnce = true;
  22247. };
  22248. Material.prototype.unfreeze = function () {
  22249. this.checkReadyOnlyOnce = false;
  22250. };
  22251. Material.prototype.isReady = function (mesh, useInstances) {
  22252. return true;
  22253. };
  22254. Material.prototype.getEffect = function () {
  22255. return this._effect;
  22256. };
  22257. Material.prototype.getScene = function () {
  22258. return this._scene;
  22259. };
  22260. Material.prototype.needAlphaBlending = function () {
  22261. return (this.alpha < 1.0);
  22262. };
  22263. Material.prototype.needAlphaTesting = function () {
  22264. return false;
  22265. };
  22266. Material.prototype.getAlphaTestTexture = function () {
  22267. return null;
  22268. };
  22269. Material.prototype.trackCreation = function (onCompiled, onError) {
  22270. };
  22271. Material.prototype.markDirty = function () {
  22272. this._wasPreviouslyReady = false;
  22273. };
  22274. Material.prototype._preBind = function () {
  22275. var engine = this._scene.getEngine();
  22276. engine.enableEffect(this._effect);
  22277. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22278. };
  22279. Material.prototype.bind = function (world, mesh) {
  22280. this._scene._cachedMaterial = this;
  22281. if (this.onBind) {
  22282. this.onBind(this, mesh);
  22283. }
  22284. if (this.disableDepthWrite) {
  22285. var engine = this._scene.getEngine();
  22286. this._cachedDepthWriteState = engine.getDepthWrite();
  22287. engine.setDepthWrite(false);
  22288. }
  22289. };
  22290. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22291. };
  22292. Material.prototype.unbind = function () {
  22293. if (this.disableDepthWrite) {
  22294. var engine = this._scene.getEngine();
  22295. engine.setDepthWrite(this._cachedDepthWriteState);
  22296. }
  22297. };
  22298. Material.prototype.clone = function (name) {
  22299. return null;
  22300. };
  22301. Material.prototype.getBindedMeshes = function () {
  22302. var result = new Array();
  22303. for (var index = 0; index < this._scene.meshes.length; index++) {
  22304. var mesh = this._scene.meshes[index];
  22305. if (mesh.material === this) {
  22306. result.push(mesh);
  22307. }
  22308. }
  22309. return result;
  22310. };
  22311. Material.prototype.dispose = function (forceDisposeEffect) {
  22312. // Animations
  22313. this.getScene().stopAnimation(this);
  22314. // Remove from scene
  22315. var index = this._scene.materials.indexOf(this);
  22316. if (index >= 0) {
  22317. this._scene.materials.splice(index, 1);
  22318. }
  22319. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22320. if (forceDisposeEffect && this._effect) {
  22321. this._scene.getEngine()._releaseEffect(this._effect);
  22322. this._effect = null;
  22323. }
  22324. // Remove from meshes
  22325. for (index = 0; index < this._scene.meshes.length; index++) {
  22326. var mesh = this._scene.meshes[index];
  22327. if (mesh.material === this) {
  22328. mesh.material = null;
  22329. }
  22330. }
  22331. // Callback
  22332. if (this.onDispose) {
  22333. this.onDispose();
  22334. }
  22335. };
  22336. Material.prototype.serialize = function () {
  22337. return BABYLON.SerializationHelper.Serialize(this);
  22338. };
  22339. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22340. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22341. multiMaterial.id = parsedMultiMaterial.id;
  22342. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22343. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22344. var subMatId = parsedMultiMaterial.materials[matIndex];
  22345. if (subMatId) {
  22346. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22347. }
  22348. else {
  22349. multiMaterial.subMaterials.push(null);
  22350. }
  22351. }
  22352. return multiMaterial;
  22353. };
  22354. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22355. if (!parsedMaterial.customType) {
  22356. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22357. }
  22358. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22359. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22360. ;
  22361. };
  22362. Material._TriangleFillMode = 0;
  22363. Material._WireFrameFillMode = 1;
  22364. Material._PointFillMode = 2;
  22365. Material._ClockWiseSideOrientation = 0;
  22366. Material._CounterClockWiseSideOrientation = 1;
  22367. __decorate([
  22368. BABYLON.serialize()
  22369. ], Material.prototype, "id", void 0);
  22370. __decorate([
  22371. BABYLON.serialize()
  22372. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22373. __decorate([
  22374. BABYLON.serialize()
  22375. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22376. __decorate([
  22377. BABYLON.serialize()
  22378. ], Material.prototype, "state", void 0);
  22379. __decorate([
  22380. BABYLON.serialize()
  22381. ], Material.prototype, "alpha", void 0);
  22382. __decorate([
  22383. BABYLON.serialize()
  22384. ], Material.prototype, "backFaceCulling", void 0);
  22385. __decorate([
  22386. BABYLON.serialize()
  22387. ], Material.prototype, "sideOrientation", void 0);
  22388. __decorate([
  22389. BABYLON.serialize()
  22390. ], Material.prototype, "alphaMode", void 0);
  22391. __decorate([
  22392. BABYLON.serialize()
  22393. ], Material.prototype, "disableDepthWrite", void 0);
  22394. __decorate([
  22395. BABYLON.serialize()
  22396. ], Material.prototype, "fogEnabled", void 0);
  22397. __decorate([
  22398. BABYLON.serialize()
  22399. ], Material.prototype, "pointSize", void 0);
  22400. __decorate([
  22401. BABYLON.serialize()
  22402. ], Material.prototype, "zOffset", void 0);
  22403. __decorate([
  22404. BABYLON.serialize()
  22405. ], Material.prototype, "wireframe", null);
  22406. __decorate([
  22407. BABYLON.serialize()
  22408. ], Material.prototype, "pointsCloud", null);
  22409. __decorate([
  22410. BABYLON.serialize()
  22411. ], Material.prototype, "fillMode", null);
  22412. return Material;
  22413. }());
  22414. BABYLON.Material = Material;
  22415. })(BABYLON || (BABYLON = {}));
  22416. var BABYLON;
  22417. (function (BABYLON) {
  22418. var StandardMaterialDefines = (function (_super) {
  22419. __extends(StandardMaterialDefines, _super);
  22420. function StandardMaterialDefines() {
  22421. _super.call(this);
  22422. this.DIFFUSE = false;
  22423. this.AMBIENT = false;
  22424. this.OPACITY = false;
  22425. this.OPACITYRGB = false;
  22426. this.REFLECTION = false;
  22427. this.EMISSIVE = false;
  22428. this.SPECULAR = false;
  22429. this.BUMP = false;
  22430. this.PARALLAX = false;
  22431. this.PARALLAXOCCLUSION = false;
  22432. this.SPECULAROVERALPHA = false;
  22433. this.CLIPPLANE = false;
  22434. this.ALPHATEST = false;
  22435. this.ALPHAFROMDIFFUSE = false;
  22436. this.POINTSIZE = false;
  22437. this.FOG = false;
  22438. this.LIGHT0 = false;
  22439. this.LIGHT1 = false;
  22440. this.LIGHT2 = false;
  22441. this.LIGHT3 = false;
  22442. this.SPOTLIGHT0 = false;
  22443. this.SPOTLIGHT1 = false;
  22444. this.SPOTLIGHT2 = false;
  22445. this.SPOTLIGHT3 = false;
  22446. this.HEMILIGHT0 = false;
  22447. this.HEMILIGHT1 = false;
  22448. this.HEMILIGHT2 = false;
  22449. this.HEMILIGHT3 = false;
  22450. this.POINTLIGHT0 = false;
  22451. this.POINTLIGHT1 = false;
  22452. this.POINTLIGHT2 = false;
  22453. this.POINTLIGHT3 = false;
  22454. this.DIRLIGHT0 = false;
  22455. this.DIRLIGHT1 = false;
  22456. this.DIRLIGHT2 = false;
  22457. this.DIRLIGHT3 = false;
  22458. this.SPECULARTERM = false;
  22459. this.SHADOW0 = false;
  22460. this.SHADOW1 = false;
  22461. this.SHADOW2 = false;
  22462. this.SHADOW3 = false;
  22463. this.SHADOWS = false;
  22464. this.SHADOWVSM0 = false;
  22465. this.SHADOWVSM1 = false;
  22466. this.SHADOWVSM2 = false;
  22467. this.SHADOWVSM3 = false;
  22468. this.SHADOWPCF0 = false;
  22469. this.SHADOWPCF1 = false;
  22470. this.SHADOWPCF2 = false;
  22471. this.SHADOWPCF3 = false;
  22472. this.DIFFUSEFRESNEL = false;
  22473. this.OPACITYFRESNEL = false;
  22474. this.REFLECTIONFRESNEL = false;
  22475. this.REFRACTIONFRESNEL = false;
  22476. this.EMISSIVEFRESNEL = false;
  22477. this.FRESNEL = false;
  22478. this.NORMAL = false;
  22479. this.UV1 = false;
  22480. this.UV2 = false;
  22481. this.VERTEXCOLOR = false;
  22482. this.VERTEXALPHA = false;
  22483. this.NUM_BONE_INFLUENCERS = 0;
  22484. this.BonesPerMesh = 0;
  22485. this.INSTANCES = false;
  22486. this.GLOSSINESS = false;
  22487. this.ROUGHNESS = false;
  22488. this.EMISSIVEASILLUMINATION = false;
  22489. this.LINKEMISSIVEWITHDIFFUSE = false;
  22490. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22491. this.LIGHTMAP = false;
  22492. this.USELIGHTMAPASSHADOWMAP = false;
  22493. this.REFLECTIONMAP_3D = false;
  22494. this.REFLECTIONMAP_SPHERICAL = false;
  22495. this.REFLECTIONMAP_PLANAR = false;
  22496. this.REFLECTIONMAP_CUBIC = false;
  22497. this.REFLECTIONMAP_PROJECTION = false;
  22498. this.REFLECTIONMAP_SKYBOX = false;
  22499. this.REFLECTIONMAP_EXPLICIT = false;
  22500. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22501. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22502. this.INVERTCUBICMAP = false;
  22503. this.LOGARITHMICDEPTH = false;
  22504. this.REFRACTION = false;
  22505. this.REFRACTIONMAP_3D = false;
  22506. this.REFLECTIONOVERALPHA = false;
  22507. this._keys = Object.keys(this);
  22508. }
  22509. return StandardMaterialDefines;
  22510. }(BABYLON.MaterialDefines));
  22511. var StandardMaterial = (function (_super) {
  22512. __extends(StandardMaterial, _super);
  22513. function StandardMaterial(name, scene) {
  22514. var _this = this;
  22515. _super.call(this, name, scene);
  22516. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22517. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22518. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22519. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22520. this.specularPower = 64;
  22521. this.useAlphaFromDiffuseTexture = false;
  22522. this.useEmissiveAsIllumination = false;
  22523. this.linkEmissiveWithDiffuse = false;
  22524. this.useReflectionFresnelFromSpecular = false;
  22525. this.useSpecularOverAlpha = false;
  22526. this.useReflectionOverAlpha = false;
  22527. this.disableLighting = false;
  22528. this.useParallax = false;
  22529. this.useParallaxOcclusion = false;
  22530. this.parallaxScaleBias = 0.05;
  22531. this.roughness = 0;
  22532. this.indexOfRefraction = 0.98;
  22533. this.invertRefractionY = true;
  22534. this.useLightmapAsShadowmap = false;
  22535. this.useGlossinessFromSpecularMapAlpha = false;
  22536. this._renderTargets = new BABYLON.SmartArray(16);
  22537. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22538. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22539. this._defines = new StandardMaterialDefines();
  22540. this._cachedDefines = new StandardMaterialDefines();
  22541. this._cachedDefines.BonesPerMesh = -1;
  22542. this.getRenderTargetTextures = function () {
  22543. _this._renderTargets.reset();
  22544. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22545. _this._renderTargets.push(_this.reflectionTexture);
  22546. }
  22547. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22548. _this._renderTargets.push(_this.refractionTexture);
  22549. }
  22550. return _this._renderTargets;
  22551. };
  22552. }
  22553. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22554. get: function () {
  22555. return this._useLogarithmicDepth;
  22556. },
  22557. set: function (value) {
  22558. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22559. },
  22560. enumerable: true,
  22561. configurable: true
  22562. });
  22563. StandardMaterial.prototype.needAlphaBlending = function () {
  22564. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22565. };
  22566. StandardMaterial.prototype.needAlphaTesting = function () {
  22567. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22568. };
  22569. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22570. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22571. };
  22572. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22573. return this.diffuseTexture;
  22574. };
  22575. // Methods
  22576. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22577. if (!mesh) {
  22578. return true;
  22579. }
  22580. if (this._defines.INSTANCES !== useInstances) {
  22581. return false;
  22582. }
  22583. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22584. return true;
  22585. }
  22586. return false;
  22587. };
  22588. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22589. if (this.isFrozen) {
  22590. if (this._wasPreviouslyReady) {
  22591. return true;
  22592. }
  22593. }
  22594. var scene = this.getScene();
  22595. if (!this.checkReadyOnEveryCall) {
  22596. if (this._renderId === scene.getRenderId()) {
  22597. if (this._checkCache(scene, mesh, useInstances)) {
  22598. return true;
  22599. }
  22600. }
  22601. }
  22602. var engine = scene.getEngine();
  22603. var needNormals = false;
  22604. var needUVs = false;
  22605. this._defines.reset();
  22606. // Textures
  22607. if (scene.texturesEnabled) {
  22608. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22609. if (!this.diffuseTexture.isReady()) {
  22610. return false;
  22611. }
  22612. else {
  22613. needUVs = true;
  22614. this._defines.DIFFUSE = true;
  22615. }
  22616. }
  22617. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22618. if (!this.ambientTexture.isReady()) {
  22619. return false;
  22620. }
  22621. else {
  22622. needUVs = true;
  22623. this._defines.AMBIENT = true;
  22624. }
  22625. }
  22626. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22627. if (!this.opacityTexture.isReady()) {
  22628. return false;
  22629. }
  22630. else {
  22631. needUVs = true;
  22632. this._defines.OPACITY = true;
  22633. if (this.opacityTexture.getAlphaFromRGB) {
  22634. this._defines.OPACITYRGB = true;
  22635. }
  22636. }
  22637. }
  22638. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22639. if (!this.reflectionTexture.isReady()) {
  22640. return false;
  22641. }
  22642. else {
  22643. needNormals = true;
  22644. this._defines.REFLECTION = true;
  22645. if (this.roughness > 0) {
  22646. this._defines.ROUGHNESS = true;
  22647. }
  22648. if (this.useReflectionOverAlpha) {
  22649. this._defines.REFLECTIONOVERALPHA = true;
  22650. }
  22651. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22652. this._defines.INVERTCUBICMAP = true;
  22653. }
  22654. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22655. switch (this.reflectionTexture.coordinatesMode) {
  22656. case BABYLON.Texture.CUBIC_MODE:
  22657. case BABYLON.Texture.INVCUBIC_MODE:
  22658. this._defines.REFLECTIONMAP_CUBIC = true;
  22659. break;
  22660. case BABYLON.Texture.EXPLICIT_MODE:
  22661. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22662. break;
  22663. case BABYLON.Texture.PLANAR_MODE:
  22664. this._defines.REFLECTIONMAP_PLANAR = true;
  22665. break;
  22666. case BABYLON.Texture.PROJECTION_MODE:
  22667. this._defines.REFLECTIONMAP_PROJECTION = true;
  22668. break;
  22669. case BABYLON.Texture.SKYBOX_MODE:
  22670. this._defines.REFLECTIONMAP_SKYBOX = true;
  22671. break;
  22672. case BABYLON.Texture.SPHERICAL_MODE:
  22673. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22674. break;
  22675. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22676. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22677. break;
  22678. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22679. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22680. break;
  22681. }
  22682. }
  22683. }
  22684. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22685. if (!this.emissiveTexture.isReady()) {
  22686. return false;
  22687. }
  22688. else {
  22689. needUVs = true;
  22690. this._defines.EMISSIVE = true;
  22691. }
  22692. }
  22693. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22694. if (!this.lightmapTexture.isReady()) {
  22695. return false;
  22696. }
  22697. else {
  22698. needUVs = true;
  22699. this._defines.LIGHTMAP = true;
  22700. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22701. }
  22702. }
  22703. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22704. if (!this.specularTexture.isReady()) {
  22705. return false;
  22706. }
  22707. else {
  22708. needUVs = true;
  22709. this._defines.SPECULAR = true;
  22710. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22711. }
  22712. }
  22713. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22714. if (!this.bumpTexture.isReady()) {
  22715. return false;
  22716. }
  22717. else {
  22718. needUVs = true;
  22719. this._defines.BUMP = true;
  22720. if (this.useParallax) {
  22721. this._defines.PARALLAX = true;
  22722. if (this.useParallaxOcclusion) {
  22723. this._defines.PARALLAXOCCLUSION = true;
  22724. }
  22725. }
  22726. }
  22727. }
  22728. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22729. if (!this.refractionTexture.isReady()) {
  22730. return false;
  22731. }
  22732. else {
  22733. needUVs = true;
  22734. this._defines.REFRACTION = true;
  22735. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22736. }
  22737. }
  22738. }
  22739. // Effect
  22740. if (scene.clipPlane) {
  22741. this._defines.CLIPPLANE = true;
  22742. }
  22743. if (engine.getAlphaTesting()) {
  22744. this._defines.ALPHATEST = true;
  22745. }
  22746. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22747. this._defines.ALPHAFROMDIFFUSE = true;
  22748. }
  22749. if (this.useEmissiveAsIllumination) {
  22750. this._defines.EMISSIVEASILLUMINATION = true;
  22751. }
  22752. if (this.linkEmissiveWithDiffuse) {
  22753. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22754. }
  22755. if (this.useLogarithmicDepth) {
  22756. this._defines.LOGARITHMICDEPTH = true;
  22757. }
  22758. // Point size
  22759. if (this.pointsCloud || scene.forcePointsCloud) {
  22760. this._defines.POINTSIZE = true;
  22761. }
  22762. // Fog
  22763. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22764. this._defines.FOG = true;
  22765. }
  22766. if (scene.lightsEnabled && !this.disableLighting) {
  22767. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22768. }
  22769. if (StandardMaterial.FresnelEnabled) {
  22770. // Fresnel
  22771. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22772. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22773. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22774. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22775. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22776. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22777. this._defines.DIFFUSEFRESNEL = true;
  22778. }
  22779. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22780. this._defines.OPACITYFRESNEL = true;
  22781. }
  22782. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22783. this._defines.REFLECTIONFRESNEL = true;
  22784. if (this.useReflectionFresnelFromSpecular) {
  22785. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22786. }
  22787. }
  22788. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22789. this._defines.REFRACTIONFRESNEL = true;
  22790. }
  22791. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22792. this._defines.EMISSIVEFRESNEL = true;
  22793. }
  22794. needNormals = true;
  22795. this._defines.FRESNEL = true;
  22796. }
  22797. }
  22798. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22799. this._defines.SPECULAROVERALPHA = true;
  22800. }
  22801. // Attribs
  22802. if (mesh) {
  22803. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22804. this._defines.NORMAL = true;
  22805. }
  22806. if (needUVs) {
  22807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22808. this._defines.UV1 = true;
  22809. }
  22810. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22811. this._defines.UV2 = true;
  22812. }
  22813. }
  22814. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22815. this._defines.VERTEXCOLOR = true;
  22816. if (mesh.hasVertexAlpha) {
  22817. this._defines.VERTEXALPHA = true;
  22818. }
  22819. }
  22820. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22821. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22822. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22823. }
  22824. // Instances
  22825. if (useInstances) {
  22826. this._defines.INSTANCES = true;
  22827. }
  22828. }
  22829. // Get correct effect
  22830. if (!this._defines.isEqual(this._cachedDefines)) {
  22831. this._defines.cloneTo(this._cachedDefines);
  22832. scene.resetCachedMaterial();
  22833. // Fallbacks
  22834. var fallbacks = new BABYLON.EffectFallbacks();
  22835. if (this._defines.REFLECTION) {
  22836. fallbacks.addFallback(0, "REFLECTION");
  22837. }
  22838. if (this._defines.SPECULAR) {
  22839. fallbacks.addFallback(0, "SPECULAR");
  22840. }
  22841. if (this._defines.BUMP) {
  22842. fallbacks.addFallback(0, "BUMP");
  22843. }
  22844. if (this._defines.PARALLAX) {
  22845. fallbacks.addFallback(1, "PARALLAX");
  22846. }
  22847. if (this._defines.PARALLAXOCCLUSION) {
  22848. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22849. }
  22850. if (this._defines.SPECULAROVERALPHA) {
  22851. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22852. }
  22853. if (this._defines.FOG) {
  22854. fallbacks.addFallback(1, "FOG");
  22855. }
  22856. if (this._defines.POINTSIZE) {
  22857. fallbacks.addFallback(0, "POINTSIZE");
  22858. }
  22859. if (this._defines.LOGARITHMICDEPTH) {
  22860. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22861. }
  22862. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22863. if (this._defines.SPECULARTERM) {
  22864. fallbacks.addFallback(0, "SPECULARTERM");
  22865. }
  22866. if (this._defines.DIFFUSEFRESNEL) {
  22867. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22868. }
  22869. if (this._defines.OPACITYFRESNEL) {
  22870. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22871. }
  22872. if (this._defines.REFLECTIONFRESNEL) {
  22873. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22874. }
  22875. if (this._defines.EMISSIVEFRESNEL) {
  22876. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  22877. }
  22878. if (this._defines.FRESNEL) {
  22879. fallbacks.addFallback(4, "FRESNEL");
  22880. }
  22881. //Attributes
  22882. var attribs = [BABYLON.VertexBuffer.PositionKind];
  22883. if (this._defines.NORMAL) {
  22884. attribs.push(BABYLON.VertexBuffer.NormalKind);
  22885. }
  22886. if (this._defines.UV1) {
  22887. attribs.push(BABYLON.VertexBuffer.UVKind);
  22888. }
  22889. if (this._defines.UV2) {
  22890. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22891. }
  22892. if (this._defines.VERTEXCOLOR) {
  22893. attribs.push(BABYLON.VertexBuffer.ColorKind);
  22894. }
  22895. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  22896. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  22897. // Legacy browser patch
  22898. var shaderName = "default";
  22899. if (!scene.getEngine().getCaps().standardDerivatives) {
  22900. shaderName = "legacydefault";
  22901. }
  22902. var join = this._defines.toString();
  22903. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  22904. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  22905. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  22906. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  22907. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  22908. "vFogInfos", "vFogColor", "pointSize",
  22909. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  22910. "mBones",
  22911. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  22912. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  22913. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  22914. "logarithmicDepthConstant"
  22915. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  22916. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  22917. ], join, fallbacks, this.onCompiled, this.onError);
  22918. }
  22919. if (!this._effect.isReady()) {
  22920. return false;
  22921. }
  22922. this._renderId = scene.getRenderId();
  22923. this._wasPreviouslyReady = true;
  22924. if (mesh) {
  22925. if (!mesh._materialDefines) {
  22926. mesh._materialDefines = new StandardMaterialDefines();
  22927. }
  22928. this._defines.cloneTo(mesh._materialDefines);
  22929. }
  22930. return true;
  22931. };
  22932. StandardMaterial.prototype.unbind = function () {
  22933. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  22934. this._effect.setTexture("reflection2DSampler", null);
  22935. }
  22936. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  22937. this._effect.setTexture("refraction2DSampler", null);
  22938. }
  22939. _super.prototype.unbind.call(this);
  22940. };
  22941. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22942. this._effect.setMatrix("world", world);
  22943. };
  22944. StandardMaterial.prototype.bind = function (world, mesh) {
  22945. var scene = this.getScene();
  22946. // Matrices
  22947. this.bindOnlyWorldMatrix(world);
  22948. // Bones
  22949. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  22950. if (scene.getCachedMaterial() !== this) {
  22951. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  22952. if (StandardMaterial.FresnelEnabled) {
  22953. // Fresnel
  22954. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22955. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  22956. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  22957. }
  22958. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22959. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  22960. }
  22961. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22962. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  22963. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  22964. }
  22965. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22966. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  22967. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  22968. }
  22969. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22970. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  22971. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  22972. }
  22973. }
  22974. // Textures
  22975. if (scene.texturesEnabled) {
  22976. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22977. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  22978. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  22979. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  22980. }
  22981. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22982. this._effect.setTexture("ambientSampler", this.ambientTexture);
  22983. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  22984. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  22985. }
  22986. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22987. this._effect.setTexture("opacitySampler", this.opacityTexture);
  22988. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  22989. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  22990. }
  22991. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22992. if (this.reflectionTexture.isCube) {
  22993. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  22994. }
  22995. else {
  22996. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  22997. }
  22998. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  22999. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23000. }
  23001. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23002. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23003. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23004. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23005. }
  23006. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23007. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23008. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23009. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23010. }
  23011. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23012. this._effect.setTexture("specularSampler", this.specularTexture);
  23013. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23014. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23015. }
  23016. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23017. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23018. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23019. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23020. }
  23021. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23022. var depth = 1.0;
  23023. if (this.refractionTexture.isCube) {
  23024. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23025. }
  23026. else {
  23027. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23028. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23029. if (this.refractionTexture.depth) {
  23030. depth = this.refractionTexture.depth;
  23031. }
  23032. }
  23033. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23034. }
  23035. }
  23036. // Clip plane
  23037. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23038. // Point size
  23039. if (this.pointsCloud) {
  23040. this._effect.setFloat("pointSize", this.pointSize);
  23041. }
  23042. // Colors
  23043. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23044. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23045. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23046. if (this._defines.SPECULARTERM) {
  23047. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23048. }
  23049. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23050. }
  23051. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23052. // Diffuse
  23053. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23054. // Lights
  23055. if (scene.lightsEnabled && !this.disableLighting) {
  23056. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23057. }
  23058. // View
  23059. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23060. this._effect.setMatrix("view", scene.getViewMatrix());
  23061. }
  23062. // Fog
  23063. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23064. // Log. depth
  23065. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23066. }
  23067. _super.prototype.bind.call(this, world, mesh);
  23068. };
  23069. StandardMaterial.prototype.getAnimatables = function () {
  23070. var results = [];
  23071. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23072. results.push(this.diffuseTexture);
  23073. }
  23074. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23075. results.push(this.ambientTexture);
  23076. }
  23077. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23078. results.push(this.opacityTexture);
  23079. }
  23080. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23081. results.push(this.reflectionTexture);
  23082. }
  23083. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23084. results.push(this.emissiveTexture);
  23085. }
  23086. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23087. results.push(this.specularTexture);
  23088. }
  23089. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23090. results.push(this.bumpTexture);
  23091. }
  23092. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23093. results.push(this.lightmapTexture);
  23094. }
  23095. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23096. results.push(this.refractionTexture);
  23097. }
  23098. return results;
  23099. };
  23100. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  23101. if (this.diffuseTexture) {
  23102. this.diffuseTexture.dispose();
  23103. }
  23104. if (this.ambientTexture) {
  23105. this.ambientTexture.dispose();
  23106. }
  23107. if (this.opacityTexture) {
  23108. this.opacityTexture.dispose();
  23109. }
  23110. if (this.reflectionTexture) {
  23111. this.reflectionTexture.dispose();
  23112. }
  23113. if (this.emissiveTexture) {
  23114. this.emissiveTexture.dispose();
  23115. }
  23116. if (this.specularTexture) {
  23117. this.specularTexture.dispose();
  23118. }
  23119. if (this.bumpTexture) {
  23120. this.bumpTexture.dispose();
  23121. }
  23122. if (this.lightmapTexture) {
  23123. this.lightmapTexture.dispose();
  23124. }
  23125. if (this.refractionTexture) {
  23126. this.refractionTexture.dispose();
  23127. }
  23128. _super.prototype.dispose.call(this, forceDisposeEffect);
  23129. };
  23130. StandardMaterial.prototype.clone = function (name) {
  23131. var _this = this;
  23132. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23133. };
  23134. StandardMaterial.prototype.serialize = function () {
  23135. return BABYLON.SerializationHelper.Serialize(this);
  23136. };
  23137. // Statics
  23138. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23139. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23140. };
  23141. // Flags used to enable or disable a type of texture for all Standard Materials
  23142. StandardMaterial.DiffuseTextureEnabled = true;
  23143. StandardMaterial.AmbientTextureEnabled = true;
  23144. StandardMaterial.OpacityTextureEnabled = true;
  23145. StandardMaterial.ReflectionTextureEnabled = true;
  23146. StandardMaterial.EmissiveTextureEnabled = true;
  23147. StandardMaterial.SpecularTextureEnabled = true;
  23148. StandardMaterial.BumpTextureEnabled = true;
  23149. StandardMaterial.FresnelEnabled = true;
  23150. StandardMaterial.LightmapTextureEnabled = true;
  23151. StandardMaterial.RefractionTextureEnabled = true;
  23152. __decorate([
  23153. BABYLON.serializeAsTexture()
  23154. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23155. __decorate([
  23156. BABYLON.serializeAsTexture()
  23157. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23158. __decorate([
  23159. BABYLON.serializeAsTexture()
  23160. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23161. __decorate([
  23162. BABYLON.serializeAsTexture()
  23163. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23164. __decorate([
  23165. BABYLON.serializeAsTexture()
  23166. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23167. __decorate([
  23168. BABYLON.serializeAsTexture()
  23169. ], StandardMaterial.prototype, "specularTexture", void 0);
  23170. __decorate([
  23171. BABYLON.serializeAsTexture()
  23172. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23173. __decorate([
  23174. BABYLON.serializeAsTexture()
  23175. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23176. __decorate([
  23177. BABYLON.serializeAsTexture()
  23178. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23179. __decorate([
  23180. BABYLON.serializeAsColor3("ambient")
  23181. ], StandardMaterial.prototype, "ambientColor", void 0);
  23182. __decorate([
  23183. BABYLON.serializeAsColor3("diffuse")
  23184. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23185. __decorate([
  23186. BABYLON.serializeAsColor3("specular")
  23187. ], StandardMaterial.prototype, "specularColor", void 0);
  23188. __decorate([
  23189. BABYLON.serializeAsColor3("emissive")
  23190. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23191. __decorate([
  23192. BABYLON.serialize()
  23193. ], StandardMaterial.prototype, "specularPower", void 0);
  23194. __decorate([
  23195. BABYLON.serialize()
  23196. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23197. __decorate([
  23198. BABYLON.serialize()
  23199. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23200. __decorate([
  23201. BABYLON.serialize()
  23202. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23203. __decorate([
  23204. BABYLON.serialize()
  23205. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23206. __decorate([
  23207. BABYLON.serialize()
  23208. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23209. __decorate([
  23210. BABYLON.serialize()
  23211. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23212. __decorate([
  23213. BABYLON.serialize()
  23214. ], StandardMaterial.prototype, "disableLighting", void 0);
  23215. __decorate([
  23216. BABYLON.serialize()
  23217. ], StandardMaterial.prototype, "useParallax", void 0);
  23218. __decorate([
  23219. BABYLON.serialize()
  23220. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23221. __decorate([
  23222. BABYLON.serialize()
  23223. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23224. __decorate([
  23225. BABYLON.serialize()
  23226. ], StandardMaterial.prototype, "roughness", void 0);
  23227. __decorate([
  23228. BABYLON.serialize()
  23229. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23230. __decorate([
  23231. BABYLON.serialize()
  23232. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23233. __decorate([
  23234. BABYLON.serialize()
  23235. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23236. __decorate([
  23237. BABYLON.serializeAsFresnelParameters()
  23238. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23239. __decorate([
  23240. BABYLON.serializeAsFresnelParameters()
  23241. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23242. __decorate([
  23243. BABYLON.serializeAsFresnelParameters()
  23244. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23245. __decorate([
  23246. BABYLON.serializeAsFresnelParameters()
  23247. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23248. __decorate([
  23249. BABYLON.serializeAsFresnelParameters()
  23250. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23251. __decorate([
  23252. BABYLON.serialize()
  23253. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23254. __decorate([
  23255. BABYLON.serialize()
  23256. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23257. return StandardMaterial;
  23258. }(BABYLON.Material));
  23259. BABYLON.StandardMaterial = StandardMaterial;
  23260. })(BABYLON || (BABYLON = {}));
  23261. var BABYLON;
  23262. (function (BABYLON) {
  23263. var MultiMaterial = (function (_super) {
  23264. __extends(MultiMaterial, _super);
  23265. function MultiMaterial(name, scene) {
  23266. _super.call(this, name, scene, true);
  23267. this.subMaterials = new Array();
  23268. scene.multiMaterials.push(this);
  23269. }
  23270. // Properties
  23271. MultiMaterial.prototype.getSubMaterial = function (index) {
  23272. if (index < 0 || index >= this.subMaterials.length) {
  23273. return this.getScene().defaultMaterial;
  23274. }
  23275. return this.subMaterials[index];
  23276. };
  23277. // Methods
  23278. MultiMaterial.prototype.isReady = function (mesh) {
  23279. for (var index = 0; index < this.subMaterials.length; index++) {
  23280. var subMaterial = this.subMaterials[index];
  23281. if (subMaterial) {
  23282. if (!this.subMaterials[index].isReady(mesh)) {
  23283. return false;
  23284. }
  23285. }
  23286. }
  23287. return true;
  23288. };
  23289. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23290. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23291. for (var index = 0; index < this.subMaterials.length; index++) {
  23292. var subMaterial = null;
  23293. if (cloneChildren) {
  23294. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23295. }
  23296. else {
  23297. subMaterial = this.subMaterials[index];
  23298. }
  23299. newMultiMaterial.subMaterials.push(subMaterial);
  23300. }
  23301. return newMultiMaterial;
  23302. };
  23303. MultiMaterial.prototype.serialize = function () {
  23304. var serializationObject = {};
  23305. serializationObject.name = this.name;
  23306. serializationObject.id = this.id;
  23307. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23308. serializationObject.materials = [];
  23309. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23310. var subMat = this.subMaterials[matIndex];
  23311. if (subMat) {
  23312. serializationObject.materials.push(subMat.id);
  23313. }
  23314. else {
  23315. serializationObject.materials.push(null);
  23316. }
  23317. }
  23318. return serializationObject;
  23319. };
  23320. return MultiMaterial;
  23321. }(BABYLON.Material));
  23322. BABYLON.MultiMaterial = MultiMaterial;
  23323. })(BABYLON || (BABYLON = {}));
  23324. var BABYLON;
  23325. (function (BABYLON) {
  23326. var SceneLoader = (function () {
  23327. function SceneLoader() {
  23328. }
  23329. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23330. get: function () {
  23331. return 0;
  23332. },
  23333. enumerable: true,
  23334. configurable: true
  23335. });
  23336. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23337. get: function () {
  23338. return 1;
  23339. },
  23340. enumerable: true,
  23341. configurable: true
  23342. });
  23343. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23344. get: function () {
  23345. return 2;
  23346. },
  23347. enumerable: true,
  23348. configurable: true
  23349. });
  23350. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23351. get: function () {
  23352. return 3;
  23353. },
  23354. enumerable: true,
  23355. configurable: true
  23356. });
  23357. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23358. get: function () {
  23359. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23360. },
  23361. set: function (value) {
  23362. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23363. },
  23364. enumerable: true,
  23365. configurable: true
  23366. });
  23367. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23368. get: function () {
  23369. return SceneLoader._ShowLoadingScreen;
  23370. },
  23371. set: function (value) {
  23372. SceneLoader._ShowLoadingScreen = value;
  23373. },
  23374. enumerable: true,
  23375. configurable: true
  23376. });
  23377. Object.defineProperty(SceneLoader, "loggingLevel", {
  23378. get: function () {
  23379. return SceneLoader._loggingLevel;
  23380. },
  23381. set: function (value) {
  23382. SceneLoader._loggingLevel = value;
  23383. },
  23384. enumerable: true,
  23385. configurable: true
  23386. });
  23387. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23388. var dotPosition = sceneFilename.lastIndexOf(".");
  23389. var queryStringPosition = sceneFilename.indexOf("?");
  23390. if (queryStringPosition === -1) {
  23391. queryStringPosition = sceneFilename.length;
  23392. }
  23393. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23394. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23395. var plugin = this._registeredPlugins[index];
  23396. if (plugin.extensions.indexOf(extension) !== -1) {
  23397. return plugin;
  23398. }
  23399. }
  23400. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23401. };
  23402. // Public functions
  23403. SceneLoader.GetPluginForExtension = function (extension) {
  23404. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23405. var plugin = this._registeredPlugins[index];
  23406. if (plugin.extensions.indexOf(extension) !== -1) {
  23407. return plugin;
  23408. }
  23409. }
  23410. return null;
  23411. };
  23412. SceneLoader.RegisterPlugin = function (plugin) {
  23413. plugin.extensions = plugin.extensions.toLowerCase();
  23414. SceneLoader._registeredPlugins.push(plugin);
  23415. };
  23416. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23417. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23418. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23419. return;
  23420. }
  23421. var loadingToken = {};
  23422. scene._addPendingData(loadingToken);
  23423. var manifestChecked = function (success) {
  23424. scene.database = database;
  23425. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23426. var importMeshFromData = function (data) {
  23427. var meshes = [];
  23428. var particleSystems = [];
  23429. var skeletons = [];
  23430. try {
  23431. if (plugin.importMesh) {
  23432. var syncedPlugin = plugin;
  23433. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23434. if (onerror) {
  23435. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23436. }
  23437. scene._removePendingData(loadingToken);
  23438. return;
  23439. }
  23440. if (onsuccess) {
  23441. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23442. onsuccess(meshes, particleSystems, skeletons);
  23443. scene._removePendingData(loadingToken);
  23444. }
  23445. }
  23446. else {
  23447. var asyncedPlugin = plugin;
  23448. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23449. if (onsuccess) {
  23450. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23451. onsuccess(meshes, particleSystems, skeletons);
  23452. scene._removePendingData(loadingToken);
  23453. }
  23454. }, function () {
  23455. if (onerror) {
  23456. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23457. }
  23458. scene._removePendingData(loadingToken);
  23459. });
  23460. }
  23461. }
  23462. catch (e) {
  23463. if (onerror) {
  23464. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  23465. }
  23466. scene._removePendingData(loadingToken);
  23467. }
  23468. };
  23469. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23470. // Direct load
  23471. importMeshFromData(sceneFilename.substr(5));
  23472. return;
  23473. }
  23474. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23475. importMeshFromData(data);
  23476. }, progressCallBack, database);
  23477. };
  23478. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23479. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23480. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23481. }
  23482. else {
  23483. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23484. manifestChecked(true);
  23485. }
  23486. };
  23487. /**
  23488. * Load a scene
  23489. * @param rootUrl a string that defines the root url for scene and resources
  23490. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23491. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23492. */
  23493. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23494. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23495. };
  23496. /**
  23497. * Append a scene
  23498. * @param rootUrl a string that defines the root url for scene and resources
  23499. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23500. * @param scene is the instance of BABYLON.Scene to append to
  23501. */
  23502. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23503. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23504. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23505. return;
  23506. }
  23507. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23508. var database;
  23509. var loadingToken = {};
  23510. scene._addPendingData(loadingToken);
  23511. if (SceneLoader.ShowLoadingScreen) {
  23512. scene.getEngine().displayLoadingUI();
  23513. }
  23514. var loadSceneFromData = function (data) {
  23515. scene.database = database;
  23516. if (plugin.load) {
  23517. var syncedPlugin = plugin;
  23518. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23519. if (onerror) {
  23520. onerror(scene);
  23521. }
  23522. scene._removePendingData(loadingToken);
  23523. scene.getEngine().hideLoadingUI();
  23524. return;
  23525. }
  23526. if (onsuccess) {
  23527. onsuccess(scene);
  23528. }
  23529. scene._removePendingData(loadingToken);
  23530. }
  23531. else {
  23532. var asyncedPlugin = plugin;
  23533. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23534. if (onsuccess) {
  23535. onsuccess(scene);
  23536. }
  23537. }, function () {
  23538. if (onerror) {
  23539. onerror(scene);
  23540. }
  23541. scene._removePendingData(loadingToken);
  23542. scene.getEngine().hideLoadingUI();
  23543. });
  23544. }
  23545. if (SceneLoader.ShowLoadingScreen) {
  23546. scene.executeWhenReady(function () {
  23547. scene.getEngine().hideLoadingUI();
  23548. });
  23549. }
  23550. };
  23551. var manifestChecked = function (success) {
  23552. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23553. };
  23554. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23555. // Direct load
  23556. loadSceneFromData(sceneFilename.substr(5));
  23557. return;
  23558. }
  23559. if (rootUrl.indexOf("file:") === -1) {
  23560. if (scene.getEngine().enableOfflineSupport) {
  23561. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23562. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23563. }
  23564. else {
  23565. manifestChecked(true);
  23566. }
  23567. }
  23568. else {
  23569. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23570. }
  23571. };
  23572. // Flags
  23573. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23574. SceneLoader._ShowLoadingScreen = true;
  23575. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23576. // Members
  23577. SceneLoader._registeredPlugins = new Array();
  23578. return SceneLoader;
  23579. }());
  23580. BABYLON.SceneLoader = SceneLoader;
  23581. ;
  23582. })(BABYLON || (BABYLON = {}));
  23583. var BABYLON;
  23584. (function (BABYLON) {
  23585. var Internals;
  23586. (function (Internals) {
  23587. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23588. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23589. var parsedMaterial = parsedData.materials[index];
  23590. if (parsedMaterial.id === id) {
  23591. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23592. }
  23593. }
  23594. return null;
  23595. };
  23596. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23597. names = (names instanceof Array) ? names : [names];
  23598. for (var i in names) {
  23599. if (mesh.name === names[i]) {
  23600. hierarchyIds.push(mesh.id);
  23601. return true;
  23602. }
  23603. }
  23604. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23605. hierarchyIds.push(mesh.id);
  23606. return true;
  23607. }
  23608. return false;
  23609. };
  23610. var logOperation = function (operation, producer) {
  23611. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23612. };
  23613. BABYLON.SceneLoader.RegisterPlugin({
  23614. extensions: ".babylon",
  23615. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23616. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23617. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23618. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23619. // and avoid problems with multiple concurrent .babylon loads.
  23620. var log = "importMesh has failed JSON parse";
  23621. try {
  23622. var parsedData = JSON.parse(data);
  23623. log = "";
  23624. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23625. var loadedSkeletonsIds = [];
  23626. var loadedMaterialsIds = [];
  23627. var hierarchyIds = [];
  23628. var index;
  23629. var cache;
  23630. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23631. var parsedMesh = parsedData.meshes[index];
  23632. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23633. if (meshesNames instanceof Array) {
  23634. // Remove found mesh name from list.
  23635. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23636. }
  23637. //Geometry?
  23638. if (parsedMesh.geometryId) {
  23639. //does the file contain geometries?
  23640. if (parsedData.geometries) {
  23641. //find the correct geometry and add it to the scene
  23642. var found = false;
  23643. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23644. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23645. return;
  23646. }
  23647. else {
  23648. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23649. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23650. switch (geometryType) {
  23651. case "boxes":
  23652. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23653. break;
  23654. case "spheres":
  23655. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23656. break;
  23657. case "cylinders":
  23658. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23659. break;
  23660. case "toruses":
  23661. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23662. break;
  23663. case "grounds":
  23664. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23665. break;
  23666. case "planes":
  23667. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23668. break;
  23669. case "torusKnots":
  23670. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23671. break;
  23672. case "vertexData":
  23673. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23674. break;
  23675. }
  23676. found = true;
  23677. }
  23678. });
  23679. }
  23680. });
  23681. if (!found) {
  23682. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23683. }
  23684. }
  23685. }
  23686. // Material ?
  23687. if (parsedMesh.materialId) {
  23688. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23689. if (!materialFound && parsedData.multiMaterials) {
  23690. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23691. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23692. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23693. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23694. var subMatId = parsedMultiMaterial.materials[matIndex];
  23695. loadedMaterialsIds.push(subMatId);
  23696. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23697. log += "\n\tMaterial " + mat.toString(fullDetails);
  23698. }
  23699. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23700. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23701. materialFound = true;
  23702. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23703. break;
  23704. }
  23705. }
  23706. }
  23707. if (!materialFound) {
  23708. loadedMaterialsIds.push(parsedMesh.materialId);
  23709. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23710. if (!mat) {
  23711. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23712. }
  23713. else {
  23714. log += "\n\tMaterial " + mat.toString(fullDetails);
  23715. }
  23716. }
  23717. }
  23718. // Skeleton ?
  23719. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23720. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23721. if (!skeletonAlreadyLoaded) {
  23722. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23723. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23724. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23725. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23726. skeletons.push(skeleton);
  23727. loadedSkeletonsIds.push(parsedSkeleton.id);
  23728. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23729. }
  23730. }
  23731. }
  23732. }
  23733. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23734. meshes.push(mesh);
  23735. log += "\n\tMesh " + mesh.toString(fullDetails);
  23736. }
  23737. }
  23738. // Connecting parents
  23739. var currentMesh;
  23740. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23741. currentMesh = scene.meshes[index];
  23742. if (currentMesh._waitingParentId) {
  23743. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23744. currentMesh._waitingParentId = undefined;
  23745. }
  23746. }
  23747. // freeze and compute world matrix application
  23748. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23749. currentMesh = scene.meshes[index];
  23750. if (currentMesh._waitingFreezeWorldMatrix) {
  23751. currentMesh.freezeWorldMatrix();
  23752. currentMesh._waitingFreezeWorldMatrix = undefined;
  23753. }
  23754. else {
  23755. currentMesh.computeWorldMatrix(true);
  23756. }
  23757. }
  23758. // Particles
  23759. if (parsedData.particleSystems) {
  23760. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23761. var parsedParticleSystem = parsedData.particleSystems[index];
  23762. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23763. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23764. }
  23765. }
  23766. }
  23767. return true;
  23768. }
  23769. catch (err) {
  23770. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23771. log = null;
  23772. throw err;
  23773. }
  23774. finally {
  23775. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23776. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23777. }
  23778. }
  23779. },
  23780. load: function (scene, data, rootUrl) {
  23781. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23782. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23783. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23784. // and avoid problems with multiple concurrent .babylon loads.
  23785. var log = "importScene has failed JSON parse";
  23786. try {
  23787. var parsedData = JSON.parse(data);
  23788. log = "";
  23789. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23790. // Scene
  23791. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23792. scene.autoClear = parsedData.autoClear;
  23793. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23794. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23795. if (parsedData.gravity) {
  23796. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23797. }
  23798. // Fog
  23799. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23800. scene.fogMode = parsedData.fogMode;
  23801. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23802. scene.fogStart = parsedData.fogStart;
  23803. scene.fogEnd = parsedData.fogEnd;
  23804. scene.fogDensity = parsedData.fogDensity;
  23805. log += "\tFog mode for scene: ";
  23806. switch (scene.fogMode) {
  23807. // getters not compiling, so using hardcoded
  23808. case 1:
  23809. log += "exp\n";
  23810. break;
  23811. case 2:
  23812. log += "exp2\n";
  23813. break;
  23814. case 3:
  23815. log += "linear\n";
  23816. break;
  23817. }
  23818. }
  23819. //Physics
  23820. if (parsedData.physicsEnabled) {
  23821. var physicsPlugin;
  23822. if (parsedData.physicsEngine === "cannon") {
  23823. physicsPlugin = new BABYLON.CannonJSPlugin();
  23824. }
  23825. else if (parsedData.physicsEngine === "oimo") {
  23826. physicsPlugin = new BABYLON.OimoJSPlugin();
  23827. }
  23828. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23829. //else - default engine, which is currently oimo
  23830. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23831. scene.enablePhysics(physicsGravity, physicsPlugin);
  23832. }
  23833. //collisions, if defined. otherwise, default is true
  23834. if (parsedData.collisionsEnabled != undefined) {
  23835. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23836. }
  23837. scene.workerCollisions = !!parsedData.workerCollisions;
  23838. var index;
  23839. var cache;
  23840. // Lights
  23841. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23842. var parsedLight = parsedData.lights[index];
  23843. var light = BABYLON.Light.Parse(parsedLight, scene);
  23844. log += (index === 0 ? "\n\tLights:" : "");
  23845. log += "\n\t\t" + light.toString(fullDetails);
  23846. }
  23847. // Animations
  23848. if (parsedData.animations) {
  23849. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23850. var parsedAnimation = parsedData.animations[index];
  23851. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23852. scene.animations.push(animation);
  23853. log += (index === 0 ? "\n\tAnimations:" : "");
  23854. log += "\n\t\t" + animation.toString(fullDetails);
  23855. }
  23856. }
  23857. // Materials
  23858. if (parsedData.materials) {
  23859. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23860. var parsedMaterial = parsedData.materials[index];
  23861. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23862. log += (index === 0 ? "\n\tMaterials:" : "");
  23863. log += "\n\t\t" + mat.toString(fullDetails);
  23864. }
  23865. }
  23866. if (parsedData.multiMaterials) {
  23867. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23868. var parsedMultiMaterial = parsedData.multiMaterials[index];
  23869. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23870. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  23871. log += "\n\t\t" + mmat.toString(fullDetails);
  23872. }
  23873. }
  23874. // Skeletons
  23875. if (parsedData.skeletons) {
  23876. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  23877. var parsedSkeleton = parsedData.skeletons[index];
  23878. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23879. log += (index === 0 ? "\n\tSkeletons:" : "");
  23880. log += "\n\t\t" + skeleton.toString(fullDetails);
  23881. }
  23882. }
  23883. // Geometries
  23884. var geometries = parsedData.geometries;
  23885. if (geometries) {
  23886. // Boxes
  23887. var boxes = geometries.boxes;
  23888. if (boxes) {
  23889. for (index = 0, cache = boxes.length; index < cache; index++) {
  23890. var parsedBox = boxes[index];
  23891. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  23892. }
  23893. }
  23894. // Spheres
  23895. var spheres = geometries.spheres;
  23896. if (spheres) {
  23897. for (index = 0, cache = spheres.length; index < cache; index++) {
  23898. var parsedSphere = spheres[index];
  23899. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  23900. }
  23901. }
  23902. // Cylinders
  23903. var cylinders = geometries.cylinders;
  23904. if (cylinders) {
  23905. for (index = 0, cache = cylinders.length; index < cache; index++) {
  23906. var parsedCylinder = cylinders[index];
  23907. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  23908. }
  23909. }
  23910. // Toruses
  23911. var toruses = geometries.toruses;
  23912. if (toruses) {
  23913. for (index = 0, cache = toruses.length; index < cache; index++) {
  23914. var parsedTorus = toruses[index];
  23915. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  23916. }
  23917. }
  23918. // Grounds
  23919. var grounds = geometries.grounds;
  23920. if (grounds) {
  23921. for (index = 0, cache = grounds.length; index < cache; index++) {
  23922. var parsedGround = grounds[index];
  23923. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  23924. }
  23925. }
  23926. // Planes
  23927. var planes = geometries.planes;
  23928. if (planes) {
  23929. for (index = 0, cache = planes.length; index < cache; index++) {
  23930. var parsedPlane = planes[index];
  23931. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  23932. }
  23933. }
  23934. // TorusKnots
  23935. var torusKnots = geometries.torusKnots;
  23936. if (torusKnots) {
  23937. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  23938. var parsedTorusKnot = torusKnots[index];
  23939. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  23940. }
  23941. }
  23942. // VertexData
  23943. var vertexData = geometries.vertexData;
  23944. if (vertexData) {
  23945. for (index = 0, cache = vertexData.length; index < cache; index++) {
  23946. var parsedVertexData = vertexData[index];
  23947. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  23948. }
  23949. }
  23950. }
  23951. // Meshes
  23952. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23953. var parsedMesh = parsedData.meshes[index];
  23954. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23955. log += (index === 0 ? "\n\tMeshes:" : "");
  23956. log += "\n\t\t" + mesh.toString(fullDetails);
  23957. }
  23958. // Cameras
  23959. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  23960. var parsedCamera = parsedData.cameras[index];
  23961. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  23962. log += (index === 0 ? "\n\tCameras:" : "");
  23963. log += "\n\t\t" + camera.toString(fullDetails);
  23964. }
  23965. if (parsedData.activeCameraID) {
  23966. scene.setActiveCameraByID(parsedData.activeCameraID);
  23967. }
  23968. // Browsing all the graph to connect the dots
  23969. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  23970. var camera = scene.cameras[index];
  23971. if (camera._waitingParentId) {
  23972. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  23973. camera._waitingParentId = undefined;
  23974. }
  23975. }
  23976. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  23977. var light = scene.lights[index];
  23978. if (light._waitingParentId) {
  23979. light.parent = scene.getLastEntryByID(light._waitingParentId);
  23980. light._waitingParentId = undefined;
  23981. }
  23982. }
  23983. // Sounds
  23984. var loadedSounds = [];
  23985. var loadedSound;
  23986. if (BABYLON.AudioEngine && parsedData.sounds) {
  23987. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  23988. var parsedSound = parsedData.sounds[index];
  23989. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  23990. if (!parsedSound.url)
  23991. parsedSound.url = parsedSound.name;
  23992. if (!loadedSounds[parsedSound.url]) {
  23993. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  23994. loadedSounds[parsedSound.url] = loadedSound;
  23995. }
  23996. else {
  23997. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  23998. }
  23999. }
  24000. else {
  24001. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24002. }
  24003. }
  24004. }
  24005. loadedSounds = [];
  24006. // Connect parents & children and parse actions
  24007. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24008. var mesh = scene.meshes[index];
  24009. if (mesh._waitingParentId) {
  24010. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24011. mesh._waitingParentId = undefined;
  24012. }
  24013. if (mesh._waitingActions) {
  24014. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24015. mesh._waitingActions = undefined;
  24016. }
  24017. }
  24018. // freeze world matrix application
  24019. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24020. var currentMesh = scene.meshes[index];
  24021. if (currentMesh._waitingFreezeWorldMatrix) {
  24022. currentMesh.freezeWorldMatrix();
  24023. currentMesh._waitingFreezeWorldMatrix = undefined;
  24024. }
  24025. else {
  24026. currentMesh.computeWorldMatrix(true);
  24027. }
  24028. }
  24029. // Particles Systems
  24030. if (parsedData.particleSystems) {
  24031. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24032. var parsedParticleSystem = parsedData.particleSystems[index];
  24033. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24034. }
  24035. }
  24036. // Lens flares
  24037. if (parsedData.lensFlareSystems) {
  24038. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24039. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24040. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24041. }
  24042. }
  24043. // Shadows
  24044. if (parsedData.shadowGenerators) {
  24045. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24046. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24047. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24048. }
  24049. }
  24050. // Actions (scene)
  24051. if (parsedData.actions) {
  24052. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24053. }
  24054. // Finish
  24055. return true;
  24056. }
  24057. catch (err) {
  24058. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24059. log = null;
  24060. throw err;
  24061. }
  24062. finally {
  24063. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24064. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24065. }
  24066. }
  24067. }
  24068. });
  24069. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24070. })(BABYLON || (BABYLON = {}));
  24071. var BABYLON;
  24072. (function (BABYLON) {
  24073. var SpriteManager = (function () {
  24074. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24076. this.name = name;
  24077. this.cellSize = cellSize;
  24078. this.sprites = new Array();
  24079. this.renderingGroupId = 0;
  24080. this.layerMask = 0x0FFFFFFF;
  24081. this.fogEnabled = true;
  24082. this.isPickable = false;
  24083. this._vertexDeclaration = [4, 4, 4, 4];
  24084. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24085. this._capacity = capacity;
  24086. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24087. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24088. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24089. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24090. this._scene = scene;
  24091. this._scene.spriteManagers.push(this);
  24092. // VBO
  24093. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24094. var indices = [];
  24095. var index = 0;
  24096. for (var count = 0; count < capacity; count++) {
  24097. indices.push(index);
  24098. indices.push(index + 1);
  24099. indices.push(index + 2);
  24100. indices.push(index);
  24101. indices.push(index + 2);
  24102. indices.push(index + 3);
  24103. index += 4;
  24104. }
  24105. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24106. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24107. // Effects
  24108. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24109. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24110. }
  24111. Object.defineProperty(SpriteManager.prototype, "texture", {
  24112. get: function () {
  24113. return this._spriteTexture;
  24114. },
  24115. set: function (value) {
  24116. this._spriteTexture = value;
  24117. },
  24118. enumerable: true,
  24119. configurable: true
  24120. });
  24121. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24122. var arrayOffset = index * 16;
  24123. if (offsetX === 0)
  24124. offsetX = this._epsilon;
  24125. else if (offsetX === 1)
  24126. offsetX = 1 - this._epsilon;
  24127. if (offsetY === 0)
  24128. offsetY = this._epsilon;
  24129. else if (offsetY === 1)
  24130. offsetY = 1 - this._epsilon;
  24131. this._vertices[arrayOffset] = sprite.position.x;
  24132. this._vertices[arrayOffset + 1] = sprite.position.y;
  24133. this._vertices[arrayOffset + 2] = sprite.position.z;
  24134. this._vertices[arrayOffset + 3] = sprite.angle;
  24135. this._vertices[arrayOffset + 4] = sprite.width;
  24136. this._vertices[arrayOffset + 5] = sprite.height;
  24137. this._vertices[arrayOffset + 6] = offsetX;
  24138. this._vertices[arrayOffset + 7] = offsetY;
  24139. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24140. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24141. var offset = (sprite.cellIndex / rowSize) >> 0;
  24142. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24143. this._vertices[arrayOffset + 11] = offset;
  24144. // Color
  24145. this._vertices[arrayOffset + 12] = sprite.color.r;
  24146. this._vertices[arrayOffset + 13] = sprite.color.g;
  24147. this._vertices[arrayOffset + 14] = sprite.color.b;
  24148. this._vertices[arrayOffset + 15] = sprite.color.a;
  24149. };
  24150. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24151. var count = Math.min(this._capacity, this.sprites.length);
  24152. var min = BABYLON.Vector3.Zero();
  24153. var max = BABYLON.Vector3.Zero();
  24154. var distance = Number.MAX_VALUE;
  24155. var currentSprite;
  24156. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24157. var cameraView = camera.getViewMatrix();
  24158. for (var index = 0; index < count; index++) {
  24159. var sprite = this.sprites[index];
  24160. if (!sprite) {
  24161. continue;
  24162. }
  24163. if (predicate) {
  24164. if (!predicate(sprite)) {
  24165. continue;
  24166. }
  24167. }
  24168. else if (!sprite.isPickable) {
  24169. continue;
  24170. }
  24171. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24172. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24173. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24174. if (ray.intersectsBoxMinMax(min, max)) {
  24175. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24176. if (distance > currentDistance) {
  24177. distance = currentDistance;
  24178. currentSprite = sprite;
  24179. if (fastCheck) {
  24180. break;
  24181. }
  24182. }
  24183. }
  24184. }
  24185. if (currentSprite) {
  24186. var result = new BABYLON.PickingInfo();
  24187. result.hit = true;
  24188. result.pickedSprite = currentSprite;
  24189. result.distance = distance;
  24190. return result;
  24191. }
  24192. return null;
  24193. };
  24194. SpriteManager.prototype.render = function () {
  24195. // Check
  24196. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24197. return;
  24198. var engine = this._scene.getEngine();
  24199. var baseSize = this._spriteTexture.getBaseSize();
  24200. // Sprites
  24201. var deltaTime = engine.getDeltaTime();
  24202. var max = Math.min(this._capacity, this.sprites.length);
  24203. var rowSize = baseSize.width / this.cellSize;
  24204. var offset = 0;
  24205. for (var index = 0; index < max; index++) {
  24206. var sprite = this.sprites[index];
  24207. if (!sprite) {
  24208. continue;
  24209. }
  24210. sprite._animate(deltaTime);
  24211. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24212. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24213. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24214. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24215. }
  24216. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24217. // Render
  24218. var effect = this._effectBase;
  24219. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24220. effect = this._effectFog;
  24221. }
  24222. engine.enableEffect(effect);
  24223. var viewMatrix = this._scene.getViewMatrix();
  24224. effect.setTexture("diffuseSampler", this._spriteTexture);
  24225. effect.setMatrix("view", viewMatrix);
  24226. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24227. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24228. // Fog
  24229. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24230. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24231. effect.setColor3("vFogColor", this._scene.fogColor);
  24232. }
  24233. // VBOs
  24234. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24235. // Draw order
  24236. engine.setDepthFunctionToLessOrEqual();
  24237. effect.setBool("alphaTest", true);
  24238. engine.setColorWrite(false);
  24239. engine.draw(true, 0, max * 6);
  24240. engine.setColorWrite(true);
  24241. effect.setBool("alphaTest", false);
  24242. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24243. engine.draw(true, 0, max * 6);
  24244. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24245. };
  24246. SpriteManager.prototype.dispose = function () {
  24247. if (this._vertexBuffer) {
  24248. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24249. this._vertexBuffer = null;
  24250. }
  24251. if (this._indexBuffer) {
  24252. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24253. this._indexBuffer = null;
  24254. }
  24255. if (this._spriteTexture) {
  24256. this._spriteTexture.dispose();
  24257. this._spriteTexture = null;
  24258. }
  24259. // Remove from scene
  24260. var index = this._scene.spriteManagers.indexOf(this);
  24261. this._scene.spriteManagers.splice(index, 1);
  24262. // Callback
  24263. if (this.onDispose) {
  24264. this.onDispose();
  24265. }
  24266. };
  24267. return SpriteManager;
  24268. }());
  24269. BABYLON.SpriteManager = SpriteManager;
  24270. })(BABYLON || (BABYLON = {}));
  24271. var BABYLON;
  24272. (function (BABYLON) {
  24273. var Sprite = (function () {
  24274. function Sprite(name, manager) {
  24275. this.name = name;
  24276. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24277. this.width = 1.0;
  24278. this.height = 1.0;
  24279. this.angle = 0;
  24280. this.cellIndex = 0;
  24281. this.invertU = 0;
  24282. this.invertV = 0;
  24283. this.animations = new Array();
  24284. this.isPickable = false;
  24285. this._animationStarted = false;
  24286. this._loopAnimation = false;
  24287. this._fromIndex = 0;
  24288. this._toIndex = 0;
  24289. this._delay = 0;
  24290. this._direction = 1;
  24291. this._frameCount = 0;
  24292. this._time = 0;
  24293. this._manager = manager;
  24294. this._manager.sprites.push(this);
  24295. this.position = BABYLON.Vector3.Zero();
  24296. }
  24297. Object.defineProperty(Sprite.prototype, "size", {
  24298. get: function () {
  24299. return this.width;
  24300. },
  24301. set: function (value) {
  24302. this.width = value;
  24303. this.height = value;
  24304. },
  24305. enumerable: true,
  24306. configurable: true
  24307. });
  24308. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24309. this._fromIndex = from;
  24310. this._toIndex = to;
  24311. this._loopAnimation = loop;
  24312. this._delay = delay;
  24313. this._animationStarted = true;
  24314. this._direction = from < to ? 1 : -1;
  24315. this.cellIndex = from;
  24316. this._time = 0;
  24317. };
  24318. Sprite.prototype.stopAnimation = function () {
  24319. this._animationStarted = false;
  24320. };
  24321. Sprite.prototype._animate = function (deltaTime) {
  24322. if (!this._animationStarted)
  24323. return;
  24324. this._time += deltaTime;
  24325. if (this._time > this._delay) {
  24326. this._time = this._time % this._delay;
  24327. this.cellIndex += this._direction;
  24328. if (this.cellIndex == this._toIndex) {
  24329. if (this._loopAnimation) {
  24330. this.cellIndex = this._fromIndex;
  24331. }
  24332. else {
  24333. this._animationStarted = false;
  24334. if (this.disposeWhenFinishedAnimating) {
  24335. this.dispose();
  24336. }
  24337. }
  24338. }
  24339. }
  24340. };
  24341. Sprite.prototype.dispose = function () {
  24342. for (var i = 0; i < this._manager.sprites.length; i++) {
  24343. if (this._manager.sprites[i] == this) {
  24344. this._manager.sprites.splice(i, 1);
  24345. }
  24346. }
  24347. };
  24348. return Sprite;
  24349. }());
  24350. BABYLON.Sprite = Sprite;
  24351. })(BABYLON || (BABYLON = {}));
  24352. var BABYLON;
  24353. (function (BABYLON) {
  24354. var Layer = (function () {
  24355. function Layer(name, imgUrl, scene, isBackground, color) {
  24356. this.name = name;
  24357. this.scale = new BABYLON.Vector2(1, 1);
  24358. this.offset = new BABYLON.Vector2(0, 0);
  24359. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24360. this._vertexDeclaration = [2];
  24361. this._vertexStrideSize = 2 * 4;
  24362. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24363. this.isBackground = isBackground === undefined ? true : isBackground;
  24364. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24365. this._scene = scene;
  24366. this._scene.layers.push(this);
  24367. // VBO
  24368. var vertices = [];
  24369. vertices.push(1, 1);
  24370. vertices.push(-1, 1);
  24371. vertices.push(-1, -1);
  24372. vertices.push(1, -1);
  24373. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24374. // Indices
  24375. var indices = [];
  24376. indices.push(0);
  24377. indices.push(1);
  24378. indices.push(2);
  24379. indices.push(0);
  24380. indices.push(2);
  24381. indices.push(3);
  24382. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24383. // Effects
  24384. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24385. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24386. }
  24387. Layer.prototype.render = function () {
  24388. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24389. // Check
  24390. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24391. return;
  24392. var engine = this._scene.getEngine();
  24393. if (this.onBeforeRender) {
  24394. this.onBeforeRender();
  24395. }
  24396. // Render
  24397. engine.enableEffect(currentEffect);
  24398. engine.setState(false);
  24399. // Texture
  24400. currentEffect.setTexture("textureSampler", this.texture);
  24401. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24402. // Color
  24403. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24404. // Scale / offset
  24405. currentEffect.setVector2("offset", this.offset);
  24406. currentEffect.setVector2("scale", this.scale);
  24407. // VBOs
  24408. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24409. // Draw order
  24410. if (!this._alphaTestEffect) {
  24411. engine.setAlphaMode(this.alphaBlendingMode);
  24412. engine.draw(true, 0, 6);
  24413. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24414. }
  24415. else {
  24416. engine.draw(true, 0, 6);
  24417. }
  24418. if (this.onAfterRender) {
  24419. this.onAfterRender();
  24420. }
  24421. };
  24422. Layer.prototype.dispose = function () {
  24423. if (this._vertexBuffer) {
  24424. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24425. this._vertexBuffer = null;
  24426. }
  24427. if (this._indexBuffer) {
  24428. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24429. this._indexBuffer = null;
  24430. }
  24431. if (this.texture) {
  24432. this.texture.dispose();
  24433. this.texture = null;
  24434. }
  24435. // Remove from scene
  24436. var index = this._scene.layers.indexOf(this);
  24437. this._scene.layers.splice(index, 1);
  24438. // Callback
  24439. if (this.onDispose) {
  24440. this.onDispose();
  24441. }
  24442. };
  24443. return Layer;
  24444. }());
  24445. BABYLON.Layer = Layer;
  24446. })(BABYLON || (BABYLON = {}));
  24447. var BABYLON;
  24448. (function (BABYLON) {
  24449. var Particle = (function () {
  24450. function Particle() {
  24451. this.position = BABYLON.Vector3.Zero();
  24452. this.direction = BABYLON.Vector3.Zero();
  24453. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24454. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24455. this.lifeTime = 1.0;
  24456. this.age = 0;
  24457. this.size = 0;
  24458. this.angle = 0;
  24459. this.angularSpeed = 0;
  24460. }
  24461. Particle.prototype.copyTo = function (other) {
  24462. other.position.copyFrom(this.position);
  24463. other.direction.copyFrom(this.direction);
  24464. other.color.copyFrom(this.color);
  24465. other.colorStep.copyFrom(this.colorStep);
  24466. other.lifeTime = this.lifeTime;
  24467. other.age = this.age;
  24468. other.size = this.size;
  24469. other.angle = this.angle;
  24470. other.angularSpeed = this.angularSpeed;
  24471. };
  24472. return Particle;
  24473. }());
  24474. BABYLON.Particle = Particle;
  24475. })(BABYLON || (BABYLON = {}));
  24476. var BABYLON;
  24477. (function (BABYLON) {
  24478. var randomNumber = function (min, max) {
  24479. if (min === max) {
  24480. return (min);
  24481. }
  24482. var random = Math.random();
  24483. return ((random * (max - min)) + min);
  24484. };
  24485. var ParticleSystem = (function () {
  24486. function ParticleSystem(name, capacity, scene, customEffect) {
  24487. var _this = this;
  24488. this.name = name;
  24489. // Members
  24490. this.animations = [];
  24491. this.renderingGroupId = 0;
  24492. this.emitter = null;
  24493. this.emitRate = 10;
  24494. this.manualEmitCount = -1;
  24495. this.updateSpeed = 0.01;
  24496. this.targetStopDuration = 0;
  24497. this.disposeOnStop = false;
  24498. this.minEmitPower = 1;
  24499. this.maxEmitPower = 1;
  24500. this.minLifeTime = 1;
  24501. this.maxLifeTime = 1;
  24502. this.minSize = 1;
  24503. this.maxSize = 1;
  24504. this.minAngularSpeed = 0;
  24505. this.maxAngularSpeed = 0;
  24506. this.layerMask = 0x0FFFFFFF;
  24507. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24508. this.forceDepthWrite = false;
  24509. this.gravity = BABYLON.Vector3.Zero();
  24510. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24511. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24512. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24513. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24514. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24515. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24516. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24517. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24518. this.particles = new Array();
  24519. this._vertexDeclaration = [3, 4, 4];
  24520. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24521. this._stockParticles = new Array();
  24522. this._newPartsExcess = 0;
  24523. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24524. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24525. this._scaledDirection = BABYLON.Vector3.Zero();
  24526. this._scaledGravity = BABYLON.Vector3.Zero();
  24527. this._currentRenderId = -1;
  24528. this._started = false;
  24529. this._stopped = false;
  24530. this._actualFrame = 0;
  24531. this.id = name;
  24532. this._capacity = capacity;
  24533. this._scene = scene;
  24534. this._customEffect = customEffect;
  24535. scene.particleSystems.push(this);
  24536. // VBO
  24537. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24538. var indices = [];
  24539. var index = 0;
  24540. for (var count = 0; count < capacity; count++) {
  24541. indices.push(index);
  24542. indices.push(index + 1);
  24543. indices.push(index + 2);
  24544. indices.push(index);
  24545. indices.push(index + 2);
  24546. indices.push(index + 3);
  24547. index += 4;
  24548. }
  24549. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24550. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24551. // Default behaviors
  24552. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24553. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24554. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24555. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24556. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24557. };
  24558. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24559. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24560. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24561. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24562. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24563. };
  24564. this.updateFunction = function (particles) {
  24565. for (var index = 0; index < particles.length; index++) {
  24566. var particle = particles[index];
  24567. particle.age += _this._scaledUpdateSpeed;
  24568. if (particle.age >= particle.lifeTime) {
  24569. _this.recycleParticle(particle);
  24570. index--;
  24571. continue;
  24572. }
  24573. else {
  24574. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24575. particle.color.addInPlace(_this._scaledColorStep);
  24576. if (particle.color.a < 0)
  24577. particle.color.a = 0;
  24578. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24579. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24580. particle.position.addInPlace(_this._scaledDirection);
  24581. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24582. particle.direction.addInPlace(_this._scaledGravity);
  24583. }
  24584. }
  24585. };
  24586. }
  24587. ParticleSystem.prototype.recycleParticle = function (particle) {
  24588. var lastParticle = this.particles.pop();
  24589. if (lastParticle !== particle) {
  24590. lastParticle.copyTo(particle);
  24591. this._stockParticles.push(lastParticle);
  24592. }
  24593. };
  24594. ParticleSystem.prototype.getCapacity = function () {
  24595. return this._capacity;
  24596. };
  24597. ParticleSystem.prototype.isAlive = function () {
  24598. return this._alive;
  24599. };
  24600. ParticleSystem.prototype.isStarted = function () {
  24601. return this._started;
  24602. };
  24603. ParticleSystem.prototype.start = function () {
  24604. this._started = true;
  24605. this._stopped = false;
  24606. this._actualFrame = 0;
  24607. };
  24608. ParticleSystem.prototype.stop = function () {
  24609. this._stopped = true;
  24610. };
  24611. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24612. var offset = index * 11;
  24613. this._vertices[offset] = particle.position.x;
  24614. this._vertices[offset + 1] = particle.position.y;
  24615. this._vertices[offset + 2] = particle.position.z;
  24616. this._vertices[offset + 3] = particle.color.r;
  24617. this._vertices[offset + 4] = particle.color.g;
  24618. this._vertices[offset + 5] = particle.color.b;
  24619. this._vertices[offset + 6] = particle.color.a;
  24620. this._vertices[offset + 7] = particle.angle;
  24621. this._vertices[offset + 8] = particle.size;
  24622. this._vertices[offset + 9] = offsetX;
  24623. this._vertices[offset + 10] = offsetY;
  24624. };
  24625. ParticleSystem.prototype._update = function (newParticles) {
  24626. // Update current
  24627. this._alive = this.particles.length > 0;
  24628. this.updateFunction(this.particles);
  24629. // Add new ones
  24630. var worldMatrix;
  24631. if (this.emitter.position) {
  24632. worldMatrix = this.emitter.getWorldMatrix();
  24633. }
  24634. else {
  24635. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24636. }
  24637. var particle;
  24638. for (var index = 0; index < newParticles; index++) {
  24639. if (this.particles.length === this._capacity) {
  24640. break;
  24641. }
  24642. if (this._stockParticles.length !== 0) {
  24643. particle = this._stockParticles.pop();
  24644. particle.age = 0;
  24645. }
  24646. else {
  24647. particle = new BABYLON.Particle();
  24648. }
  24649. this.particles.push(particle);
  24650. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24651. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24652. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24653. particle.size = randomNumber(this.minSize, this.maxSize);
  24654. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24655. this.startPositionFunction(worldMatrix, particle.position, particle);
  24656. var step = randomNumber(0, 1.0);
  24657. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24658. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24659. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24660. }
  24661. };
  24662. ParticleSystem.prototype._getEffect = function () {
  24663. if (this._customEffect) {
  24664. return this._customEffect;
  24665. }
  24666. ;
  24667. var defines = [];
  24668. if (this._scene.clipPlane) {
  24669. defines.push("#define CLIPPLANE");
  24670. }
  24671. // Effect
  24672. var join = defines.join("\n");
  24673. if (this._cachedDefines !== join) {
  24674. this._cachedDefines = join;
  24675. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24676. }
  24677. return this._effect;
  24678. };
  24679. ParticleSystem.prototype.animate = function () {
  24680. if (!this._started)
  24681. return;
  24682. var effect = this._getEffect();
  24683. // Check
  24684. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24685. return;
  24686. if (this._currentRenderId === this._scene.getRenderId()) {
  24687. return;
  24688. }
  24689. this._currentRenderId = this._scene.getRenderId();
  24690. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24691. // determine the number of particles we need to create
  24692. var newParticles;
  24693. if (this.manualEmitCount > -1) {
  24694. newParticles = this.manualEmitCount;
  24695. this._newPartsExcess = 0;
  24696. this.manualEmitCount = 0;
  24697. }
  24698. else {
  24699. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24700. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24701. }
  24702. if (this._newPartsExcess > 1.0) {
  24703. newParticles += this._newPartsExcess >> 0;
  24704. this._newPartsExcess -= this._newPartsExcess >> 0;
  24705. }
  24706. this._alive = false;
  24707. if (!this._stopped) {
  24708. this._actualFrame += this._scaledUpdateSpeed;
  24709. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24710. this.stop();
  24711. }
  24712. else {
  24713. newParticles = 0;
  24714. }
  24715. this._update(newParticles);
  24716. // Stopped?
  24717. if (this._stopped) {
  24718. if (!this._alive) {
  24719. this._started = false;
  24720. if (this.disposeOnStop) {
  24721. this._scene._toBeDisposed.push(this);
  24722. }
  24723. }
  24724. }
  24725. // Update VBO
  24726. var offset = 0;
  24727. for (var index = 0; index < this.particles.length; index++) {
  24728. var particle = this.particles[index];
  24729. this._appendParticleVertex(offset++, particle, 0, 0);
  24730. this._appendParticleVertex(offset++, particle, 1, 0);
  24731. this._appendParticleVertex(offset++, particle, 1, 1);
  24732. this._appendParticleVertex(offset++, particle, 0, 1);
  24733. }
  24734. var engine = this._scene.getEngine();
  24735. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24736. };
  24737. ParticleSystem.prototype.render = function () {
  24738. var effect = this._getEffect();
  24739. // Check
  24740. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24741. return 0;
  24742. var engine = this._scene.getEngine();
  24743. // Render
  24744. engine.enableEffect(effect);
  24745. engine.setState(false);
  24746. var viewMatrix = this._scene.getViewMatrix();
  24747. effect.setTexture("diffuseSampler", this.particleTexture);
  24748. effect.setMatrix("view", viewMatrix);
  24749. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24750. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24751. if (this._scene.clipPlane) {
  24752. var clipPlane = this._scene.clipPlane;
  24753. var invView = viewMatrix.clone();
  24754. invView.invert();
  24755. effect.setMatrix("invView", invView);
  24756. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24757. }
  24758. // VBOs
  24759. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24760. // Draw order
  24761. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24762. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24763. }
  24764. else {
  24765. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24766. }
  24767. if (this.forceDepthWrite) {
  24768. engine.setDepthWrite(true);
  24769. }
  24770. engine.draw(true, 0, this.particles.length * 6);
  24771. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24772. return this.particles.length;
  24773. };
  24774. ParticleSystem.prototype.dispose = function () {
  24775. if (this._vertexBuffer) {
  24776. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24777. this._vertexBuffer = null;
  24778. }
  24779. if (this._indexBuffer) {
  24780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24781. this._indexBuffer = null;
  24782. }
  24783. if (this.particleTexture) {
  24784. this.particleTexture.dispose();
  24785. this.particleTexture = null;
  24786. }
  24787. // Remove from scene
  24788. var index = this._scene.particleSystems.indexOf(this);
  24789. this._scene.particleSystems.splice(index, 1);
  24790. // Callback
  24791. if (this.onDispose) {
  24792. this.onDispose();
  24793. }
  24794. };
  24795. // Clone
  24796. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24797. var result = new ParticleSystem(name, this._capacity, this._scene);
  24798. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24799. if (newEmitter === undefined) {
  24800. newEmitter = this.emitter;
  24801. }
  24802. result.emitter = newEmitter;
  24803. if (this.particleTexture) {
  24804. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24805. }
  24806. result.start();
  24807. return result;
  24808. };
  24809. ParticleSystem.prototype.serialize = function () {
  24810. var serializationObject = {};
  24811. serializationObject.name = this.name;
  24812. serializationObject.id = this.id;
  24813. // Emitter
  24814. if (this.emitter.position) {
  24815. serializationObject.emitterId = this.emitter.id;
  24816. }
  24817. else {
  24818. serializationObject.emitter = this.emitter.asArray();
  24819. }
  24820. serializationObject.capacity = this.getCapacity();
  24821. if (this.particleTexture) {
  24822. serializationObject.textureName = this.particleTexture.name;
  24823. }
  24824. // Animations
  24825. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24826. // Particle system
  24827. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24828. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24829. serializationObject.minSize = this.minSize;
  24830. serializationObject.maxSize = this.maxSize;
  24831. serializationObject.minEmitPower = this.minEmitPower;
  24832. serializationObject.maxEmitPower = this.maxEmitPower;
  24833. serializationObject.minLifeTime = this.minLifeTime;
  24834. serializationObject.maxLifeTime = this.maxLifeTime;
  24835. serializationObject.emitRate = this.emitRate;
  24836. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24837. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24838. serializationObject.gravity = this.gravity.asArray();
  24839. serializationObject.direction1 = this.direction1.asArray();
  24840. serializationObject.direction2 = this.direction2.asArray();
  24841. serializationObject.color1 = this.color1.asArray();
  24842. serializationObject.color2 = this.color2.asArray();
  24843. serializationObject.colorDead = this.colorDead.asArray();
  24844. serializationObject.updateSpeed = this.updateSpeed;
  24845. serializationObject.targetStopDuration = this.targetStopDuration;
  24846. serializationObject.textureMask = this.textureMask.asArray();
  24847. serializationObject.blendMode = this.blendMode;
  24848. return serializationObject;
  24849. };
  24850. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24851. var name = parsedParticleSystem.name;
  24852. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24853. if (parsedParticleSystem.id) {
  24854. particleSystem.id = parsedParticleSystem.id;
  24855. }
  24856. // Texture
  24857. if (parsedParticleSystem.textureName) {
  24858. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24859. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24860. }
  24861. // Emitter
  24862. if (parsedParticleSystem.emitterId) {
  24863. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24864. }
  24865. else {
  24866. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24867. }
  24868. // Animations
  24869. if (parsedParticleSystem.animations) {
  24870. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  24871. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  24872. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24873. }
  24874. }
  24875. if (parsedParticleSystem.autoAnimate) {
  24876. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  24877. }
  24878. // Particle system
  24879. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  24880. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  24881. particleSystem.minSize = parsedParticleSystem.minSize;
  24882. particleSystem.maxSize = parsedParticleSystem.maxSize;
  24883. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  24884. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  24885. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  24886. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  24887. particleSystem.emitRate = parsedParticleSystem.emitRate;
  24888. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  24889. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  24890. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  24891. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  24892. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  24893. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  24894. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  24895. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  24896. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  24897. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  24898. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  24899. particleSystem.blendMode = parsedParticleSystem.blendMode;
  24900. particleSystem.start();
  24901. return particleSystem;
  24902. };
  24903. // Statics
  24904. ParticleSystem.BLENDMODE_ONEONE = 0;
  24905. ParticleSystem.BLENDMODE_STANDARD = 1;
  24906. return ParticleSystem;
  24907. }());
  24908. BABYLON.ParticleSystem = ParticleSystem;
  24909. })(BABYLON || (BABYLON = {}));
  24910. var BABYLON;
  24911. (function (BABYLON) {
  24912. var AnimationRange = (function () {
  24913. function AnimationRange(name, from, to) {
  24914. this.name = name;
  24915. this.from = from;
  24916. this.to = to;
  24917. }
  24918. AnimationRange.prototype.clone = function () {
  24919. return new AnimationRange(this.name, this.from, this.to);
  24920. };
  24921. return AnimationRange;
  24922. }());
  24923. BABYLON.AnimationRange = AnimationRange;
  24924. /**
  24925. * Composed of a frame, and an action function
  24926. */
  24927. var AnimationEvent = (function () {
  24928. function AnimationEvent(frame, action, onlyOnce) {
  24929. this.frame = frame;
  24930. this.action = action;
  24931. this.onlyOnce = onlyOnce;
  24932. this.isDone = false;
  24933. }
  24934. return AnimationEvent;
  24935. }());
  24936. BABYLON.AnimationEvent = AnimationEvent;
  24937. var PathCursor = (function () {
  24938. function PathCursor(path) {
  24939. this.path = path;
  24940. this._onchange = new Array();
  24941. this.value = 0;
  24942. this.animations = new Array();
  24943. }
  24944. PathCursor.prototype.getPoint = function () {
  24945. var point = this.path.getPointAtLengthPosition(this.value);
  24946. return new BABYLON.Vector3(point.x, 0, point.y);
  24947. };
  24948. PathCursor.prototype.moveAhead = function (step) {
  24949. if (step === void 0) { step = 0.002; }
  24950. this.move(step);
  24951. return this;
  24952. };
  24953. PathCursor.prototype.moveBack = function (step) {
  24954. if (step === void 0) { step = 0.002; }
  24955. this.move(-step);
  24956. return this;
  24957. };
  24958. PathCursor.prototype.move = function (step) {
  24959. if (Math.abs(step) > 1) {
  24960. throw "step size should be less than 1.";
  24961. }
  24962. this.value += step;
  24963. this.ensureLimits();
  24964. this.raiseOnChange();
  24965. return this;
  24966. };
  24967. PathCursor.prototype.ensureLimits = function () {
  24968. while (this.value > 1) {
  24969. this.value -= 1;
  24970. }
  24971. while (this.value < 0) {
  24972. this.value += 1;
  24973. }
  24974. return this;
  24975. };
  24976. // used by animation engine
  24977. PathCursor.prototype.markAsDirty = function (propertyName) {
  24978. this.ensureLimits();
  24979. this.raiseOnChange();
  24980. return this;
  24981. };
  24982. PathCursor.prototype.raiseOnChange = function () {
  24983. var _this = this;
  24984. this._onchange.forEach(function (f) { return f(_this); });
  24985. return this;
  24986. };
  24987. PathCursor.prototype.onchange = function (f) {
  24988. this._onchange.push(f);
  24989. return this;
  24990. };
  24991. return PathCursor;
  24992. }());
  24993. BABYLON.PathCursor = PathCursor;
  24994. var Animation = (function () {
  24995. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  24996. this.name = name;
  24997. this.targetProperty = targetProperty;
  24998. this.framePerSecond = framePerSecond;
  24999. this.dataType = dataType;
  25000. this.loopMode = loopMode;
  25001. this.enableBlending = enableBlending;
  25002. this._offsetsCache = {};
  25003. this._highLimitsCache = {};
  25004. this._stopped = false;
  25005. this._blendingFactor = 0;
  25006. // The set of event that will be linked to this animation
  25007. this._events = new Array();
  25008. this.allowMatricesInterpolation = false;
  25009. this.blendingSpeed = 0.01;
  25010. this._ranges = {};
  25011. this.targetPropertyPath = targetProperty.split(".");
  25012. this.dataType = dataType;
  25013. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25014. }
  25015. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25016. var dataType = undefined;
  25017. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25018. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25019. }
  25020. else if (from instanceof BABYLON.Quaternion) {
  25021. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25022. }
  25023. else if (from instanceof BABYLON.Vector3) {
  25024. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25025. }
  25026. else if (from instanceof BABYLON.Vector2) {
  25027. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25028. }
  25029. else if (from instanceof BABYLON.Color3) {
  25030. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25031. }
  25032. if (dataType == undefined) {
  25033. return null;
  25034. }
  25035. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25036. var keys = [];
  25037. keys.push({ frame: 0, value: from });
  25038. keys.push({ frame: totalFrame, value: to });
  25039. animation.setKeys(keys);
  25040. if (easingFunction !== undefined) {
  25041. animation.setEasingFunction(easingFunction);
  25042. }
  25043. return animation;
  25044. };
  25045. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25046. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25047. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25048. };
  25049. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25050. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25051. node.animations.push(animation);
  25052. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25053. };
  25054. // Methods
  25055. /**
  25056. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25057. */
  25058. Animation.prototype.toString = function (fullDetails) {
  25059. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25060. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25061. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25062. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25063. if (fullDetails) {
  25064. ret += ", Ranges: {";
  25065. var first = true;
  25066. for (var name in this._ranges) {
  25067. if (!first) {
  25068. ret + ", ";
  25069. first = false;
  25070. }
  25071. ret += name;
  25072. }
  25073. ret += "}";
  25074. }
  25075. return ret;
  25076. };
  25077. /**
  25078. * Add an event to this animation.
  25079. */
  25080. Animation.prototype.addEvent = function (event) {
  25081. this._events.push(event);
  25082. };
  25083. /**
  25084. * Remove all events found at the given frame
  25085. * @param frame
  25086. */
  25087. Animation.prototype.removeEvents = function (frame) {
  25088. for (var index = 0; index < this._events.length; index++) {
  25089. if (this._events[index].frame === frame) {
  25090. this._events.splice(index, 1);
  25091. index--;
  25092. }
  25093. }
  25094. };
  25095. Animation.prototype.createRange = function (name, from, to) {
  25096. // check name not already in use; could happen for bones after serialized
  25097. if (!this._ranges[name]) {
  25098. this._ranges[name] = new AnimationRange(name, from, to);
  25099. }
  25100. };
  25101. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25102. if (deleteFrames === void 0) { deleteFrames = true; }
  25103. if (this._ranges[name]) {
  25104. if (deleteFrames) {
  25105. var from = this._ranges[name].from;
  25106. var to = this._ranges[name].to;
  25107. // this loop MUST go high to low for multiple splices to work
  25108. for (var key = this._keys.length - 1; key >= 0; key--) {
  25109. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25110. this._keys.splice(key, 1);
  25111. }
  25112. }
  25113. }
  25114. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25115. }
  25116. };
  25117. Animation.prototype.getRange = function (name) {
  25118. return this._ranges[name];
  25119. };
  25120. Animation.prototype.reset = function () {
  25121. this._offsetsCache = {};
  25122. this._highLimitsCache = {};
  25123. this.currentFrame = 0;
  25124. this._blendingFactor = 0;
  25125. this._originalBlendValue = null;
  25126. };
  25127. Animation.prototype.isStopped = function () {
  25128. return this._stopped;
  25129. };
  25130. Animation.prototype.getKeys = function () {
  25131. return this._keys;
  25132. };
  25133. Animation.prototype.getHighestFrame = function () {
  25134. var ret = 0;
  25135. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25136. if (ret < this._keys[key].frame) {
  25137. ret = this._keys[key].frame;
  25138. }
  25139. }
  25140. return ret;
  25141. };
  25142. Animation.prototype.getEasingFunction = function () {
  25143. return this._easingFunction;
  25144. };
  25145. Animation.prototype.setEasingFunction = function (easingFunction) {
  25146. this._easingFunction = easingFunction;
  25147. };
  25148. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25149. return startValue + (endValue - startValue) * gradient;
  25150. };
  25151. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25152. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25153. };
  25154. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25155. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25156. };
  25157. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25158. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25159. };
  25160. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25161. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25162. };
  25163. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25164. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25165. };
  25166. Animation.prototype.clone = function () {
  25167. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25168. if (this._keys) {
  25169. clone.setKeys(this._keys);
  25170. }
  25171. if (this._ranges) {
  25172. clone._ranges = {};
  25173. for (var name in this._ranges) {
  25174. clone._ranges[name] = this._ranges[name].clone();
  25175. }
  25176. }
  25177. return clone;
  25178. };
  25179. Animation.prototype.setKeys = function (values) {
  25180. this._keys = values.slice(0);
  25181. this._offsetsCache = {};
  25182. this._highLimitsCache = {};
  25183. };
  25184. Animation.prototype._getKeyValue = function (value) {
  25185. if (typeof value === "function") {
  25186. return value();
  25187. }
  25188. return value;
  25189. };
  25190. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25191. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25192. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25193. }
  25194. this.currentFrame = currentFrame;
  25195. // Try to get a hash to find the right key
  25196. 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));
  25197. if (this._keys[startKey].frame >= currentFrame) {
  25198. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25199. startKey--;
  25200. }
  25201. }
  25202. for (var key = startKey; key < this._keys.length; key++) {
  25203. if (this._keys[key + 1].frame >= currentFrame) {
  25204. var startValue = this._getKeyValue(this._keys[key].value);
  25205. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25206. // gradient : percent of currentFrame between the frame inf and the frame sup
  25207. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25208. // check for easingFunction and correction of gradient
  25209. if (this._easingFunction != null) {
  25210. gradient = this._easingFunction.ease(gradient);
  25211. }
  25212. switch (this.dataType) {
  25213. // Float
  25214. case Animation.ANIMATIONTYPE_FLOAT:
  25215. switch (loopMode) {
  25216. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25217. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25218. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25219. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25220. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25221. }
  25222. break;
  25223. // Quaternion
  25224. case Animation.ANIMATIONTYPE_QUATERNION:
  25225. var quaternion = null;
  25226. switch (loopMode) {
  25227. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25228. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25229. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25230. break;
  25231. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25232. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25233. break;
  25234. }
  25235. return quaternion;
  25236. // Vector3
  25237. case Animation.ANIMATIONTYPE_VECTOR3:
  25238. switch (loopMode) {
  25239. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25240. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25241. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25242. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25243. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25244. }
  25245. // Vector2
  25246. case Animation.ANIMATIONTYPE_VECTOR2:
  25247. switch (loopMode) {
  25248. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25249. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25250. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25251. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25252. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25253. }
  25254. // Color3
  25255. case Animation.ANIMATIONTYPE_COLOR3:
  25256. switch (loopMode) {
  25257. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25258. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25259. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25260. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25261. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25262. }
  25263. // Matrix
  25264. case Animation.ANIMATIONTYPE_MATRIX:
  25265. switch (loopMode) {
  25266. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25267. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25268. if (this.allowMatricesInterpolation) {
  25269. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25270. }
  25271. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25272. return startValue;
  25273. }
  25274. default:
  25275. break;
  25276. }
  25277. break;
  25278. }
  25279. }
  25280. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25281. };
  25282. Animation.prototype.setValue = function (currentValue, blend) {
  25283. if (blend === void 0) { blend = false; }
  25284. // Set value
  25285. var path;
  25286. var destination;
  25287. if (this.targetPropertyPath.length > 1) {
  25288. var property = this._target[this.targetPropertyPath[0]];
  25289. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25290. property = property[this.targetPropertyPath[index]];
  25291. }
  25292. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25293. destination = property;
  25294. }
  25295. else {
  25296. path = this.targetPropertyPath[0];
  25297. destination = this._target;
  25298. }
  25299. // Blending
  25300. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25301. if (!this._originalBlendValue) {
  25302. this._originalBlendValue = destination[path];
  25303. }
  25304. if (this._originalBlendValue.prototype) {
  25305. if (this._originalBlendValue.prototype.Lerp) {
  25306. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25307. }
  25308. else {
  25309. destination[path] = currentValue;
  25310. }
  25311. }
  25312. else {
  25313. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25314. }
  25315. this._blendingFactor += this.blendingSpeed;
  25316. }
  25317. else {
  25318. destination[path] = currentValue;
  25319. }
  25320. if (this._target.markAsDirty) {
  25321. this._target.markAsDirty(this.targetProperty);
  25322. }
  25323. };
  25324. Animation.prototype.goToFrame = function (frame) {
  25325. if (frame < this._keys[0].frame) {
  25326. frame = this._keys[0].frame;
  25327. }
  25328. else if (frame > this._keys[this._keys.length - 1].frame) {
  25329. frame = this._keys[this._keys.length - 1].frame;
  25330. }
  25331. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25332. this.setValue(currentValue);
  25333. };
  25334. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25335. if (blend === void 0) { blend = false; }
  25336. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25337. this._stopped = true;
  25338. return false;
  25339. }
  25340. var returnValue = true;
  25341. // Adding a start key at frame 0 if missing
  25342. if (this._keys[0].frame !== 0) {
  25343. var newKey = { frame: 0, value: this._keys[0].value };
  25344. this._keys.splice(0, 0, newKey);
  25345. }
  25346. // Check limits
  25347. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25348. from = this._keys[0].frame;
  25349. }
  25350. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25351. to = this._keys[this._keys.length - 1].frame;
  25352. }
  25353. // Compute ratio
  25354. var range = to - from;
  25355. var offsetValue;
  25356. // ratio represents the frame delta between from and to
  25357. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25358. var highLimitValue = 0;
  25359. if (ratio > range && !loop) {
  25360. returnValue = false;
  25361. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25362. }
  25363. else {
  25364. // Get max value if required
  25365. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25366. var keyOffset = to.toString() + from.toString();
  25367. if (!this._offsetsCache[keyOffset]) {
  25368. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25369. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25370. switch (this.dataType) {
  25371. // Float
  25372. case Animation.ANIMATIONTYPE_FLOAT:
  25373. this._offsetsCache[keyOffset] = toValue - fromValue;
  25374. break;
  25375. // Quaternion
  25376. case Animation.ANIMATIONTYPE_QUATERNION:
  25377. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25378. break;
  25379. // Vector3
  25380. case Animation.ANIMATIONTYPE_VECTOR3:
  25381. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25382. // Vector2
  25383. case Animation.ANIMATIONTYPE_VECTOR2:
  25384. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25385. // Color3
  25386. case Animation.ANIMATIONTYPE_COLOR3:
  25387. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25388. default:
  25389. break;
  25390. }
  25391. this._highLimitsCache[keyOffset] = toValue;
  25392. }
  25393. highLimitValue = this._highLimitsCache[keyOffset];
  25394. offsetValue = this._offsetsCache[keyOffset];
  25395. }
  25396. }
  25397. if (offsetValue === undefined) {
  25398. switch (this.dataType) {
  25399. // Float
  25400. case Animation.ANIMATIONTYPE_FLOAT:
  25401. offsetValue = 0;
  25402. break;
  25403. // Quaternion
  25404. case Animation.ANIMATIONTYPE_QUATERNION:
  25405. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25406. break;
  25407. // Vector3
  25408. case Animation.ANIMATIONTYPE_VECTOR3:
  25409. offsetValue = BABYLON.Vector3.Zero();
  25410. break;
  25411. // Vector2
  25412. case Animation.ANIMATIONTYPE_VECTOR2:
  25413. offsetValue = BABYLON.Vector2.Zero();
  25414. break;
  25415. // Color3
  25416. case Animation.ANIMATIONTYPE_COLOR3:
  25417. offsetValue = BABYLON.Color3.Black();
  25418. }
  25419. }
  25420. // Compute value
  25421. var repeatCount = (ratio / range) >> 0;
  25422. var currentFrame = returnValue ? from + ratio % range : to;
  25423. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25424. // Set value
  25425. this.setValue(currentValue);
  25426. // Check events
  25427. for (var index = 0; index < this._events.length; index++) {
  25428. if (currentFrame >= this._events[index].frame) {
  25429. var event = this._events[index];
  25430. if (!event.isDone) {
  25431. // If event should be done only once, remove it.
  25432. if (event.onlyOnce) {
  25433. this._events.splice(index, 1);
  25434. index--;
  25435. }
  25436. event.isDone = true;
  25437. event.action();
  25438. } // Don't do anything if the event has already be done.
  25439. }
  25440. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25441. // reset event, the animation is looping
  25442. this._events[index].isDone = false;
  25443. }
  25444. }
  25445. if (!returnValue) {
  25446. this._stopped = true;
  25447. }
  25448. return returnValue;
  25449. };
  25450. Animation.prototype.serialize = function () {
  25451. var serializationObject = {};
  25452. serializationObject.name = this.name;
  25453. serializationObject.property = this.targetProperty;
  25454. serializationObject.framePerSecond = this.framePerSecond;
  25455. serializationObject.dataType = this.dataType;
  25456. serializationObject.loopBehavior = this.loopMode;
  25457. var dataType = this.dataType;
  25458. serializationObject.keys = [];
  25459. var keys = this.getKeys();
  25460. for (var index = 0; index < keys.length; index++) {
  25461. var animationKey = keys[index];
  25462. var key = {};
  25463. key.frame = animationKey.frame;
  25464. switch (dataType) {
  25465. case Animation.ANIMATIONTYPE_FLOAT:
  25466. key.values = [animationKey.value];
  25467. break;
  25468. case Animation.ANIMATIONTYPE_QUATERNION:
  25469. case Animation.ANIMATIONTYPE_MATRIX:
  25470. case Animation.ANIMATIONTYPE_VECTOR3:
  25471. case Animation.ANIMATIONTYPE_COLOR3:
  25472. key.values = animationKey.value.asArray();
  25473. break;
  25474. }
  25475. serializationObject.keys.push(key);
  25476. }
  25477. serializationObject.ranges = [];
  25478. for (var name in this._ranges) {
  25479. var range = {};
  25480. range.name = name;
  25481. range.from = this._ranges[name].from;
  25482. range.to = this._ranges[name].to;
  25483. serializationObject.ranges.push(range);
  25484. }
  25485. return serializationObject;
  25486. };
  25487. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25488. get: function () {
  25489. return Animation._ANIMATIONTYPE_FLOAT;
  25490. },
  25491. enumerable: true,
  25492. configurable: true
  25493. });
  25494. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25495. get: function () {
  25496. return Animation._ANIMATIONTYPE_VECTOR3;
  25497. },
  25498. enumerable: true,
  25499. configurable: true
  25500. });
  25501. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25502. get: function () {
  25503. return Animation._ANIMATIONTYPE_VECTOR2;
  25504. },
  25505. enumerable: true,
  25506. configurable: true
  25507. });
  25508. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25509. get: function () {
  25510. return Animation._ANIMATIONTYPE_QUATERNION;
  25511. },
  25512. enumerable: true,
  25513. configurable: true
  25514. });
  25515. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25516. get: function () {
  25517. return Animation._ANIMATIONTYPE_MATRIX;
  25518. },
  25519. enumerable: true,
  25520. configurable: true
  25521. });
  25522. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25523. get: function () {
  25524. return Animation._ANIMATIONTYPE_COLOR3;
  25525. },
  25526. enumerable: true,
  25527. configurable: true
  25528. });
  25529. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25530. get: function () {
  25531. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25532. },
  25533. enumerable: true,
  25534. configurable: true
  25535. });
  25536. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25537. get: function () {
  25538. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25539. },
  25540. enumerable: true,
  25541. configurable: true
  25542. });
  25543. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25544. get: function () {
  25545. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25546. },
  25547. enumerable: true,
  25548. configurable: true
  25549. });
  25550. Animation.Parse = function (parsedAnimation) {
  25551. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25552. var dataType = parsedAnimation.dataType;
  25553. var keys = [];
  25554. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25555. var key = parsedAnimation.keys[index];
  25556. var data;
  25557. switch (dataType) {
  25558. case Animation.ANIMATIONTYPE_FLOAT:
  25559. data = key.values[0];
  25560. break;
  25561. case Animation.ANIMATIONTYPE_QUATERNION:
  25562. data = BABYLON.Quaternion.FromArray(key.values);
  25563. break;
  25564. case Animation.ANIMATIONTYPE_MATRIX:
  25565. data = BABYLON.Matrix.FromArray(key.values);
  25566. break;
  25567. case Animation.ANIMATIONTYPE_COLOR3:
  25568. data = BABYLON.Color3.FromArray(key.values);
  25569. break;
  25570. case Animation.ANIMATIONTYPE_VECTOR3:
  25571. default:
  25572. data = BABYLON.Vector3.FromArray(key.values);
  25573. break;
  25574. }
  25575. keys.push({
  25576. frame: key.frame,
  25577. value: data
  25578. });
  25579. }
  25580. animation.setKeys(keys);
  25581. if (parsedAnimation.ranges) {
  25582. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25583. data = parsedAnimation.ranges[index];
  25584. animation.createRange(data.name, data.from, data.to);
  25585. }
  25586. }
  25587. return animation;
  25588. };
  25589. Animation.AppendSerializedAnimations = function (source, destination) {
  25590. if (source.animations) {
  25591. destination.animations = [];
  25592. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25593. var animation = source.animations[animationIndex];
  25594. destination.animations.push(animation.serialize());
  25595. }
  25596. }
  25597. };
  25598. // Statics
  25599. Animation._ANIMATIONTYPE_FLOAT = 0;
  25600. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25601. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25602. Animation._ANIMATIONTYPE_MATRIX = 3;
  25603. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25604. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25605. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25606. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25607. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25608. return Animation;
  25609. }());
  25610. BABYLON.Animation = Animation;
  25611. })(BABYLON || (BABYLON = {}));
  25612. var BABYLON;
  25613. (function (BABYLON) {
  25614. var Animatable = (function () {
  25615. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25616. if (fromFrame === void 0) { fromFrame = 0; }
  25617. if (toFrame === void 0) { toFrame = 100; }
  25618. if (loopAnimation === void 0) { loopAnimation = false; }
  25619. if (speedRatio === void 0) { speedRatio = 1.0; }
  25620. this.target = target;
  25621. this.fromFrame = fromFrame;
  25622. this.toFrame = toFrame;
  25623. this.loopAnimation = loopAnimation;
  25624. this.speedRatio = speedRatio;
  25625. this.onAnimationEnd = onAnimationEnd;
  25626. this._animations = new Array();
  25627. this._paused = false;
  25628. this.animationStarted = false;
  25629. if (animations) {
  25630. this.appendAnimations(target, animations);
  25631. }
  25632. this._scene = scene;
  25633. scene._activeAnimatables.push(this);
  25634. }
  25635. // Methods
  25636. Animatable.prototype.getAnimations = function () {
  25637. return this._animations;
  25638. };
  25639. Animatable.prototype.appendAnimations = function (target, animations) {
  25640. for (var index = 0; index < animations.length; index++) {
  25641. var animation = animations[index];
  25642. animation._target = target;
  25643. this._animations.push(animation);
  25644. }
  25645. };
  25646. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25647. var animations = this._animations;
  25648. for (var index = 0; index < animations.length; index++) {
  25649. if (animations[index].targetProperty === property) {
  25650. return animations[index];
  25651. }
  25652. }
  25653. return null;
  25654. };
  25655. Animatable.prototype.reset = function () {
  25656. var animations = this._animations;
  25657. for (var index = 0; index < animations.length; index++) {
  25658. animations[index].reset();
  25659. }
  25660. this._localDelayOffset = null;
  25661. this._pausedDelay = null;
  25662. };
  25663. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25664. var animations = this._animations;
  25665. for (var index = 0; index < animations.length; index++) {
  25666. animations[index].enableBlending = true;
  25667. animations[index].blendingSpeed = blendingSpeed;
  25668. }
  25669. };
  25670. Animatable.prototype.disableBlending = function () {
  25671. var animations = this._animations;
  25672. for (var index = 0; index < animations.length; index++) {
  25673. animations[index].enableBlending = false;
  25674. }
  25675. };
  25676. Animatable.prototype.goToFrame = function (frame) {
  25677. var animations = this._animations;
  25678. for (var index = 0; index < animations.length; index++) {
  25679. animations[index].goToFrame(frame);
  25680. }
  25681. };
  25682. Animatable.prototype.pause = function () {
  25683. if (this._paused) {
  25684. return;
  25685. }
  25686. this._paused = true;
  25687. };
  25688. Animatable.prototype.restart = function () {
  25689. this._paused = false;
  25690. };
  25691. Animatable.prototype.stop = function () {
  25692. var index = this._scene._activeAnimatables.indexOf(this);
  25693. if (index > -1) {
  25694. this._scene._activeAnimatables.splice(index, 1);
  25695. var animations = this._animations;
  25696. for (var index = 0; index < animations.length; index++) {
  25697. animations[index].reset();
  25698. }
  25699. if (this.onAnimationEnd) {
  25700. this.onAnimationEnd();
  25701. }
  25702. }
  25703. };
  25704. Animatable.prototype._animate = function (delay) {
  25705. if (this._paused) {
  25706. this.animationStarted = false;
  25707. if (!this._pausedDelay) {
  25708. this._pausedDelay = delay;
  25709. }
  25710. return true;
  25711. }
  25712. if (!this._localDelayOffset) {
  25713. this._localDelayOffset = delay;
  25714. }
  25715. else if (this._pausedDelay) {
  25716. this._localDelayOffset += delay - this._pausedDelay;
  25717. this._pausedDelay = null;
  25718. }
  25719. // Animating
  25720. var running = false;
  25721. var animations = this._animations;
  25722. var index;
  25723. for (index = 0; index < animations.length; index++) {
  25724. var animation = animations[index];
  25725. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25726. running = running || isRunning;
  25727. }
  25728. this.animationStarted = running;
  25729. if (!running) {
  25730. // Remove from active animatables
  25731. index = this._scene._activeAnimatables.indexOf(this);
  25732. this._scene._activeAnimatables.splice(index, 1);
  25733. }
  25734. if (!running && this.onAnimationEnd) {
  25735. this.onAnimationEnd();
  25736. this.onAnimationEnd = null;
  25737. }
  25738. return running;
  25739. };
  25740. return Animatable;
  25741. }());
  25742. BABYLON.Animatable = Animatable;
  25743. })(BABYLON || (BABYLON = {}));
  25744. var BABYLON;
  25745. (function (BABYLON) {
  25746. var EasingFunction = (function () {
  25747. function EasingFunction() {
  25748. // Properties
  25749. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25750. }
  25751. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25752. get: function () {
  25753. return EasingFunction._EASINGMODE_EASEIN;
  25754. },
  25755. enumerable: true,
  25756. configurable: true
  25757. });
  25758. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25759. get: function () {
  25760. return EasingFunction._EASINGMODE_EASEOUT;
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25766. get: function () {
  25767. return EasingFunction._EASINGMODE_EASEINOUT;
  25768. },
  25769. enumerable: true,
  25770. configurable: true
  25771. });
  25772. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25773. var n = Math.min(Math.max(easingMode, 0), 2);
  25774. this._easingMode = n;
  25775. };
  25776. EasingFunction.prototype.getEasingMode = function () {
  25777. return this._easingMode;
  25778. };
  25779. EasingFunction.prototype.easeInCore = function (gradient) {
  25780. throw new Error('You must implement this method');
  25781. };
  25782. EasingFunction.prototype.ease = function (gradient) {
  25783. switch (this._easingMode) {
  25784. case EasingFunction.EASINGMODE_EASEIN:
  25785. return this.easeInCore(gradient);
  25786. case EasingFunction.EASINGMODE_EASEOUT:
  25787. return (1 - this.easeInCore(1 - gradient));
  25788. }
  25789. if (gradient >= 0.5) {
  25790. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25791. }
  25792. return (this.easeInCore(gradient * 2) * 0.5);
  25793. };
  25794. //Statics
  25795. EasingFunction._EASINGMODE_EASEIN = 0;
  25796. EasingFunction._EASINGMODE_EASEOUT = 1;
  25797. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25798. return EasingFunction;
  25799. }());
  25800. BABYLON.EasingFunction = EasingFunction;
  25801. var CircleEase = (function (_super) {
  25802. __extends(CircleEase, _super);
  25803. function CircleEase() {
  25804. _super.apply(this, arguments);
  25805. }
  25806. CircleEase.prototype.easeInCore = function (gradient) {
  25807. gradient = Math.max(0, Math.min(1, gradient));
  25808. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25809. };
  25810. return CircleEase;
  25811. }(EasingFunction));
  25812. BABYLON.CircleEase = CircleEase;
  25813. var BackEase = (function (_super) {
  25814. __extends(BackEase, _super);
  25815. function BackEase(amplitude) {
  25816. if (amplitude === void 0) { amplitude = 1; }
  25817. _super.call(this);
  25818. this.amplitude = amplitude;
  25819. }
  25820. BackEase.prototype.easeInCore = function (gradient) {
  25821. var num = Math.max(0, this.amplitude);
  25822. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25823. };
  25824. return BackEase;
  25825. }(EasingFunction));
  25826. BABYLON.BackEase = BackEase;
  25827. var BounceEase = (function (_super) {
  25828. __extends(BounceEase, _super);
  25829. function BounceEase(bounces, bounciness) {
  25830. if (bounces === void 0) { bounces = 3; }
  25831. if (bounciness === void 0) { bounciness = 2; }
  25832. _super.call(this);
  25833. this.bounces = bounces;
  25834. this.bounciness = bounciness;
  25835. }
  25836. BounceEase.prototype.easeInCore = function (gradient) {
  25837. var y = Math.max(0.0, this.bounces);
  25838. var bounciness = this.bounciness;
  25839. if (bounciness <= 1.0) {
  25840. bounciness = 1.001;
  25841. }
  25842. var num9 = Math.pow(bounciness, y);
  25843. var num5 = 1.0 - bounciness;
  25844. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25845. var num15 = gradient * num4;
  25846. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25847. var num3 = Math.floor(num65);
  25848. var num13 = num3 + 1.0;
  25849. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25850. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25851. var num7 = (num8 + num12) * 0.5;
  25852. var num6 = gradient - num7;
  25853. var num2 = num7 - num8;
  25854. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25855. };
  25856. return BounceEase;
  25857. }(EasingFunction));
  25858. BABYLON.BounceEase = BounceEase;
  25859. var CubicEase = (function (_super) {
  25860. __extends(CubicEase, _super);
  25861. function CubicEase() {
  25862. _super.apply(this, arguments);
  25863. }
  25864. CubicEase.prototype.easeInCore = function (gradient) {
  25865. return (gradient * gradient * gradient);
  25866. };
  25867. return CubicEase;
  25868. }(EasingFunction));
  25869. BABYLON.CubicEase = CubicEase;
  25870. var ElasticEase = (function (_super) {
  25871. __extends(ElasticEase, _super);
  25872. function ElasticEase(oscillations, springiness) {
  25873. if (oscillations === void 0) { oscillations = 3; }
  25874. if (springiness === void 0) { springiness = 3; }
  25875. _super.call(this);
  25876. this.oscillations = oscillations;
  25877. this.springiness = springiness;
  25878. }
  25879. ElasticEase.prototype.easeInCore = function (gradient) {
  25880. var num2;
  25881. var num3 = Math.max(0.0, this.oscillations);
  25882. var num = Math.max(0.0, this.springiness);
  25883. if (num == 0) {
  25884. num2 = gradient;
  25885. }
  25886. else {
  25887. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  25888. }
  25889. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  25890. };
  25891. return ElasticEase;
  25892. }(EasingFunction));
  25893. BABYLON.ElasticEase = ElasticEase;
  25894. var ExponentialEase = (function (_super) {
  25895. __extends(ExponentialEase, _super);
  25896. function ExponentialEase(exponent) {
  25897. if (exponent === void 0) { exponent = 2; }
  25898. _super.call(this);
  25899. this.exponent = exponent;
  25900. }
  25901. ExponentialEase.prototype.easeInCore = function (gradient) {
  25902. if (this.exponent <= 0) {
  25903. return gradient;
  25904. }
  25905. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  25906. };
  25907. return ExponentialEase;
  25908. }(EasingFunction));
  25909. BABYLON.ExponentialEase = ExponentialEase;
  25910. var PowerEase = (function (_super) {
  25911. __extends(PowerEase, _super);
  25912. function PowerEase(power) {
  25913. if (power === void 0) { power = 2; }
  25914. _super.call(this);
  25915. this.power = power;
  25916. }
  25917. PowerEase.prototype.easeInCore = function (gradient) {
  25918. var y = Math.max(0.0, this.power);
  25919. return Math.pow(gradient, y);
  25920. };
  25921. return PowerEase;
  25922. }(EasingFunction));
  25923. BABYLON.PowerEase = PowerEase;
  25924. var QuadraticEase = (function (_super) {
  25925. __extends(QuadraticEase, _super);
  25926. function QuadraticEase() {
  25927. _super.apply(this, arguments);
  25928. }
  25929. QuadraticEase.prototype.easeInCore = function (gradient) {
  25930. return (gradient * gradient);
  25931. };
  25932. return QuadraticEase;
  25933. }(EasingFunction));
  25934. BABYLON.QuadraticEase = QuadraticEase;
  25935. var QuarticEase = (function (_super) {
  25936. __extends(QuarticEase, _super);
  25937. function QuarticEase() {
  25938. _super.apply(this, arguments);
  25939. }
  25940. QuarticEase.prototype.easeInCore = function (gradient) {
  25941. return (gradient * gradient * gradient * gradient);
  25942. };
  25943. return QuarticEase;
  25944. }(EasingFunction));
  25945. BABYLON.QuarticEase = QuarticEase;
  25946. var QuinticEase = (function (_super) {
  25947. __extends(QuinticEase, _super);
  25948. function QuinticEase() {
  25949. _super.apply(this, arguments);
  25950. }
  25951. QuinticEase.prototype.easeInCore = function (gradient) {
  25952. return (gradient * gradient * gradient * gradient * gradient);
  25953. };
  25954. return QuinticEase;
  25955. }(EasingFunction));
  25956. BABYLON.QuinticEase = QuinticEase;
  25957. var SineEase = (function (_super) {
  25958. __extends(SineEase, _super);
  25959. function SineEase() {
  25960. _super.apply(this, arguments);
  25961. }
  25962. SineEase.prototype.easeInCore = function (gradient) {
  25963. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  25964. };
  25965. return SineEase;
  25966. }(EasingFunction));
  25967. BABYLON.SineEase = SineEase;
  25968. var BezierCurveEase = (function (_super) {
  25969. __extends(BezierCurveEase, _super);
  25970. function BezierCurveEase(x1, y1, x2, y2) {
  25971. if (x1 === void 0) { x1 = 0; }
  25972. if (y1 === void 0) { y1 = 0; }
  25973. if (x2 === void 0) { x2 = 1; }
  25974. if (y2 === void 0) { y2 = 1; }
  25975. _super.call(this);
  25976. this.x1 = x1;
  25977. this.y1 = y1;
  25978. this.x2 = x2;
  25979. this.y2 = y2;
  25980. }
  25981. BezierCurveEase.prototype.easeInCore = function (gradient) {
  25982. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  25983. };
  25984. return BezierCurveEase;
  25985. }(EasingFunction));
  25986. BABYLON.BezierCurveEase = BezierCurveEase;
  25987. })(BABYLON || (BABYLON = {}));
  25988. var BABYLON;
  25989. (function (BABYLON) {
  25990. var Bone = (function (_super) {
  25991. __extends(Bone, _super);
  25992. function Bone(name, skeleton, parentBone, matrix, restPose) {
  25993. _super.call(this, name, skeleton.getScene());
  25994. this.name = name;
  25995. this.children = new Array();
  25996. this.animations = new Array();
  25997. this._worldTransform = new BABYLON.Matrix();
  25998. this._absoluteTransform = new BABYLON.Matrix();
  25999. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26000. this._skeleton = skeleton;
  26001. this._matrix = matrix;
  26002. this._baseMatrix = matrix;
  26003. this._restPose = restPose ? restPose : matrix.clone();
  26004. skeleton.bones.push(this);
  26005. if (parentBone) {
  26006. this._parent = parentBone;
  26007. parentBone.children.push(this);
  26008. }
  26009. else {
  26010. this._parent = null;
  26011. }
  26012. this._updateDifferenceMatrix();
  26013. }
  26014. // Members
  26015. Bone.prototype.getParent = function () {
  26016. return this._parent;
  26017. };
  26018. Bone.prototype.getLocalMatrix = function () {
  26019. return this._matrix;
  26020. };
  26021. Bone.prototype.getBaseMatrix = function () {
  26022. return this._baseMatrix;
  26023. };
  26024. Bone.prototype.getRestPose = function () {
  26025. return this._restPose;
  26026. };
  26027. Bone.prototype.returnToRest = function () {
  26028. this.updateMatrix(this._restPose.clone());
  26029. };
  26030. Bone.prototype.getWorldMatrix = function () {
  26031. return this._worldTransform;
  26032. };
  26033. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26034. return this._invertedAbsoluteTransform;
  26035. };
  26036. Bone.prototype.getAbsoluteTransform = function () {
  26037. return this._absoluteTransform;
  26038. };
  26039. // Methods
  26040. Bone.prototype.updateMatrix = function (matrix) {
  26041. this._baseMatrix = matrix.clone();
  26042. this._matrix = matrix.clone();
  26043. this._skeleton._markAsDirty();
  26044. this._updateDifferenceMatrix();
  26045. };
  26046. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26047. if (!rootMatrix) {
  26048. rootMatrix = this._baseMatrix;
  26049. }
  26050. if (this._parent) {
  26051. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26052. }
  26053. else {
  26054. this._absoluteTransform.copyFrom(rootMatrix);
  26055. }
  26056. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26057. for (var index = 0; index < this.children.length; index++) {
  26058. this.children[index]._updateDifferenceMatrix();
  26059. }
  26060. };
  26061. Bone.prototype.markAsDirty = function () {
  26062. this._currentRenderId++;
  26063. this._skeleton._markAsDirty();
  26064. };
  26065. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26066. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26067. // all animation may be coming from a library skeleton, so may need to create animation
  26068. if (this.animations.length === 0) {
  26069. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26070. this.animations[0].setKeys([]);
  26071. }
  26072. // get animation info / verify there is such a range from the source bone
  26073. var sourceRange = source.animations[0].getRange(rangeName);
  26074. if (!sourceRange) {
  26075. return false;
  26076. }
  26077. var from = sourceRange.from;
  26078. var to = sourceRange.to;
  26079. var sourceKeys = source.animations[0].getKeys();
  26080. // rescaling prep
  26081. var sourceBoneLength = source.length;
  26082. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26083. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26084. var destKeys = this.animations[0].getKeys();
  26085. // loop vars declaration / initialization
  26086. var orig;
  26087. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26088. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26089. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26090. var mat;
  26091. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26092. orig = sourceKeys[key];
  26093. if (orig.frame >= from && orig.frame <= to) {
  26094. if (scalingReqd) {
  26095. orig.value.decompose(origScale, origRotation, origTranslation);
  26096. origTranslation.scaleInPlace(ratio);
  26097. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26098. }
  26099. else {
  26100. mat = orig.value;
  26101. }
  26102. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26103. }
  26104. }
  26105. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26106. return true;
  26107. };
  26108. return Bone;
  26109. }(BABYLON.Node));
  26110. BABYLON.Bone = Bone;
  26111. })(BABYLON || (BABYLON = {}));
  26112. var BABYLON;
  26113. (function (BABYLON) {
  26114. var Skeleton = (function () {
  26115. function Skeleton(name, id, scene) {
  26116. this.name = name;
  26117. this.id = id;
  26118. this.bones = new Array();
  26119. this.needInitialSkinMatrix = false;
  26120. this._isDirty = true;
  26121. this._meshesWithPoseMatrix = new Array();
  26122. this._identity = BABYLON.Matrix.Identity();
  26123. this._ranges = {};
  26124. this.bones = [];
  26125. this._scene = scene;
  26126. scene.skeletons.push(this);
  26127. //make sure it will recalculate the matrix next time prepare is called.
  26128. this._isDirty = true;
  26129. }
  26130. // Members
  26131. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26132. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26133. return mesh._bonesTransformMatrices;
  26134. }
  26135. return this._transformMatrices;
  26136. };
  26137. Skeleton.prototype.getScene = function () {
  26138. return this._scene;
  26139. };
  26140. // Methods
  26141. /**
  26142. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26143. */
  26144. Skeleton.prototype.toString = function (fullDetails) {
  26145. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26146. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26147. if (fullDetails) {
  26148. ret += ", Ranges: {";
  26149. var first = true;
  26150. for (var name in this._ranges) {
  26151. if (!first) {
  26152. ret + ", ";
  26153. first = false;
  26154. }
  26155. ret += name;
  26156. }
  26157. ret += "}";
  26158. }
  26159. return ret;
  26160. };
  26161. /**
  26162. * Get bone's index searching by name
  26163. * @param {string} name is bone's name to search for
  26164. * @return {number} Indice of the bone. Returns -1 if not found
  26165. */
  26166. Skeleton.prototype.getBoneIndexByName = function (name) {
  26167. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26168. if (this.bones[boneIndex].name === name) {
  26169. return boneIndex;
  26170. }
  26171. }
  26172. return -1;
  26173. };
  26174. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26175. // check name not already in use
  26176. if (!this._ranges[name]) {
  26177. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26178. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26179. if (this.bones[i].animations[0]) {
  26180. this.bones[i].animations[0].createRange(name, from, to);
  26181. }
  26182. }
  26183. }
  26184. };
  26185. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26186. if (deleteFrames === void 0) { deleteFrames = true; }
  26187. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26188. if (this.bones[i].animations[0]) {
  26189. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26190. }
  26191. }
  26192. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26193. };
  26194. Skeleton.prototype.getAnimationRange = function (name) {
  26195. return this._ranges[name];
  26196. };
  26197. /**
  26198. * Returns as an Array, all AnimationRanges defined on this skeleton
  26199. */
  26200. Skeleton.prototype.getAnimationRanges = function () {
  26201. var animationRanges = [];
  26202. var name;
  26203. var i = 0;
  26204. for (name in this._ranges) {
  26205. animationRanges[i] = this._ranges[name];
  26206. i++;
  26207. }
  26208. return animationRanges;
  26209. };
  26210. /**
  26211. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26212. */
  26213. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26214. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26215. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26216. return false;
  26217. }
  26218. var ret = true;
  26219. var frameOffset = this._getHighestAnimationFrame() + 1;
  26220. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26221. var boneDict = {};
  26222. var sourceBones = source.bones;
  26223. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26224. boneDict[sourceBones[i].name] = sourceBones[i];
  26225. }
  26226. if (this.bones.length !== sourceBones.length) {
  26227. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26228. ret = false;
  26229. }
  26230. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26231. var boneName = this.bones[i].name;
  26232. var sourceBone = boneDict[boneName];
  26233. if (sourceBone) {
  26234. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26235. }
  26236. else {
  26237. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26238. ret = false;
  26239. }
  26240. }
  26241. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26242. var range = source.getAnimationRange(name);
  26243. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26244. return ret;
  26245. };
  26246. Skeleton.prototype.returnToRest = function () {
  26247. for (var index = 0; index < this.bones.length; index++) {
  26248. this.bones[index].returnToRest();
  26249. }
  26250. };
  26251. Skeleton.prototype._getHighestAnimationFrame = function () {
  26252. var ret = 0;
  26253. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26254. if (this.bones[i].animations[0]) {
  26255. var highest = this.bones[i].animations[0].getHighestFrame();
  26256. if (ret < highest) {
  26257. ret = highest;
  26258. }
  26259. }
  26260. }
  26261. return ret;
  26262. };
  26263. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26264. var range = this.getAnimationRange(name);
  26265. if (!range) {
  26266. return null;
  26267. }
  26268. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26269. };
  26270. Skeleton.prototype._markAsDirty = function () {
  26271. this._isDirty = true;
  26272. };
  26273. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26274. this._meshesWithPoseMatrix.push(mesh);
  26275. };
  26276. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26277. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26278. if (index > -1) {
  26279. this._meshesWithPoseMatrix.splice(index, 1);
  26280. }
  26281. };
  26282. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26283. for (var index = 0; index < this.bones.length; index++) {
  26284. var bone = this.bones[index];
  26285. var parentBone = bone.getParent();
  26286. if (parentBone) {
  26287. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26288. }
  26289. else {
  26290. if (initialSkinMatrix) {
  26291. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26292. }
  26293. else {
  26294. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26295. }
  26296. }
  26297. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26298. }
  26299. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26300. };
  26301. Skeleton.prototype.prepare = function () {
  26302. if (!this._isDirty) {
  26303. return;
  26304. }
  26305. if (this.needInitialSkinMatrix) {
  26306. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26307. var mesh = this._meshesWithPoseMatrix[index];
  26308. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26309. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26310. }
  26311. var poseMatrix = mesh.getPoseMatrix();
  26312. // Prepare bones
  26313. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26314. var bone = this.bones[boneIndex];
  26315. if (!bone.getParent()) {
  26316. var matrix = bone.getBaseMatrix();
  26317. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26318. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26319. }
  26320. }
  26321. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26322. }
  26323. }
  26324. else {
  26325. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26326. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26327. }
  26328. this._computeTransformMatrices(this._transformMatrices, null);
  26329. }
  26330. this._isDirty = false;
  26331. this._scene._activeBones += this.bones.length;
  26332. };
  26333. Skeleton.prototype.getAnimatables = function () {
  26334. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26335. this._animatables = [];
  26336. for (var index = 0; index < this.bones.length; index++) {
  26337. this._animatables.push(this.bones[index]);
  26338. }
  26339. }
  26340. return this._animatables;
  26341. };
  26342. Skeleton.prototype.clone = function (name, id) {
  26343. var result = new Skeleton(name, id || name, this._scene);
  26344. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26345. for (var index = 0; index < this.bones.length; index++) {
  26346. var source = this.bones[index];
  26347. var parentBone = null;
  26348. if (source.getParent()) {
  26349. var parentIndex = this.bones.indexOf(source.getParent());
  26350. parentBone = result.bones[parentIndex];
  26351. }
  26352. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26353. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26354. }
  26355. if (this._ranges) {
  26356. result._ranges = {};
  26357. for (var rangeName in this._ranges) {
  26358. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26359. }
  26360. }
  26361. this._isDirty = true;
  26362. return result;
  26363. };
  26364. Skeleton.prototype.dispose = function () {
  26365. this._meshesWithPoseMatrix = [];
  26366. // Animations
  26367. this.getScene().stopAnimation(this);
  26368. // Remove from scene
  26369. this.getScene().removeSkeleton(this);
  26370. };
  26371. Skeleton.prototype.serialize = function () {
  26372. var serializationObject = {};
  26373. serializationObject.name = this.name;
  26374. serializationObject.id = this.id;
  26375. serializationObject.bones = [];
  26376. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26377. for (var index = 0; index < this.bones.length; index++) {
  26378. var bone = this.bones[index];
  26379. var serializedBone = {
  26380. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26381. name: bone.name,
  26382. matrix: bone.getLocalMatrix().toArray(),
  26383. rest: bone.getRestPose().toArray()
  26384. };
  26385. serializationObject.bones.push(serializedBone);
  26386. if (bone.length) {
  26387. serializedBone.length = bone.length;
  26388. }
  26389. if (bone.animations && bone.animations.length > 0) {
  26390. serializedBone.animation = bone.animations[0].serialize();
  26391. }
  26392. serializationObject.ranges = [];
  26393. for (var name in this._ranges) {
  26394. var range = {};
  26395. range.name = name;
  26396. range.from = this._ranges[name].from;
  26397. range.to = this._ranges[name].to;
  26398. serializationObject.ranges.push(range);
  26399. }
  26400. }
  26401. return serializationObject;
  26402. };
  26403. Skeleton.Parse = function (parsedSkeleton, scene) {
  26404. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26405. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26406. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26407. var parsedBone = parsedSkeleton.bones[index];
  26408. var parentBone = null;
  26409. if (parsedBone.parentBoneIndex > -1) {
  26410. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26411. }
  26412. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26413. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26414. if (parsedBone.length) {
  26415. bone.length = parsedBone.length;
  26416. }
  26417. if (parsedBone.animation) {
  26418. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26419. }
  26420. }
  26421. // placed after bones, so createAnimationRange can cascade down
  26422. if (parsedSkeleton.ranges) {
  26423. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26424. var data = parsedSkeleton.ranges[index];
  26425. skeleton.createAnimationRange(data.name, data.from, data.to);
  26426. }
  26427. }
  26428. return skeleton;
  26429. };
  26430. return Skeleton;
  26431. }());
  26432. BABYLON.Skeleton = Skeleton;
  26433. })(BABYLON || (BABYLON = {}));
  26434. var BABYLON;
  26435. (function (BABYLON) {
  26436. var PostProcess = (function () {
  26437. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26439. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26440. this.name = name;
  26441. this.width = -1;
  26442. this.height = -1;
  26443. this._reusable = false;
  26444. this._textures = new BABYLON.SmartArray(2);
  26445. this._currentRenderTextureInd = 0;
  26446. if (camera != null) {
  26447. this._camera = camera;
  26448. this._scene = camera.getScene();
  26449. camera.attachPostProcess(this);
  26450. this._engine = this._scene.getEngine();
  26451. }
  26452. else {
  26453. this._engine = engine;
  26454. }
  26455. this._renderRatio = ratio;
  26456. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26457. this._reusable = reusable || false;
  26458. this._textureType = textureType;
  26459. this._samplers = samplers || [];
  26460. this._samplers.push("textureSampler");
  26461. this._fragmentUrl = fragmentUrl;
  26462. this._parameters = parameters || [];
  26463. this.updateEffect(defines);
  26464. }
  26465. PostProcess.prototype.updateEffect = function (defines) {
  26466. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26467. };
  26468. PostProcess.prototype.isReusable = function () {
  26469. return this._reusable;
  26470. };
  26471. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26472. camera = camera || this._camera;
  26473. var scene = camera.getScene();
  26474. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26475. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26476. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26477. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26478. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26479. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26480. if (this._textures.length > 0) {
  26481. for (var i = 0; i < this._textures.length; i++) {
  26482. this._engine._releaseTexture(this._textures.data[i]);
  26483. }
  26484. this._textures.reset();
  26485. }
  26486. this.width = desiredWidth;
  26487. this.height = desiredHeight;
  26488. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  26489. if (this._reusable) {
  26490. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  26491. }
  26492. if (this.onSizeChanged) {
  26493. this.onSizeChanged();
  26494. }
  26495. }
  26496. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26497. if (this.onActivate) {
  26498. this.onActivate(camera);
  26499. }
  26500. // Clear
  26501. if (this.clearColor) {
  26502. this._engine.clear(this.clearColor, true, true);
  26503. }
  26504. else {
  26505. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26506. }
  26507. if (this._reusable) {
  26508. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26509. }
  26510. };
  26511. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26512. get: function () {
  26513. return this._effect.isSupported;
  26514. },
  26515. enumerable: true,
  26516. configurable: true
  26517. });
  26518. PostProcess.prototype.apply = function () {
  26519. // Check
  26520. if (!this._effect.isReady())
  26521. return null;
  26522. // States
  26523. this._engine.enableEffect(this._effect);
  26524. this._engine.setState(false);
  26525. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26526. this._engine.setDepthBuffer(false);
  26527. this._engine.setDepthWrite(false);
  26528. // Texture
  26529. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26530. // Parameters
  26531. if (this.onApply) {
  26532. this.onApply(this._effect);
  26533. }
  26534. return this._effect;
  26535. };
  26536. PostProcess.prototype.dispose = function (camera) {
  26537. camera = camera || this._camera;
  26538. if (this._textures.length > 0) {
  26539. for (var i = 0; i < this._textures.length; i++) {
  26540. this._engine._releaseTexture(this._textures.data[i]);
  26541. }
  26542. this._textures.reset();
  26543. }
  26544. if (!camera) {
  26545. return;
  26546. }
  26547. camera.detachPostProcess(this);
  26548. var index = camera._postProcesses.indexOf(this);
  26549. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26550. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26551. }
  26552. };
  26553. return PostProcess;
  26554. }());
  26555. BABYLON.PostProcess = PostProcess;
  26556. })(BABYLON || (BABYLON = {}));
  26557. var BABYLON;
  26558. (function (BABYLON) {
  26559. var PostProcessManager = (function () {
  26560. function PostProcessManager(scene) {
  26561. this._vertexDeclaration = [2];
  26562. this._vertexStrideSize = 2 * 4;
  26563. this._scene = scene;
  26564. }
  26565. PostProcessManager.prototype._prepareBuffers = function () {
  26566. if (this._vertexBuffer) {
  26567. return;
  26568. }
  26569. // VBO
  26570. var vertices = [];
  26571. vertices.push(1, 1);
  26572. vertices.push(-1, 1);
  26573. vertices.push(-1, -1);
  26574. vertices.push(1, -1);
  26575. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26576. // Indices
  26577. var indices = [];
  26578. indices.push(0);
  26579. indices.push(1);
  26580. indices.push(2);
  26581. indices.push(0);
  26582. indices.push(2);
  26583. indices.push(3);
  26584. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26585. };
  26586. // Methods
  26587. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26588. var postProcesses = this._scene.activeCamera._postProcesses;
  26589. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26590. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26591. return false;
  26592. }
  26593. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26594. return true;
  26595. };
  26596. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26597. var engine = this._scene.getEngine();
  26598. for (var index = 0; index < postProcesses.length; index++) {
  26599. if (index < postProcesses.length - 1) {
  26600. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26601. }
  26602. else {
  26603. if (targetTexture) {
  26604. engine.bindFramebuffer(targetTexture);
  26605. }
  26606. else {
  26607. engine.restoreDefaultFramebuffer();
  26608. }
  26609. }
  26610. var pp = postProcesses[index];
  26611. var effect = pp.apply();
  26612. if (effect) {
  26613. if (pp.onBeforeRender) {
  26614. pp.onBeforeRender(effect);
  26615. }
  26616. // VBOs
  26617. this._prepareBuffers();
  26618. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26619. // Draw order
  26620. engine.draw(true, 0, 6);
  26621. if (pp.onAfterRender) {
  26622. pp.onAfterRender(effect);
  26623. }
  26624. }
  26625. }
  26626. // Restore depth buffer
  26627. engine.setDepthBuffer(true);
  26628. engine.setDepthWrite(true);
  26629. };
  26630. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26631. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26632. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26633. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26634. return;
  26635. }
  26636. var engine = this._scene.getEngine();
  26637. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26638. if (index < postProcessesTakenIndices.length - 1) {
  26639. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26640. }
  26641. else {
  26642. if (targetTexture) {
  26643. engine.bindFramebuffer(targetTexture, faceIndex);
  26644. }
  26645. else {
  26646. engine.restoreDefaultFramebuffer();
  26647. }
  26648. }
  26649. if (doNotPresent) {
  26650. break;
  26651. }
  26652. var pp = postProcesses[postProcessesTakenIndices[index]];
  26653. var effect = pp.apply();
  26654. if (effect) {
  26655. if (pp.onBeforeRender) {
  26656. pp.onBeforeRender(effect);
  26657. }
  26658. // VBOs
  26659. this._prepareBuffers();
  26660. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26661. // Draw order
  26662. engine.draw(true, 0, 6);
  26663. if (pp.onAfterRender) {
  26664. pp.onAfterRender(effect);
  26665. }
  26666. }
  26667. }
  26668. // Restore depth buffer
  26669. engine.setDepthBuffer(true);
  26670. engine.setDepthWrite(true);
  26671. };
  26672. PostProcessManager.prototype.dispose = function () {
  26673. if (this._vertexBuffer) {
  26674. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26675. this._vertexBuffer = null;
  26676. }
  26677. if (this._indexBuffer) {
  26678. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26679. this._indexBuffer = null;
  26680. }
  26681. };
  26682. return PostProcessManager;
  26683. }());
  26684. BABYLON.PostProcessManager = PostProcessManager;
  26685. })(BABYLON || (BABYLON = {}));
  26686. var BABYLON;
  26687. (function (BABYLON) {
  26688. var PassPostProcess = (function (_super) {
  26689. __extends(PassPostProcess, _super);
  26690. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26691. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26692. }
  26693. return PassPostProcess;
  26694. }(BABYLON.PostProcess));
  26695. BABYLON.PassPostProcess = PassPostProcess;
  26696. })(BABYLON || (BABYLON = {}));
  26697. var BABYLON;
  26698. (function (BABYLON) {
  26699. /**
  26700. * This is a holder class for the physics joint created by the physics plugin.
  26701. * It holds a set of functions to control the underlying joint.
  26702. */
  26703. var PhysicsJoint = (function () {
  26704. function PhysicsJoint(type, jointData) {
  26705. this.type = type;
  26706. this.jointData = jointData;
  26707. jointData.nativeParams = jointData.nativeParams || {};
  26708. }
  26709. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26710. get: function () {
  26711. return this._physicsJoint;
  26712. },
  26713. set: function (newJoint) {
  26714. if (this._physicsJoint) {
  26715. }
  26716. this._physicsJoint = newJoint;
  26717. },
  26718. enumerable: true,
  26719. configurable: true
  26720. });
  26721. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26722. set: function (physicsPlugin) {
  26723. this._physicsPlugin = physicsPlugin;
  26724. },
  26725. enumerable: true,
  26726. configurable: true
  26727. });
  26728. /**
  26729. * Execute a function that is physics-plugin specific.
  26730. * @param {Function} func the function that will be executed.
  26731. * It accepts two parameters: the physics world and the physics joint.
  26732. */
  26733. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26734. func(this._physicsPlugin.world, this._physicsJoint);
  26735. };
  26736. //TODO check if the native joints are the same
  26737. //Joint Types
  26738. PhysicsJoint.DistanceJoint = 0;
  26739. PhysicsJoint.HingeJoint = 1;
  26740. PhysicsJoint.BallAndSocketJoint = 2;
  26741. PhysicsJoint.WheelJoint = 3;
  26742. PhysicsJoint.SliderJoint = 4;
  26743. //OIMO
  26744. PhysicsJoint.PrismaticJoint = 5;
  26745. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26746. PhysicsJoint.UniversalJoint = 6;
  26747. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26748. //Cannon
  26749. //Similar to a Ball-Joint. Different in params
  26750. PhysicsJoint.PointToPointJoint = 8;
  26751. //Cannon only at the moment
  26752. PhysicsJoint.SpringJoint = 9;
  26753. return PhysicsJoint;
  26754. }());
  26755. BABYLON.PhysicsJoint = PhysicsJoint;
  26756. /**
  26757. * A class representing a physics distance joint.
  26758. */
  26759. var DistanceJoint = (function (_super) {
  26760. __extends(DistanceJoint, _super);
  26761. function DistanceJoint(jointData) {
  26762. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26763. }
  26764. /**
  26765. * Update the predefined distance.
  26766. */
  26767. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26768. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26769. };
  26770. return DistanceJoint;
  26771. }(PhysicsJoint));
  26772. BABYLON.DistanceJoint = DistanceJoint;
  26773. /**
  26774. * This class represents a single hinge physics joint
  26775. */
  26776. var HingeJoint = (function (_super) {
  26777. __extends(HingeJoint, _super);
  26778. function HingeJoint(jointData) {
  26779. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26780. }
  26781. /**
  26782. * Set the motor values.
  26783. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26784. * @param {number} force the force to apply
  26785. * @param {number} maxForce max force for this motor.
  26786. */
  26787. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26788. this._physicsPlugin.setMotor(this, force, maxForce);
  26789. };
  26790. /**
  26791. * Set the motor's limits.
  26792. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26793. */
  26794. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26795. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26796. };
  26797. return HingeJoint;
  26798. }(PhysicsJoint));
  26799. BABYLON.HingeJoint = HingeJoint;
  26800. /**
  26801. * This class represents a dual hinge physics joint (same as wheel joint)
  26802. */
  26803. var Hinge2Joint = (function (_super) {
  26804. __extends(Hinge2Joint, _super);
  26805. function Hinge2Joint(jointData) {
  26806. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26807. }
  26808. /**
  26809. * Set the motor values.
  26810. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26811. * @param {number} force the force to apply
  26812. * @param {number} maxForce max force for this motor.
  26813. * @param {motorIndex} the motor's index, 0 or 1.
  26814. */
  26815. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26816. if (motorIndex === void 0) { motorIndex = 0; }
  26817. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26818. };
  26819. /**
  26820. * Set the motor limits.
  26821. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26822. * @param {number} upperLimit the upper limit
  26823. * @param {number} lowerLimit lower limit
  26824. * @param {motorIndex} the motor's index, 0 or 1.
  26825. */
  26826. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26827. if (motorIndex === void 0) { motorIndex = 0; }
  26828. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26829. };
  26830. return Hinge2Joint;
  26831. }(PhysicsJoint));
  26832. BABYLON.Hinge2Joint = Hinge2Joint;
  26833. })(BABYLON || (BABYLON = {}));
  26834. var BABYLON;
  26835. (function (BABYLON) {
  26836. var PhysicsImpostor = (function () {
  26837. function PhysicsImpostor(object, type, _options, _scene) {
  26838. var _this = this;
  26839. if (_options === void 0) { _options = { mass: 0 }; }
  26840. this.object = object;
  26841. this.type = type;
  26842. this._options = _options;
  26843. this._scene = _scene;
  26844. this._bodyUpdateRequired = false;
  26845. this._onBeforePhysicsStepCallbacks = new Array();
  26846. this._onAfterPhysicsStepCallbacks = new Array();
  26847. this._onPhysicsCollideCallbacks = [];
  26848. this._deltaPosition = BABYLON.Vector3.Zero();
  26849. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  26850. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  26851. /**
  26852. * this function is executed by the physics engine.
  26853. */
  26854. this.beforeStep = function () {
  26855. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  26856. //conjugate deltaRotation
  26857. if (_this._deltaRotationConjugated) {
  26858. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  26859. }
  26860. else {
  26861. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  26862. }
  26863. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  26864. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  26865. func(_this);
  26866. });
  26867. };
  26868. /**
  26869. * this function is executed by the physics engine.
  26870. */
  26871. this.afterStep = function () {
  26872. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  26873. func(_this);
  26874. });
  26875. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  26876. _this.object.position.addInPlace(_this._deltaPosition);
  26877. if (_this._deltaRotation) {
  26878. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  26879. }
  26880. };
  26881. //event and body object due to cannon's event-based architecture.
  26882. this.onCollide = function (e) {
  26883. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  26884. if (otherImpostor) {
  26885. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  26886. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  26887. }).forEach(function (obj) {
  26888. obj.callback(_this, otherImpostor);
  26889. });
  26890. }
  26891. };
  26892. //sanity check!
  26893. if (!this.object) {
  26894. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  26895. return;
  26896. }
  26897. //legacy support for old syntax.
  26898. if (!this._scene && object.getScene) {
  26899. this._scene = object.getScene();
  26900. }
  26901. this._physicsEngine = this._scene.getPhysicsEngine();
  26902. if (!this._physicsEngine) {
  26903. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  26904. }
  26905. else {
  26906. //set the object's quaternion, if not set
  26907. if (!this.object.rotationQuaternion) {
  26908. if (this.object.rotation) {
  26909. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  26910. }
  26911. else {
  26912. this.object.rotationQuaternion = new BABYLON.Quaternion();
  26913. }
  26914. }
  26915. //default options params
  26916. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  26917. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  26918. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  26919. this._joints = [];
  26920. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  26921. if (!this.object.parent) {
  26922. this._init();
  26923. }
  26924. }
  26925. }
  26926. /**
  26927. * This function will completly initialize this impostor.
  26928. * It will create a new body - but only if this mesh has no parent.
  26929. * If it has, this impostor will not be used other than to define the impostor
  26930. * of the child mesh.
  26931. */
  26932. PhysicsImpostor.prototype._init = function () {
  26933. this._physicsEngine.removeImpostor(this);
  26934. this.physicsBody = null;
  26935. this._parent = this._parent || this._getPhysicsParent();
  26936. if (!this.parent) {
  26937. this._physicsEngine.addImpostor(this);
  26938. }
  26939. };
  26940. PhysicsImpostor.prototype._getPhysicsParent = function () {
  26941. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  26942. var parentMesh = this.object.parent;
  26943. return parentMesh.physicsImpostor;
  26944. }
  26945. return;
  26946. };
  26947. /**
  26948. * Should a new body be generated.
  26949. */
  26950. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  26951. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  26952. };
  26953. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  26954. this.forceUpdate();
  26955. };
  26956. /**
  26957. * Force a regeneration of this or the parent's impostor's body.
  26958. * Use under cautious - This will remove all joints already implemented.
  26959. */
  26960. PhysicsImpostor.prototype.forceUpdate = function () {
  26961. this._init();
  26962. if (this.parent) {
  26963. this.parent.forceUpdate();
  26964. }
  26965. };
  26966. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  26967. /*public get mesh(): AbstractMesh {
  26968. return this._mesh;
  26969. }*/
  26970. /**
  26971. * Gets the body that holds this impostor. Either its own, or its parent.
  26972. */
  26973. get: function () {
  26974. return this._parent ? this._parent.physicsBody : this._physicsBody;
  26975. },
  26976. /**
  26977. * Set the physics body. Used mainly by the physics engine/plugin
  26978. */
  26979. set: function (physicsBody) {
  26980. if (this._physicsBody) {
  26981. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  26982. }
  26983. this._physicsBody = physicsBody;
  26984. this.resetUpdateFlags();
  26985. },
  26986. enumerable: true,
  26987. configurable: true
  26988. });
  26989. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  26990. get: function () {
  26991. return this._parent;
  26992. },
  26993. enumerable: true,
  26994. configurable: true
  26995. });
  26996. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  26997. this._bodyUpdateRequired = false;
  26998. };
  26999. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27000. if (this.object.getBoundingInfo) {
  27001. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27002. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27003. }
  27004. else {
  27005. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27006. }
  27007. };
  27008. PhysicsImpostor.prototype.getObjectCenter = function () {
  27009. if (this.object.getBoundingInfo) {
  27010. return this.object.getBoundingInfo().boundingBox.center;
  27011. }
  27012. else {
  27013. return this.object.position;
  27014. }
  27015. };
  27016. /**
  27017. * Get a specific parametes from the options parameter.
  27018. */
  27019. PhysicsImpostor.prototype.getParam = function (paramName) {
  27020. return this._options[paramName];
  27021. };
  27022. /**
  27023. * Sets a specific parameter in the options given to the physics plugin
  27024. */
  27025. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27026. this._options[paramName] = value;
  27027. this._bodyUpdateRequired = true;
  27028. };
  27029. /**
  27030. * Specifically change the body's mass option. Won't recreate the physics body object
  27031. */
  27032. PhysicsImpostor.prototype.setMass = function (mass) {
  27033. if (this.getParam("mass") !== mass) {
  27034. this.setParam("mass", mass);
  27035. }
  27036. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27037. };
  27038. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27039. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27040. };
  27041. /**
  27042. * Set the body's linear velocity.
  27043. */
  27044. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27045. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27046. };
  27047. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27048. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27049. };
  27050. /**
  27051. * Set the body's linear velocity.
  27052. */
  27053. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27054. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27055. };
  27056. /**
  27057. * Execute a function with the physics plugin native code.
  27058. * Provide a function the will have two variables - the world object and the physics body object.
  27059. */
  27060. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27061. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27062. };
  27063. /**
  27064. * Register a function that will be executed before the physics world is stepping forward.
  27065. */
  27066. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27067. this._onBeforePhysicsStepCallbacks.push(func);
  27068. };
  27069. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27070. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27071. if (index > -1) {
  27072. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27073. }
  27074. else {
  27075. BABYLON.Tools.Warn("Function to remove was not found");
  27076. }
  27077. };
  27078. /**
  27079. * Register a function that will be executed after the physics step
  27080. */
  27081. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27082. this._onAfterPhysicsStepCallbacks.push(func);
  27083. };
  27084. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27085. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27086. if (index > -1) {
  27087. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27088. }
  27089. else {
  27090. BABYLON.Tools.Warn("Function to remove was not found");
  27091. }
  27092. };
  27093. /**
  27094. * register a function that will be executed when this impostor collides against a different body.
  27095. */
  27096. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27097. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27098. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27099. };
  27100. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27101. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27102. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27103. if (index > -1) {
  27104. this._onPhysicsCollideCallbacks.splice(index, 1);
  27105. }
  27106. else {
  27107. BABYLON.Tools.Warn("Function to remove was not found");
  27108. }
  27109. };
  27110. /**
  27111. * Apply a force
  27112. */
  27113. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27114. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27115. };
  27116. /**
  27117. * Apply an impulse
  27118. */
  27119. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27120. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27121. };
  27122. /**
  27123. * A help function to create a joint.
  27124. */
  27125. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27126. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27127. this.addJoint(otherImpostor, joint);
  27128. };
  27129. /**
  27130. * Add a joint to this impostor with a different impostor.
  27131. */
  27132. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27133. this._joints.push({
  27134. otherImpostor: otherImpostor,
  27135. joint: joint
  27136. });
  27137. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27138. };
  27139. /**
  27140. * Will keep this body still, in a sleep mode.
  27141. */
  27142. PhysicsImpostor.prototype.sleep = function () {
  27143. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27144. };
  27145. /**
  27146. * Wake the body up.
  27147. */
  27148. PhysicsImpostor.prototype.wakeUp = function () {
  27149. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27150. };
  27151. PhysicsImpostor.prototype.clone = function (newObject) {
  27152. if (!newObject)
  27153. return null;
  27154. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27155. };
  27156. PhysicsImpostor.prototype.dispose = function () {
  27157. this.physicsBody = null;
  27158. if (this.parent) {
  27159. this.parent.forceUpdate();
  27160. }
  27161. else {
  27162. }
  27163. };
  27164. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27165. this._deltaPosition.copyFrom(position);
  27166. };
  27167. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27168. if (!this._deltaRotation) {
  27169. this._deltaRotation = new BABYLON.Quaternion();
  27170. }
  27171. this._deltaRotation.copyFrom(rotation);
  27172. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27173. };
  27174. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27175. //Impostor types
  27176. PhysicsImpostor.NoImpostor = 0;
  27177. PhysicsImpostor.SphereImpostor = 1;
  27178. PhysicsImpostor.BoxImpostor = 2;
  27179. PhysicsImpostor.PlaneImpostor = 3;
  27180. PhysicsImpostor.MeshImpostor = 4;
  27181. PhysicsImpostor.CylinderImpostor = 7;
  27182. PhysicsImpostor.ParticleImpostor = 8;
  27183. PhysicsImpostor.HeightmapImpostor = 9;
  27184. return PhysicsImpostor;
  27185. }());
  27186. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27187. })(BABYLON || (BABYLON = {}));
  27188. var BABYLON;
  27189. (function (BABYLON) {
  27190. var PhysicsEngine = (function () {
  27191. function PhysicsEngine(gravity, _physicsPlugin) {
  27192. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27193. this._physicsPlugin = _physicsPlugin;
  27194. //new methods and parameters
  27195. this._impostors = [];
  27196. this._joints = [];
  27197. if (!this._physicsPlugin.isSupported()) {
  27198. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27199. + "Please make sure it is included.");
  27200. }
  27201. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27202. this.setGravity(gravity);
  27203. this.setTimeStep();
  27204. }
  27205. PhysicsEngine.prototype.setGravity = function (gravity) {
  27206. this.gravity = gravity;
  27207. this._physicsPlugin.setGravity(this.gravity);
  27208. };
  27209. /**
  27210. * Set the time step of the physics engine.
  27211. * default is 1/60.
  27212. * To slow it down, enter 1/600 for example.
  27213. * To speed it up, 1/30
  27214. * @param {number} newTimeStep the new timestep to apply to this world.
  27215. */
  27216. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27217. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27218. this._physicsPlugin.setTimeStep(newTimeStep);
  27219. };
  27220. PhysicsEngine.prototype.dispose = function () {
  27221. this._impostors.forEach(function (impostor) {
  27222. impostor.dispose();
  27223. });
  27224. this._physicsPlugin.dispose();
  27225. };
  27226. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27227. return this._physicsPlugin.name;
  27228. };
  27229. /**
  27230. * Adding a new impostor for the impostor tracking.
  27231. * This will be done by the impostor itself.
  27232. * @param {PhysicsImpostor} impostor the impostor to add
  27233. */
  27234. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27235. impostor.uniqueId = this._impostors.push(impostor);
  27236. //if no parent, generate the body
  27237. if (!impostor.parent) {
  27238. this._physicsPlugin.generatePhysicsBody(impostor);
  27239. }
  27240. };
  27241. /**
  27242. * Remove an impostor from the engine.
  27243. * This impostor and its mesh will not longer be updated by the physics engine.
  27244. * @param {PhysicsImpostor} impostor the impostor to remove
  27245. */
  27246. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27247. var index = this._impostors.indexOf(impostor);
  27248. if (index > -1) {
  27249. var removed = this._impostors.splice(index, 1);
  27250. //Is it needed?
  27251. if (removed.length) {
  27252. //this will also remove it from the world.
  27253. removed[0].physicsBody = null;
  27254. }
  27255. }
  27256. };
  27257. /**
  27258. * Add a joint to the physics engine
  27259. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27260. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27261. * @param {PhysicsJoint} the joint that will connect both impostors.
  27262. */
  27263. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27264. var impostorJoint = {
  27265. mainImpostor: mainImpostor,
  27266. connectedImpostor: connectedImpostor,
  27267. joint: joint
  27268. };
  27269. joint.physicsPlugin = this._physicsPlugin;
  27270. this._joints.push(impostorJoint);
  27271. this._physicsPlugin.generateJoint(impostorJoint);
  27272. };
  27273. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27274. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27275. return (impostorJoint.connectedImpostor === connectedImpostor
  27276. && impostorJoint.joint === joint
  27277. && impostorJoint.mainImpostor === mainImpostor);
  27278. });
  27279. if (matchingJoints.length) {
  27280. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27281. }
  27282. };
  27283. /**
  27284. * Called by the scene. no need to call it.
  27285. */
  27286. PhysicsEngine.prototype._step = function (delta) {
  27287. var _this = this;
  27288. //check if any mesh has no body / requires an update
  27289. this._impostors.forEach(function (impostor) {
  27290. if (impostor.isBodyInitRequired()) {
  27291. _this._physicsPlugin.generatePhysicsBody(impostor);
  27292. }
  27293. });
  27294. if (delta > 0.1) {
  27295. delta = 0.1;
  27296. }
  27297. else if (delta <= 0) {
  27298. delta = 1.0 / 60.0;
  27299. }
  27300. this._physicsPlugin.executeStep(delta, this._impostors);
  27301. };
  27302. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27303. return this._physicsPlugin;
  27304. };
  27305. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27306. for (var i = 0; i < this._impostors.length; ++i) {
  27307. if (this._impostors[i].object === object) {
  27308. return this._impostors[i];
  27309. }
  27310. }
  27311. };
  27312. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27313. for (var i = 0; i < this._impostors.length; ++i) {
  27314. if (this._impostors[i].physicsBody === body) {
  27315. return this._impostors[i];
  27316. }
  27317. }
  27318. };
  27319. // Statics, Legacy support.
  27320. /**
  27321. * @Deprecated
  27322. *
  27323. */
  27324. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27325. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27326. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27327. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27328. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27329. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27330. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27331. PhysicsEngine.CapsuleImpostor = -1;
  27332. PhysicsEngine.ConeImpostor = -1;
  27333. PhysicsEngine.ConvexHullImpostor = -1;
  27334. PhysicsEngine.Epsilon = 0.001;
  27335. return PhysicsEngine;
  27336. }());
  27337. BABYLON.PhysicsEngine = PhysicsEngine;
  27338. })(BABYLON || (BABYLON = {}));
  27339. var BABYLON;
  27340. (function (BABYLON) {
  27341. var VertexData = (function () {
  27342. function VertexData() {
  27343. }
  27344. VertexData.prototype.set = function (data, kind) {
  27345. switch (kind) {
  27346. case BABYLON.VertexBuffer.PositionKind:
  27347. this.positions = data;
  27348. break;
  27349. case BABYLON.VertexBuffer.NormalKind:
  27350. this.normals = data;
  27351. break;
  27352. case BABYLON.VertexBuffer.UVKind:
  27353. this.uvs = data;
  27354. break;
  27355. case BABYLON.VertexBuffer.UV2Kind:
  27356. this.uvs2 = data;
  27357. break;
  27358. case BABYLON.VertexBuffer.UV3Kind:
  27359. this.uvs3 = data;
  27360. break;
  27361. case BABYLON.VertexBuffer.UV4Kind:
  27362. this.uvs4 = data;
  27363. break;
  27364. case BABYLON.VertexBuffer.UV5Kind:
  27365. this.uvs5 = data;
  27366. break;
  27367. case BABYLON.VertexBuffer.UV6Kind:
  27368. this.uvs6 = data;
  27369. break;
  27370. case BABYLON.VertexBuffer.ColorKind:
  27371. this.colors = data;
  27372. break;
  27373. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27374. this.matricesIndices = data;
  27375. break;
  27376. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27377. this.matricesWeights = data;
  27378. break;
  27379. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27380. this.matricesIndicesExtra = data;
  27381. break;
  27382. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27383. this.matricesWeightsExtra = data;
  27384. break;
  27385. }
  27386. };
  27387. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27388. this._applyTo(mesh, updatable);
  27389. };
  27390. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27391. this._applyTo(geometry, updatable);
  27392. };
  27393. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27394. this._update(mesh);
  27395. };
  27396. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27397. this._update(geometry);
  27398. };
  27399. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27400. if (this.positions) {
  27401. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27402. }
  27403. if (this.normals) {
  27404. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27405. }
  27406. if (this.uvs) {
  27407. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27408. }
  27409. if (this.uvs2) {
  27410. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27411. }
  27412. if (this.uvs3) {
  27413. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27414. }
  27415. if (this.uvs4) {
  27416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27417. }
  27418. if (this.uvs5) {
  27419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27420. }
  27421. if (this.uvs6) {
  27422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27423. }
  27424. if (this.colors) {
  27425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27426. }
  27427. if (this.matricesIndices) {
  27428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27429. }
  27430. if (this.matricesWeights) {
  27431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27432. }
  27433. if (this.matricesIndicesExtra) {
  27434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27435. }
  27436. if (this.matricesWeightsExtra) {
  27437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27438. }
  27439. if (this.indices) {
  27440. meshOrGeometry.setIndices(this.indices);
  27441. }
  27442. };
  27443. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27444. if (this.positions) {
  27445. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27446. }
  27447. if (this.normals) {
  27448. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27449. }
  27450. if (this.uvs) {
  27451. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27452. }
  27453. if (this.uvs2) {
  27454. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27455. }
  27456. if (this.uvs3) {
  27457. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27458. }
  27459. if (this.uvs4) {
  27460. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27461. }
  27462. if (this.uvs5) {
  27463. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27464. }
  27465. if (this.uvs6) {
  27466. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27467. }
  27468. if (this.colors) {
  27469. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27470. }
  27471. if (this.matricesIndices) {
  27472. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27473. }
  27474. if (this.matricesWeights) {
  27475. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27476. }
  27477. if (this.matricesIndicesExtra) {
  27478. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27479. }
  27480. if (this.matricesWeightsExtra) {
  27481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27482. }
  27483. if (this.indices) {
  27484. meshOrGeometry.setIndices(this.indices);
  27485. }
  27486. };
  27487. VertexData.prototype.transform = function (matrix) {
  27488. var transformed = BABYLON.Vector3.Zero();
  27489. var index;
  27490. if (this.positions) {
  27491. var position = BABYLON.Vector3.Zero();
  27492. for (index = 0; index < this.positions.length; index += 3) {
  27493. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27494. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27495. this.positions[index] = transformed.x;
  27496. this.positions[index + 1] = transformed.y;
  27497. this.positions[index + 2] = transformed.z;
  27498. }
  27499. }
  27500. if (this.normals) {
  27501. var normal = BABYLON.Vector3.Zero();
  27502. for (index = 0; index < this.normals.length; index += 3) {
  27503. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27504. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27505. this.normals[index] = transformed.x;
  27506. this.normals[index + 1] = transformed.y;
  27507. this.normals[index + 2] = transformed.z;
  27508. }
  27509. }
  27510. };
  27511. VertexData.prototype.merge = function (other) {
  27512. if (other.indices) {
  27513. if (!this.indices) {
  27514. this.indices = [];
  27515. }
  27516. var offset = this.positions ? this.positions.length / 3 : 0;
  27517. for (var index = 0; index < other.indices.length; index++) {
  27518. //TODO check type - if Int32Array!
  27519. this.indices.push(other.indices[index] + offset);
  27520. }
  27521. }
  27522. this.positions = this._mergeElement(this.positions, other.positions);
  27523. this.normals = this._mergeElement(this.normals, other.normals);
  27524. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27525. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27526. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27527. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27528. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27529. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27530. this.colors = this._mergeElement(this.colors, other.colors);
  27531. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27532. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27533. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27534. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27535. };
  27536. VertexData.prototype._mergeElement = function (source, other) {
  27537. if (!other)
  27538. return source;
  27539. if (!source)
  27540. return other;
  27541. var len = other.length + source.length;
  27542. var isSrcTypedArray = source instanceof Float32Array;
  27543. var isOthTypedArray = other instanceof Float32Array;
  27544. // use non-loop method when the source is Float32Array
  27545. if (isSrcTypedArray) {
  27546. var ret32 = new Float32Array(len);
  27547. ret32.set(source);
  27548. ret32.set(other, source.length);
  27549. return ret32;
  27550. }
  27551. else if (!isOthTypedArray) {
  27552. return source.concat(other);
  27553. }
  27554. else {
  27555. var ret = source.slice(0); // copy source to a separate array
  27556. for (var i = 0, len = other.length; i < len; i++) {
  27557. ret.push(other[i]);
  27558. }
  27559. return ret;
  27560. }
  27561. };
  27562. VertexData.prototype.serialize = function () {
  27563. var serializationObject = this.serialize();
  27564. if (this.positions) {
  27565. serializationObject.positions = this.positions;
  27566. }
  27567. if (this.normals) {
  27568. serializationObject.normals = this.normals;
  27569. }
  27570. if (this.uvs) {
  27571. serializationObject.uvs = this.uvs;
  27572. }
  27573. if (this.uvs2) {
  27574. serializationObject.uvs2 = this.uvs2;
  27575. }
  27576. if (this.uvs3) {
  27577. serializationObject.uvs3 = this.uvs3;
  27578. }
  27579. if (this.uvs4) {
  27580. serializationObject.uvs4 = this.uvs4;
  27581. }
  27582. if (this.uvs5) {
  27583. serializationObject.uvs5 = this.uvs5;
  27584. }
  27585. if (this.uvs6) {
  27586. serializationObject.uvs6 = this.uvs6;
  27587. }
  27588. if (this.colors) {
  27589. serializationObject.colors = this.colors;
  27590. }
  27591. if (this.matricesIndices) {
  27592. serializationObject.matricesIndices = this.matricesIndices;
  27593. serializationObject.matricesIndices._isExpanded = true;
  27594. }
  27595. if (this.matricesWeights) {
  27596. serializationObject.matricesWeights = this.matricesWeights;
  27597. }
  27598. if (this.matricesIndicesExtra) {
  27599. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27600. serializationObject.matricesIndicesExtra._isExpanded = true;
  27601. }
  27602. if (this.matricesWeightsExtra) {
  27603. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27604. }
  27605. serializationObject.indices = this.indices;
  27606. return serializationObject;
  27607. };
  27608. // Statics
  27609. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27610. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27611. };
  27612. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27613. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27614. };
  27615. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27616. var result = new VertexData();
  27617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27618. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27619. }
  27620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27621. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27622. }
  27623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27624. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27625. }
  27626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27627. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27628. }
  27629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27630. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27631. }
  27632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27633. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27634. }
  27635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27636. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27637. }
  27638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27639. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27640. }
  27641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27642. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27643. }
  27644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27645. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27646. }
  27647. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27648. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27649. }
  27650. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27651. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27652. }
  27653. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27654. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27655. }
  27656. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27657. return result;
  27658. };
  27659. VertexData.CreateRibbon = function (options) {
  27660. var pathArray = options.pathArray;
  27661. var closeArray = options.closeArray || false;
  27662. var closePath = options.closePath || false;
  27663. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27664. var offset = options.offset || defaultOffset;
  27665. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27666. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27667. var positions = [];
  27668. var indices = [];
  27669. var normals = [];
  27670. var uvs = [];
  27671. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27672. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27673. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27674. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27675. var minlg; // minimal length among all paths from pathArray
  27676. var lg = []; // array of path lengths : nb of vertex per path
  27677. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27678. var p; // path iterator
  27679. var i; // point iterator
  27680. var j; // point iterator
  27681. // if single path in pathArray
  27682. if (pathArray.length < 2) {
  27683. var ar1 = [];
  27684. var ar2 = [];
  27685. for (i = 0; i < pathArray[0].length - offset; i++) {
  27686. ar1.push(pathArray[0][i]);
  27687. ar2.push(pathArray[0][i + offset]);
  27688. }
  27689. pathArray = [ar1, ar2];
  27690. }
  27691. // positions and horizontal distances (u)
  27692. var idc = 0;
  27693. var closePathCorr = (closePath) ? 1 : 0;
  27694. var path;
  27695. var l;
  27696. minlg = pathArray[0].length;
  27697. var vectlg;
  27698. var dist;
  27699. for (p = 0; p < pathArray.length; p++) {
  27700. uTotalDistance[p] = 0;
  27701. us[p] = [0];
  27702. path = pathArray[p];
  27703. l = path.length;
  27704. minlg = (minlg < l) ? minlg : l;
  27705. j = 0;
  27706. while (j < l) {
  27707. positions.push(path[j].x, path[j].y, path[j].z);
  27708. if (j > 0) {
  27709. vectlg = path[j].subtract(path[j - 1]).length();
  27710. dist = vectlg + uTotalDistance[p];
  27711. us[p].push(dist);
  27712. uTotalDistance[p] = dist;
  27713. }
  27714. j++;
  27715. }
  27716. if (closePath) {
  27717. j--;
  27718. positions.push(path[0].x, path[0].y, path[0].z);
  27719. vectlg = path[j].subtract(path[0]).length();
  27720. dist = vectlg + uTotalDistance[p];
  27721. us[p].push(dist);
  27722. uTotalDistance[p] = dist;
  27723. }
  27724. lg[p] = l + closePathCorr;
  27725. idx[p] = idc;
  27726. idc += (l + closePathCorr);
  27727. }
  27728. // vertical distances (v)
  27729. var path1;
  27730. var path2;
  27731. var vertex1;
  27732. var vertex2;
  27733. for (i = 0; i < minlg + closePathCorr; i++) {
  27734. vTotalDistance[i] = 0;
  27735. vs[i] = [0];
  27736. for (p = 0; p < pathArray.length - 1; p++) {
  27737. path1 = pathArray[p];
  27738. path2 = pathArray[p + 1];
  27739. if (i === minlg) {
  27740. vertex1 = path1[0];
  27741. vertex2 = path2[0];
  27742. }
  27743. else {
  27744. vertex1 = path1[i];
  27745. vertex2 = path2[i];
  27746. }
  27747. vectlg = vertex2.subtract(vertex1).length();
  27748. dist = vectlg + vTotalDistance[i];
  27749. vs[i].push(dist);
  27750. vTotalDistance[i] = dist;
  27751. }
  27752. if (closeArray) {
  27753. path1 = pathArray[p];
  27754. path2 = pathArray[0];
  27755. if (i === minlg) {
  27756. vertex2 = path2[0];
  27757. }
  27758. vectlg = vertex2.subtract(vertex1).length();
  27759. dist = vectlg + vTotalDistance[i];
  27760. vTotalDistance[i] = dist;
  27761. }
  27762. }
  27763. // uvs
  27764. var u;
  27765. var v;
  27766. for (p = 0; p < pathArray.length; p++) {
  27767. for (i = 0; i < minlg + closePathCorr; i++) {
  27768. u = us[p][i] / uTotalDistance[p];
  27769. v = vs[i][p] / vTotalDistance[i];
  27770. uvs.push(u, v);
  27771. }
  27772. }
  27773. // indices
  27774. p = 0; // path index
  27775. var pi = 0; // positions array index
  27776. var l1 = lg[p] - 1; // path1 length
  27777. var l2 = lg[p + 1] - 1; // path2 length
  27778. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27779. var shft = idx[1] - idx[0]; // shift
  27780. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27781. while (pi <= min && p < path1nb) {
  27782. // 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
  27783. indices.push(pi, pi + shft, pi + 1);
  27784. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27785. pi += 1;
  27786. if (pi === min) {
  27787. p++;
  27788. if (p === lg.length - 1) {
  27789. shft = idx[0] - idx[p];
  27790. l1 = lg[p] - 1;
  27791. l2 = lg[0] - 1;
  27792. }
  27793. else {
  27794. shft = idx[p + 1] - idx[p];
  27795. l1 = lg[p] - 1;
  27796. l2 = lg[p + 1] - 1;
  27797. }
  27798. pi = idx[p];
  27799. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27800. }
  27801. }
  27802. // normals
  27803. VertexData.ComputeNormals(positions, indices, normals);
  27804. if (closePath) {
  27805. var indexFirst = 0;
  27806. var indexLast = 0;
  27807. for (p = 0; p < pathArray.length; p++) {
  27808. indexFirst = idx[p] * 3;
  27809. if (p + 1 < pathArray.length) {
  27810. indexLast = (idx[p + 1] - 1) * 3;
  27811. }
  27812. else {
  27813. indexLast = normals.length - 3;
  27814. }
  27815. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27816. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27817. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27818. normals[indexLast] = normals[indexFirst];
  27819. normals[indexLast + 1] = normals[indexFirst + 1];
  27820. normals[indexLast + 2] = normals[indexFirst + 2];
  27821. }
  27822. }
  27823. // sides
  27824. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27825. // Result
  27826. var vertexData = new VertexData();
  27827. vertexData.indices = indices;
  27828. vertexData.positions = positions;
  27829. vertexData.normals = normals;
  27830. vertexData.uvs = uvs;
  27831. if (closePath) {
  27832. vertexData._idx = idx;
  27833. }
  27834. return vertexData;
  27835. };
  27836. VertexData.CreateBox = function (options) {
  27837. var normalsSource = [
  27838. new BABYLON.Vector3(0, 0, 1),
  27839. new BABYLON.Vector3(0, 0, -1),
  27840. new BABYLON.Vector3(1, 0, 0),
  27841. new BABYLON.Vector3(-1, 0, 0),
  27842. new BABYLON.Vector3(0, 1, 0),
  27843. new BABYLON.Vector3(0, -1, 0)
  27844. ];
  27845. var indices = [];
  27846. var positions = [];
  27847. var normals = [];
  27848. var uvs = [];
  27849. var width = options.width || options.size || 1;
  27850. var height = options.height || options.size || 1;
  27851. var depth = options.depth || options.size || 1;
  27852. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27853. var faceUV = options.faceUV || new Array(6);
  27854. var faceColors = options.faceColors;
  27855. var colors = [];
  27856. // default face colors and UV if undefined
  27857. for (var f = 0; f < 6; f++) {
  27858. if (faceUV[f] === undefined) {
  27859. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27860. }
  27861. if (faceColors && faceColors[f] === undefined) {
  27862. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27863. }
  27864. }
  27865. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27866. // Create each face in turn.
  27867. for (var index = 0; index < normalsSource.length; index++) {
  27868. var normal = normalsSource[index];
  27869. // Get two vectors perpendicular to the face normal and to each other.
  27870. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27871. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27872. // Six indices (two triangles) per face.
  27873. var verticesLength = positions.length / 3;
  27874. indices.push(verticesLength);
  27875. indices.push(verticesLength + 1);
  27876. indices.push(verticesLength + 2);
  27877. indices.push(verticesLength);
  27878. indices.push(verticesLength + 2);
  27879. indices.push(verticesLength + 3);
  27880. // Four vertices per face.
  27881. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27882. positions.push(vertex.x, vertex.y, vertex.z);
  27883. normals.push(normal.x, normal.y, normal.z);
  27884. uvs.push(faceUV[index].z, faceUV[index].w);
  27885. if (faceColors) {
  27886. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27887. }
  27888. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27889. positions.push(vertex.x, vertex.y, vertex.z);
  27890. normals.push(normal.x, normal.y, normal.z);
  27891. uvs.push(faceUV[index].x, faceUV[index].w);
  27892. if (faceColors) {
  27893. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27894. }
  27895. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27896. positions.push(vertex.x, vertex.y, vertex.z);
  27897. normals.push(normal.x, normal.y, normal.z);
  27898. uvs.push(faceUV[index].x, faceUV[index].y);
  27899. if (faceColors) {
  27900. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27901. }
  27902. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27903. positions.push(vertex.x, vertex.y, vertex.z);
  27904. normals.push(normal.x, normal.y, normal.z);
  27905. uvs.push(faceUV[index].z, faceUV[index].y);
  27906. if (faceColors) {
  27907. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27908. }
  27909. }
  27910. // sides
  27911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27912. // Result
  27913. var vertexData = new VertexData();
  27914. vertexData.indices = indices;
  27915. vertexData.positions = positions;
  27916. vertexData.normals = normals;
  27917. vertexData.uvs = uvs;
  27918. if (faceColors) {
  27919. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27920. vertexData.colors = totalColors;
  27921. }
  27922. return vertexData;
  27923. };
  27924. VertexData.CreateSphere = function (options) {
  27925. var segments = options.segments || 32;
  27926. var diameterX = options.diameterX || options.diameter || 1;
  27927. var diameterY = options.diameterY || options.diameter || 1;
  27928. var diameterZ = options.diameterZ || options.diameter || 1;
  27929. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27930. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27931. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27932. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27933. var totalZRotationSteps = 2 + segments;
  27934. var totalYRotationSteps = 2 * totalZRotationSteps;
  27935. var indices = [];
  27936. var positions = [];
  27937. var normals = [];
  27938. var uvs = [];
  27939. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27940. var normalizedZ = zRotationStep / totalZRotationSteps;
  27941. var angleZ = normalizedZ * Math.PI * slice;
  27942. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27943. var normalizedY = yRotationStep / totalYRotationSteps;
  27944. var angleY = normalizedY * Math.PI * 2 * arc;
  27945. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27946. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27947. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27948. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27949. var vertex = complete.multiply(radius);
  27950. var normal = complete.divide(radius).normalize();
  27951. positions.push(vertex.x, vertex.y, vertex.z);
  27952. normals.push(normal.x, normal.y, normal.z);
  27953. uvs.push(normalizedY, normalizedZ);
  27954. }
  27955. if (zRotationStep > 0) {
  27956. var verticesCount = positions.length / 3;
  27957. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27958. indices.push((firstIndex));
  27959. indices.push((firstIndex + 1));
  27960. indices.push(firstIndex + totalYRotationSteps + 1);
  27961. indices.push((firstIndex + totalYRotationSteps + 1));
  27962. indices.push((firstIndex + 1));
  27963. indices.push((firstIndex + totalYRotationSteps + 2));
  27964. }
  27965. }
  27966. }
  27967. // Sides
  27968. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27969. // Result
  27970. var vertexData = new VertexData();
  27971. vertexData.indices = indices;
  27972. vertexData.positions = positions;
  27973. vertexData.normals = normals;
  27974. vertexData.uvs = uvs;
  27975. return vertexData;
  27976. };
  27977. // Cylinder and cone
  27978. VertexData.CreateCylinder = function (options) {
  27979. var height = options.height || 2;
  27980. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27981. var diameterBottom = options.diameterBottom || options.diameter || 1;
  27982. var tessellation = options.tessellation || 24;
  27983. var subdivisions = options.subdivisions || 1;
  27984. var hasRings = options.hasRings;
  27985. var enclose = options.enclose;
  27986. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27988. var faceUV = options.faceUV || new Array(3);
  27989. var faceColors = options.faceColors;
  27990. // default face colors and UV if undefined
  27991. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27992. var ringNb = (hasRings) ? subdivisions : 1;
  27993. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27994. var f;
  27995. for (f = 0; f < surfaceNb; f++) {
  27996. if (faceColors && faceColors[f] === undefined) {
  27997. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27998. }
  27999. }
  28000. for (f = 0; f < surfaceNb; f++) {
  28001. if (faceUV && faceUV[f] === undefined) {
  28002. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28003. }
  28004. }
  28005. var indices = [];
  28006. var positions = [];
  28007. var normals = [];
  28008. var uvs = [];
  28009. var colors = [];
  28010. var angle_step = Math.PI * 2 * arc / tessellation;
  28011. var angle;
  28012. var h;
  28013. var radius;
  28014. var tan = (diameterBottom - diameterTop) / 2 / height;
  28015. var ringVertex = BABYLON.Vector3.Zero();
  28016. var ringNormal = BABYLON.Vector3.Zero();
  28017. var ringFirstVertex = BABYLON.Vector3.Zero();
  28018. var ringFirstNormal = BABYLON.Vector3.Zero();
  28019. var quadNormal = BABYLON.Vector3.Zero();
  28020. var Y = BABYLON.Axis.Y;
  28021. // positions, normals, uvs
  28022. var i;
  28023. var j;
  28024. var r;
  28025. var ringIdx = 1;
  28026. var s = 1; // surface index
  28027. var cs = 0;
  28028. var v = 0;
  28029. for (i = 0; i <= subdivisions; i++) {
  28030. h = i / subdivisions;
  28031. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28032. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28033. for (r = 0; r < ringIdx; r++) {
  28034. if (hasRings) {
  28035. s += r;
  28036. }
  28037. if (enclose) {
  28038. s += 2 * r;
  28039. }
  28040. for (j = 0; j <= tessellation; j++) {
  28041. angle = j * angle_step;
  28042. // position
  28043. ringVertex.x = Math.cos(-angle) * radius;
  28044. ringVertex.y = -height / 2 + h * height;
  28045. ringVertex.z = Math.sin(-angle) * radius;
  28046. // normal
  28047. if (diameterTop === 0 && i === subdivisions) {
  28048. // if no top cap, reuse former normals
  28049. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28050. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28051. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28052. }
  28053. else {
  28054. ringNormal.x = ringVertex.x;
  28055. ringNormal.z = ringVertex.z;
  28056. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28057. ringNormal.normalize();
  28058. }
  28059. // keep first ring vertex values for enclose
  28060. if (j === 0) {
  28061. ringFirstVertex.copyFrom(ringVertex);
  28062. ringFirstNormal.copyFrom(ringNormal);
  28063. }
  28064. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28065. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28066. if (hasRings) {
  28067. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28068. }
  28069. else {
  28070. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28071. }
  28072. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28073. if (faceColors) {
  28074. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28075. }
  28076. }
  28077. // if enclose, add four vertices and their dedicated normals
  28078. if (arc !== 1 && enclose) {
  28079. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28080. positions.push(0, ringVertex.y, 0);
  28081. positions.push(0, ringVertex.y, 0);
  28082. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28083. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28084. quadNormal.normalize();
  28085. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28086. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28087. quadNormal.normalize();
  28088. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28089. if (hasRings) {
  28090. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28091. }
  28092. else {
  28093. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28094. }
  28095. uvs.push(faceUV[s + 1].x, v);
  28096. uvs.push(faceUV[s + 1].z, v);
  28097. if (hasRings) {
  28098. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28099. }
  28100. else {
  28101. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28102. }
  28103. uvs.push(faceUV[s + 2].x, v);
  28104. uvs.push(faceUV[s + 2].z, v);
  28105. if (faceColors) {
  28106. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28107. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28108. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28109. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28110. }
  28111. }
  28112. if (cs !== s) {
  28113. cs = s;
  28114. }
  28115. }
  28116. }
  28117. // indices
  28118. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28119. var s;
  28120. i = 0;
  28121. for (s = 0; s < subdivisions; s++) {
  28122. for (j = 0; j < tessellation; j++) {
  28123. var i0 = i * (e + 1) + j;
  28124. var i1 = (i + 1) * (e + 1) + j;
  28125. var i2 = i * (e + 1) + (j + 1);
  28126. var i3 = (i + 1) * (e + 1) + (j + 1);
  28127. indices.push(i0, i1, i2);
  28128. indices.push(i3, i2, i1);
  28129. }
  28130. if (arc !== 1 && enclose) {
  28131. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28132. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28133. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28134. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28135. }
  28136. i = (hasRings) ? (i + 2) : (i + 1);
  28137. }
  28138. // Caps
  28139. var createCylinderCap = function (isTop) {
  28140. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28141. if (radius === 0) {
  28142. return;
  28143. }
  28144. // Cap positions, normals & uvs
  28145. var angle;
  28146. var circleVector;
  28147. var i;
  28148. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28149. var c;
  28150. if (faceColors) {
  28151. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28152. }
  28153. // cap center
  28154. var vbase = positions.length / 3;
  28155. var offset = isTop ? height / 2 : -height / 2;
  28156. var center = new BABYLON.Vector3(0, offset, 0);
  28157. positions.push(center.x, center.y, center.z);
  28158. normals.push(0, isTop ? 1 : -1, 0);
  28159. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28160. if (faceColors) {
  28161. colors.push(c.r, c.g, c.b, c.a);
  28162. }
  28163. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28164. for (i = 0; i <= tessellation; i++) {
  28165. angle = Math.PI * 2 * i * arc / tessellation;
  28166. var cos = Math.cos(-angle);
  28167. var sin = Math.sin(-angle);
  28168. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28169. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28170. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28171. normals.push(0, isTop ? 1 : -1, 0);
  28172. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28173. if (faceColors) {
  28174. colors.push(c.r, c.g, c.b, c.a);
  28175. }
  28176. }
  28177. // Cap indices
  28178. for (i = 0; i < tessellation; i++) {
  28179. if (!isTop) {
  28180. indices.push(vbase);
  28181. indices.push(vbase + (i + 1));
  28182. indices.push(vbase + (i + 2));
  28183. }
  28184. else {
  28185. indices.push(vbase);
  28186. indices.push(vbase + (i + 2));
  28187. indices.push(vbase + (i + 1));
  28188. }
  28189. }
  28190. };
  28191. // add caps to geometry
  28192. createCylinderCap(false);
  28193. createCylinderCap(true);
  28194. // Sides
  28195. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28196. var vertexData = new VertexData();
  28197. vertexData.indices = indices;
  28198. vertexData.positions = positions;
  28199. vertexData.normals = normals;
  28200. vertexData.uvs = uvs;
  28201. if (faceColors) {
  28202. vertexData.colors = colors;
  28203. }
  28204. return vertexData;
  28205. };
  28206. VertexData.CreateTorus = function (options) {
  28207. var indices = [];
  28208. var positions = [];
  28209. var normals = [];
  28210. var uvs = [];
  28211. var diameter = options.diameter || 1;
  28212. var thickness = options.thickness || 0.5;
  28213. var tessellation = options.tessellation || 16;
  28214. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28215. var stride = tessellation + 1;
  28216. for (var i = 0; i <= tessellation; i++) {
  28217. var u = i / tessellation;
  28218. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28219. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28220. for (var j = 0; j <= tessellation; j++) {
  28221. var v = 1 - j / tessellation;
  28222. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28223. var dx = Math.cos(innerAngle);
  28224. var dy = Math.sin(innerAngle);
  28225. // Create a vertex.
  28226. var normal = new BABYLON.Vector3(dx, dy, 0);
  28227. var position = normal.scale(thickness / 2);
  28228. var textureCoordinate = new BABYLON.Vector2(u, v);
  28229. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28230. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28231. positions.push(position.x, position.y, position.z);
  28232. normals.push(normal.x, normal.y, normal.z);
  28233. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28234. // And create indices for two triangles.
  28235. var nextI = (i + 1) % stride;
  28236. var nextJ = (j + 1) % stride;
  28237. indices.push(i * stride + j);
  28238. indices.push(i * stride + nextJ);
  28239. indices.push(nextI * stride + j);
  28240. indices.push(i * stride + nextJ);
  28241. indices.push(nextI * stride + nextJ);
  28242. indices.push(nextI * stride + j);
  28243. }
  28244. }
  28245. // Sides
  28246. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28247. // Result
  28248. var vertexData = new VertexData();
  28249. vertexData.indices = indices;
  28250. vertexData.positions = positions;
  28251. vertexData.normals = normals;
  28252. vertexData.uvs = uvs;
  28253. return vertexData;
  28254. };
  28255. VertexData.CreateLineSystem = function (options) {
  28256. var indices = [];
  28257. var positions = [];
  28258. var lines = options.lines;
  28259. var idx = 0;
  28260. for (var l = 0; l < lines.length; l++) {
  28261. var points = lines[l];
  28262. for (var index = 0; index < points.length; index++) {
  28263. positions.push(points[index].x, points[index].y, points[index].z);
  28264. if (index > 0) {
  28265. indices.push(idx - 1);
  28266. indices.push(idx);
  28267. }
  28268. idx++;
  28269. }
  28270. }
  28271. var vertexData = new VertexData();
  28272. vertexData.indices = indices;
  28273. vertexData.positions = positions;
  28274. return vertexData;
  28275. };
  28276. VertexData.CreateDashedLines = function (options) {
  28277. var dashSize = options.dashSize || 3;
  28278. var gapSize = options.gapSize || 1;
  28279. var dashNb = options.dashNb || 200;
  28280. var points = options.points;
  28281. var positions = new Array();
  28282. var indices = new Array();
  28283. var curvect = BABYLON.Vector3.Zero();
  28284. var lg = 0;
  28285. var nb = 0;
  28286. var shft = 0;
  28287. var dashshft = 0;
  28288. var curshft = 0;
  28289. var idx = 0;
  28290. var i = 0;
  28291. for (i = 0; i < points.length - 1; i++) {
  28292. points[i + 1].subtractToRef(points[i], curvect);
  28293. lg += curvect.length();
  28294. }
  28295. shft = lg / dashNb;
  28296. dashshft = dashSize * shft / (dashSize + gapSize);
  28297. for (i = 0; i < points.length - 1; i++) {
  28298. points[i + 1].subtractToRef(points[i], curvect);
  28299. nb = Math.floor(curvect.length() / shft);
  28300. curvect.normalize();
  28301. for (var j = 0; j < nb; j++) {
  28302. curshft = shft * j;
  28303. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28304. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28305. indices.push(idx, idx + 1);
  28306. idx += 2;
  28307. }
  28308. }
  28309. // Result
  28310. var vertexData = new VertexData();
  28311. vertexData.positions = positions;
  28312. vertexData.indices = indices;
  28313. return vertexData;
  28314. };
  28315. VertexData.CreateGround = function (options) {
  28316. var indices = [];
  28317. var positions = [];
  28318. var normals = [];
  28319. var uvs = [];
  28320. var row, col;
  28321. var width = options.width || 1;
  28322. var height = options.height || 1;
  28323. var subdivisions = options.subdivisions || 1;
  28324. for (row = 0; row <= subdivisions; row++) {
  28325. for (col = 0; col <= subdivisions; col++) {
  28326. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28327. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28328. positions.push(position.x, position.y, position.z);
  28329. normals.push(normal.x, normal.y, normal.z);
  28330. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28331. }
  28332. }
  28333. for (row = 0; row < subdivisions; row++) {
  28334. for (col = 0; col < subdivisions; col++) {
  28335. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28336. indices.push(col + 1 + row * (subdivisions + 1));
  28337. indices.push(col + row * (subdivisions + 1));
  28338. indices.push(col + (row + 1) * (subdivisions + 1));
  28339. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28340. indices.push(col + row * (subdivisions + 1));
  28341. }
  28342. }
  28343. // Result
  28344. var vertexData = new VertexData();
  28345. vertexData.indices = indices;
  28346. vertexData.positions = positions;
  28347. vertexData.normals = normals;
  28348. vertexData.uvs = uvs;
  28349. return vertexData;
  28350. };
  28351. VertexData.CreateTiledGround = function (options) {
  28352. var xmin = options.xmin;
  28353. var zmin = options.zmin;
  28354. var xmax = options.xmax;
  28355. var zmax = options.zmax;
  28356. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28357. var precision = options.precision || { w: 1, h: 1 };
  28358. var indices = [];
  28359. var positions = [];
  28360. var normals = [];
  28361. var uvs = [];
  28362. var row, col, tileRow, tileCol;
  28363. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28364. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28365. precision.w = (precision.w < 1) ? 1 : precision.w;
  28366. precision.h = (precision.h < 1) ? 1 : precision.h;
  28367. var tileSize = {
  28368. 'w': (xmax - xmin) / subdivisions.w,
  28369. 'h': (zmax - zmin) / subdivisions.h
  28370. };
  28371. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28372. // Indices
  28373. var base = positions.length / 3;
  28374. var rowLength = precision.w + 1;
  28375. for (row = 0; row < precision.h; row++) {
  28376. for (col = 0; col < precision.w; col++) {
  28377. var square = [
  28378. base + col + row * rowLength,
  28379. base + (col + 1) + row * rowLength,
  28380. base + (col + 1) + (row + 1) * rowLength,
  28381. base + col + (row + 1) * rowLength
  28382. ];
  28383. indices.push(square[1]);
  28384. indices.push(square[2]);
  28385. indices.push(square[3]);
  28386. indices.push(square[0]);
  28387. indices.push(square[1]);
  28388. indices.push(square[3]);
  28389. }
  28390. }
  28391. // Position, normals and uvs
  28392. var position = BABYLON.Vector3.Zero();
  28393. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28394. for (row = 0; row <= precision.h; row++) {
  28395. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28396. for (col = 0; col <= precision.w; col++) {
  28397. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28398. position.y = 0;
  28399. positions.push(position.x, position.y, position.z);
  28400. normals.push(normal.x, normal.y, normal.z);
  28401. uvs.push(col / precision.w, row / precision.h);
  28402. }
  28403. }
  28404. }
  28405. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28406. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28407. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28408. }
  28409. }
  28410. // Result
  28411. var vertexData = new VertexData();
  28412. vertexData.indices = indices;
  28413. vertexData.positions = positions;
  28414. vertexData.normals = normals;
  28415. vertexData.uvs = uvs;
  28416. return vertexData;
  28417. };
  28418. VertexData.CreateGroundFromHeightMap = function (options) {
  28419. var indices = [];
  28420. var positions = [];
  28421. var normals = [];
  28422. var uvs = [];
  28423. var row, col;
  28424. // Vertices
  28425. for (row = 0; row <= options.subdivisions; row++) {
  28426. for (col = 0; col <= options.subdivisions; col++) {
  28427. 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));
  28428. // Compute height
  28429. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28430. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28431. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28432. var r = options.buffer[pos] / 255.0;
  28433. var g = options.buffer[pos + 1] / 255.0;
  28434. var b = options.buffer[pos + 2] / 255.0;
  28435. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28436. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28437. // Add vertex
  28438. positions.push(position.x, position.y, position.z);
  28439. normals.push(0, 0, 0);
  28440. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28441. }
  28442. }
  28443. // Indices
  28444. for (row = 0; row < options.subdivisions; row++) {
  28445. for (col = 0; col < options.subdivisions; col++) {
  28446. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28447. indices.push(col + 1 + row * (options.subdivisions + 1));
  28448. indices.push(col + row * (options.subdivisions + 1));
  28449. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28450. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28451. indices.push(col + row * (options.subdivisions + 1));
  28452. }
  28453. }
  28454. // Normals
  28455. VertexData.ComputeNormals(positions, indices, normals);
  28456. // Result
  28457. var vertexData = new VertexData();
  28458. vertexData.indices = indices;
  28459. vertexData.positions = positions;
  28460. vertexData.normals = normals;
  28461. vertexData.uvs = uvs;
  28462. return vertexData;
  28463. };
  28464. VertexData.CreatePlane = function (options) {
  28465. var indices = [];
  28466. var positions = [];
  28467. var normals = [];
  28468. var uvs = [];
  28469. var width = options.width || options.size || 1;
  28470. var height = options.height || options.size || 1;
  28471. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28472. // Vertices
  28473. var halfWidth = width / 2.0;
  28474. var halfHeight = height / 2.0;
  28475. positions.push(-halfWidth, -halfHeight, 0);
  28476. normals.push(0, 0, -1.0);
  28477. uvs.push(0.0, 0.0);
  28478. positions.push(halfWidth, -halfHeight, 0);
  28479. normals.push(0, 0, -1.0);
  28480. uvs.push(1.0, 0.0);
  28481. positions.push(halfWidth, halfHeight, 0);
  28482. normals.push(0, 0, -1.0);
  28483. uvs.push(1.0, 1.0);
  28484. positions.push(-halfWidth, halfHeight, 0);
  28485. normals.push(0, 0, -1.0);
  28486. uvs.push(0.0, 1.0);
  28487. // Indices
  28488. indices.push(0);
  28489. indices.push(1);
  28490. indices.push(2);
  28491. indices.push(0);
  28492. indices.push(2);
  28493. indices.push(3);
  28494. // Sides
  28495. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28496. // Result
  28497. var vertexData = new VertexData();
  28498. vertexData.indices = indices;
  28499. vertexData.positions = positions;
  28500. vertexData.normals = normals;
  28501. vertexData.uvs = uvs;
  28502. return vertexData;
  28503. };
  28504. VertexData.CreateDisc = function (options) {
  28505. var positions = [];
  28506. var indices = [];
  28507. var normals = [];
  28508. var uvs = [];
  28509. var radius = options.radius || 0.5;
  28510. var tessellation = options.tessellation || 64;
  28511. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28512. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28513. // positions and uvs
  28514. positions.push(0, 0, 0); // disc center first
  28515. uvs.push(0.5, 0.5);
  28516. var theta = Math.PI * 2 * arc;
  28517. var step = theta / tessellation;
  28518. for (var a = 0; a < theta; a += step) {
  28519. var x = Math.cos(a);
  28520. var y = Math.sin(a);
  28521. var u = (x + 1) / 2;
  28522. var v = (1 - y) / 2;
  28523. positions.push(radius * x, radius * y, 0);
  28524. uvs.push(u, v);
  28525. }
  28526. if (arc === 1) {
  28527. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28528. uvs.push(uvs[2], uvs[3]);
  28529. }
  28530. //indices
  28531. var vertexNb = positions.length / 3;
  28532. for (var i = 1; i < vertexNb - 1; i++) {
  28533. indices.push(i + 1, 0, i);
  28534. }
  28535. // result
  28536. VertexData.ComputeNormals(positions, indices, normals);
  28537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28538. var vertexData = new VertexData();
  28539. vertexData.indices = indices;
  28540. vertexData.positions = positions;
  28541. vertexData.normals = normals;
  28542. vertexData.uvs = uvs;
  28543. return vertexData;
  28544. };
  28545. VertexData.CreateIcoSphere = function (options) {
  28546. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28547. var radius = options.radius || 1;
  28548. var flat = (options.flat === undefined) ? true : options.flat;
  28549. var subdivisions = options.subdivisions || 4;
  28550. var radiusX = options.radiusX || radius;
  28551. var radiusY = options.radiusY || radius;
  28552. var radiusZ = options.radiusZ || radius;
  28553. var t = (1 + Math.sqrt(5)) / 2;
  28554. // 12 vertex x,y,z
  28555. var ico_vertices = [
  28556. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28557. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28558. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28559. ];
  28560. // index of 3 vertex makes a face of icopshere
  28561. var ico_indices = [
  28562. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28563. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28564. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28565. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28566. ];
  28567. // vertex for uv have aliased position, not for UV
  28568. var vertices_unalias_id = [
  28569. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28570. // vertex alias
  28571. 0,
  28572. 2,
  28573. 3,
  28574. 3,
  28575. 3,
  28576. 4,
  28577. 7,
  28578. 8,
  28579. 9,
  28580. 9,
  28581. 10,
  28582. 11 // 23: B + 12
  28583. ];
  28584. // uv as integer step (not pixels !)
  28585. var ico_vertexuv = [
  28586. 5, 1, 3, 1, 6, 4, 0, 0,
  28587. 5, 3, 4, 2, 2, 2, 4, 0,
  28588. 2, 0, 1, 1, 6, 0, 6, 2,
  28589. // vertex alias (for same vertex on different faces)
  28590. 0, 4,
  28591. 3, 3,
  28592. 4, 4,
  28593. 3, 1,
  28594. 4, 2,
  28595. 4, 4,
  28596. 0, 2,
  28597. 1, 1,
  28598. 2, 2,
  28599. 3, 3,
  28600. 1, 3,
  28601. 2, 4 // 23: B + 12
  28602. ];
  28603. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28604. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28605. // First island of uv mapping
  28606. // v = 4h 3+ 2
  28607. // v = 3h 9+ 4
  28608. // v = 2h 9+ 5 B
  28609. // v = 1h 9 1 0
  28610. // v = 0h 3 8 7 A
  28611. // u = 0 1 2 3 4 5 6 *a
  28612. // Second island of uv mapping
  28613. // v = 4h 0+ B+ 4+
  28614. // v = 3h A+ 2+
  28615. // v = 2h 7+ 6 3+
  28616. // v = 1h 8+ 3+
  28617. // v = 0h
  28618. // u = 0 1 2 3 4 5 6 *a
  28619. // Face layout on texture UV mapping
  28620. // ============
  28621. // \ 4 /\ 16 / ======
  28622. // \ / \ / /\ 11 /
  28623. // \/ 7 \/ / \ /
  28624. // ======= / 10 \/
  28625. // /\ 17 /\ =======
  28626. // / \ / \ \ 15 /\
  28627. // / 8 \/ 12 \ \ / \
  28628. // ============ \/ 6 \
  28629. // \ 18 /\ ============
  28630. // \ / \ \ 5 /\ 0 /
  28631. // \/ 13 \ \ / \ /
  28632. // ======= \/ 1 \/
  28633. // =============
  28634. // /\ 19 /\ 2 /\
  28635. // / \ / \ / \
  28636. // / 14 \/ 9 \/ 3 \
  28637. // ===================
  28638. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28639. var ustep = 138 / 1024;
  28640. var vstep = 239 / 1024;
  28641. var uoffset = 60 / 1024;
  28642. var voffset = 26 / 1024;
  28643. // Second island should have margin, not to touch the first island
  28644. // avoid any borderline artefact in pixel rounding
  28645. var island_u_offset = -40 / 1024;
  28646. var island_v_offset = +20 / 1024;
  28647. // face is either island 0 or 1 :
  28648. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28649. var island = [
  28650. 0, 0, 0, 0, 1,
  28651. 0, 0, 1, 1, 0,
  28652. 0, 0, 1, 1, 0,
  28653. 0, 1, 1, 1, 0 // 15 - 19
  28654. ];
  28655. var indices = [];
  28656. var positions = [];
  28657. var normals = [];
  28658. var uvs = [];
  28659. var current_indice = 0;
  28660. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28661. var face_vertex_pos = new Array(3);
  28662. var face_vertex_uv = new Array(3);
  28663. var v012;
  28664. for (v012 = 0; v012 < 3; v012++) {
  28665. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28666. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28667. }
  28668. // create all with normals
  28669. for (var face = 0; face < 20; face++) {
  28670. // 3 vertex per face
  28671. for (v012 = 0; v012 < 3; v012++) {
  28672. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28673. var v_id = ico_indices[3 * face + v012];
  28674. // vertex have 3D position (x,y,z)
  28675. 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]);
  28676. // Normalize to get normal, then scale to radius
  28677. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28678. // uv Coordinates from vertex ID
  28679. 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);
  28680. }
  28681. // Subdivide the face (interpolate pos, norm, uv)
  28682. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28683. // - norm is linear interpolation of vertex corner normal
  28684. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28685. // - uv is linear interpolation
  28686. //
  28687. // Topology is as below for sub-divide by 2
  28688. // vertex shown as v0,v1,v2
  28689. // interp index is i1 to progress in range [v0,v1[
  28690. // interp index is i2 to progress in range [v0,v2[
  28691. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28692. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28693. //
  28694. //
  28695. // i2 v2
  28696. // ^ ^
  28697. // / / \
  28698. // / / \
  28699. // / / \
  28700. // / / (0,1) \
  28701. // / #---------\
  28702. // / / \ (0,0)'/ \
  28703. // / / \ / \
  28704. // / / \ / \
  28705. // / / (0,0) \ / (1,0) \
  28706. // / #---------#---------\
  28707. // v0 v1
  28708. //
  28709. // --------------------> i1
  28710. //
  28711. // interp of (i1,i2):
  28712. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28713. // along i1 : lerp(x0,x1, i1/(S-i2))
  28714. //
  28715. // centroid of triangle is needed to get help normal computation
  28716. // (c1,c2) are used for centroid location
  28717. var interp_vertex = function (i1, i2, c1, c2) {
  28718. // vertex is interpolated from
  28719. // - face_vertex_pos[0..2]
  28720. // - face_vertex_uv[0..2]
  28721. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28722. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28723. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28724. pos_interp.normalize();
  28725. var vertex_normal;
  28726. if (flat) {
  28727. // in flat mode, recalculate normal as face centroid normal
  28728. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28729. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28730. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28731. }
  28732. else {
  28733. // in smooth mode, recalculate normal from each single vertex position
  28734. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28735. }
  28736. // Vertex normal need correction due to X,Y,Z radius scaling
  28737. vertex_normal.x /= radiusX;
  28738. vertex_normal.y /= radiusY;
  28739. vertex_normal.z /= radiusZ;
  28740. vertex_normal.normalize();
  28741. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28742. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28743. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28744. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28745. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28746. uvs.push(uv_interp.x, uv_interp.y);
  28747. // push each vertex has member of a face
  28748. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28749. indices.push(current_indice);
  28750. current_indice++;
  28751. };
  28752. for (var i2 = 0; i2 < subdivisions; i2++) {
  28753. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28754. // face : (i1,i2) for /\ :
  28755. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28756. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28757. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28758. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28759. if (i1 + i2 + 1 < subdivisions) {
  28760. // face : (i1,i2)' for \/ :
  28761. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28762. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28763. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28764. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28765. }
  28766. }
  28767. }
  28768. }
  28769. // Sides
  28770. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28771. // Result
  28772. var vertexData = new VertexData();
  28773. vertexData.indices = indices;
  28774. vertexData.positions = positions;
  28775. vertexData.normals = normals;
  28776. vertexData.uvs = uvs;
  28777. return vertexData;
  28778. };
  28779. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28780. VertexData.CreatePolyhedron = function (options) {
  28781. // provided polyhedron types :
  28782. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28783. // 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)
  28784. var polyhedra = [];
  28785. 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]] };
  28786. 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]] };
  28787. polyhedra[2] = {
  28788. 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]],
  28789. 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]]
  28790. };
  28791. polyhedra[3] = {
  28792. 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]],
  28793. 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]]
  28794. };
  28795. polyhedra[4] = {
  28796. 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]],
  28797. 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]]
  28798. };
  28799. 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]] };
  28800. 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]] };
  28801. 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]] };
  28802. 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]] };
  28803. 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]] };
  28804. 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]] };
  28805. 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]] };
  28806. 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]] };
  28807. 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]] };
  28808. polyhedra[14] = {
  28809. 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]],
  28810. 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]]
  28811. };
  28812. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28813. var size = options.size;
  28814. var sizeX = options.sizeX || size || 1;
  28815. var sizeY = options.sizeY || size || 1;
  28816. var sizeZ = options.sizeZ || size || 1;
  28817. var data = options.custom || polyhedra[type];
  28818. var nbfaces = data.face.length;
  28819. var faceUV = options.faceUV || new Array(nbfaces);
  28820. var faceColors = options.faceColors;
  28821. var flat = (options.flat === undefined) ? true : options.flat;
  28822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28823. var positions = [];
  28824. var indices = [];
  28825. var normals = [];
  28826. var uvs = [];
  28827. var colors = [];
  28828. var index = 0;
  28829. var faceIdx = 0; // face cursor in the array "indexes"
  28830. var indexes = [];
  28831. var i = 0;
  28832. var f = 0;
  28833. var u, v, ang, x, y, tmp;
  28834. // default face colors and UV if undefined
  28835. if (flat) {
  28836. for (f = 0; f < nbfaces; f++) {
  28837. if (faceColors && faceColors[f] === undefined) {
  28838. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28839. }
  28840. if (faceUV && faceUV[f] === undefined) {
  28841. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28842. }
  28843. }
  28844. }
  28845. if (!flat) {
  28846. for (i = 0; i < data.vertex.length; i++) {
  28847. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28848. uvs.push(0, 0);
  28849. }
  28850. for (f = 0; f < nbfaces; f++) {
  28851. for (i = 0; i < data.face[f].length - 2; i++) {
  28852. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28853. }
  28854. }
  28855. }
  28856. else {
  28857. for (f = 0; f < nbfaces; f++) {
  28858. var fl = data.face[f].length; // number of vertices of the current face
  28859. ang = 2 * Math.PI / fl;
  28860. x = 0.5 * Math.tan(ang / 2);
  28861. y = 0.5;
  28862. // positions, uvs, colors
  28863. for (i = 0; i < fl; i++) {
  28864. // positions
  28865. 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);
  28866. indexes.push(index);
  28867. index++;
  28868. // uvs
  28869. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28870. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28871. uvs.push(u, v);
  28872. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28873. y = x * Math.sin(ang) + y * Math.cos(ang);
  28874. x = tmp;
  28875. // colors
  28876. if (faceColors) {
  28877. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28878. }
  28879. }
  28880. // indices from indexes
  28881. for (i = 0; i < fl - 2; i++) {
  28882. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28883. }
  28884. faceIdx += fl;
  28885. }
  28886. }
  28887. VertexData.ComputeNormals(positions, indices, normals);
  28888. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28889. var vertexData = new VertexData();
  28890. vertexData.positions = positions;
  28891. vertexData.indices = indices;
  28892. vertexData.normals = normals;
  28893. vertexData.uvs = uvs;
  28894. if (faceColors && flat) {
  28895. vertexData.colors = colors;
  28896. }
  28897. return vertexData;
  28898. };
  28899. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28900. VertexData.CreateTorusKnot = function (options) {
  28901. var indices = [];
  28902. var positions = [];
  28903. var normals = [];
  28904. var uvs = [];
  28905. var radius = options.radius || 2;
  28906. var tube = options.tube || 0.5;
  28907. var radialSegments = options.radialSegments || 32;
  28908. var tubularSegments = options.tubularSegments || 32;
  28909. var p = options.p || 2;
  28910. var q = options.q || 3;
  28911. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28912. // Helper
  28913. var getPos = function (angle) {
  28914. var cu = Math.cos(angle);
  28915. var su = Math.sin(angle);
  28916. var quOverP = q / p * angle;
  28917. var cs = Math.cos(quOverP);
  28918. var tx = radius * (2 + cs) * 0.5 * cu;
  28919. var ty = radius * (2 + cs) * su * 0.5;
  28920. var tz = radius * Math.sin(quOverP) * 0.5;
  28921. return new BABYLON.Vector3(tx, ty, tz);
  28922. };
  28923. // Vertices
  28924. var i;
  28925. var j;
  28926. for (i = 0; i <= radialSegments; i++) {
  28927. var modI = i % radialSegments;
  28928. var u = modI / radialSegments * 2 * p * Math.PI;
  28929. var p1 = getPos(u);
  28930. var p2 = getPos(u + 0.01);
  28931. var tang = p2.subtract(p1);
  28932. var n = p2.add(p1);
  28933. var bitan = BABYLON.Vector3.Cross(tang, n);
  28934. n = BABYLON.Vector3.Cross(bitan, tang);
  28935. bitan.normalize();
  28936. n.normalize();
  28937. for (j = 0; j < tubularSegments; j++) {
  28938. var modJ = j % tubularSegments;
  28939. var v = modJ / tubularSegments * 2 * Math.PI;
  28940. var cx = -tube * Math.cos(v);
  28941. var cy = tube * Math.sin(v);
  28942. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28943. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28944. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28945. uvs.push(i / radialSegments);
  28946. uvs.push(j / tubularSegments);
  28947. }
  28948. }
  28949. for (i = 0; i < radialSegments; i++) {
  28950. for (j = 0; j < tubularSegments; j++) {
  28951. var jNext = (j + 1) % tubularSegments;
  28952. var a = i * tubularSegments + j;
  28953. var b = (i + 1) * tubularSegments + j;
  28954. var c = (i + 1) * tubularSegments + jNext;
  28955. var d = i * tubularSegments + jNext;
  28956. indices.push(d);
  28957. indices.push(b);
  28958. indices.push(a);
  28959. indices.push(d);
  28960. indices.push(c);
  28961. indices.push(b);
  28962. }
  28963. }
  28964. // Normals
  28965. VertexData.ComputeNormals(positions, indices, normals);
  28966. // Sides
  28967. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28968. // Result
  28969. var vertexData = new VertexData();
  28970. vertexData.indices = indices;
  28971. vertexData.positions = positions;
  28972. vertexData.normals = normals;
  28973. vertexData.uvs = uvs;
  28974. return vertexData;
  28975. };
  28976. // Tools
  28977. /**
  28978. * @param {any} - positions (number[] or Float32Array)
  28979. * @param {any} - indices (number[] or Uint16Array)
  28980. * @param {any} - normals (number[] or Float32Array)
  28981. */
  28982. VertexData.ComputeNormals = function (positions, indices, normals) {
  28983. var index = 0;
  28984. var p1p2x = 0.0;
  28985. var p1p2y = 0.0;
  28986. var p1p2z = 0.0;
  28987. var p3p2x = 0.0;
  28988. var p3p2y = 0.0;
  28989. var p3p2z = 0.0;
  28990. var faceNormalx = 0.0;
  28991. var faceNormaly = 0.0;
  28992. var faceNormalz = 0.0;
  28993. var length = 0.0;
  28994. var i1 = 0;
  28995. var i2 = 0;
  28996. var i3 = 0;
  28997. for (index = 0; index < positions.length; index++) {
  28998. normals[index] = 0.0;
  28999. }
  29000. // indice triplet = 1 face
  29001. var nbFaces = indices.length / 3;
  29002. for (index = 0; index < nbFaces; index++) {
  29003. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29004. i2 = indices[index * 3 + 1];
  29005. i3 = indices[index * 3 + 2];
  29006. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29007. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29008. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29009. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29010. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29011. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29012. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29013. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29014. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29015. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29016. length = (length === 0) ? 1.0 : length;
  29017. faceNormalx /= length; // normalize this normal
  29018. faceNormaly /= length;
  29019. faceNormalz /= length;
  29020. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29021. normals[i1 * 3 + 1] += faceNormaly;
  29022. normals[i1 * 3 + 2] += faceNormalz;
  29023. normals[i2 * 3] += faceNormalx;
  29024. normals[i2 * 3 + 1] += faceNormaly;
  29025. normals[i2 * 3 + 2] += faceNormalz;
  29026. normals[i3 * 3] += faceNormalx;
  29027. normals[i3 * 3 + 1] += faceNormaly;
  29028. normals[i3 * 3 + 2] += faceNormalz;
  29029. }
  29030. // last normalization of each normal
  29031. for (index = 0; index < normals.length / 3; index++) {
  29032. faceNormalx = normals[index * 3];
  29033. faceNormaly = normals[index * 3 + 1];
  29034. faceNormalz = normals[index * 3 + 2];
  29035. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29036. length = (length === 0) ? 1.0 : length;
  29037. faceNormalx /= length;
  29038. faceNormaly /= length;
  29039. faceNormalz /= length;
  29040. normals[index * 3] = faceNormalx;
  29041. normals[index * 3 + 1] = faceNormaly;
  29042. normals[index * 3 + 2] = faceNormalz;
  29043. }
  29044. };
  29045. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29046. var li = indices.length;
  29047. var ln = normals.length;
  29048. var i;
  29049. var n;
  29050. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29051. switch (sideOrientation) {
  29052. case BABYLON.Mesh.FRONTSIDE:
  29053. // nothing changed
  29054. break;
  29055. case BABYLON.Mesh.BACKSIDE:
  29056. var tmp;
  29057. // indices
  29058. for (i = 0; i < li; i += 3) {
  29059. tmp = indices[i];
  29060. indices[i] = indices[i + 2];
  29061. indices[i + 2] = tmp;
  29062. }
  29063. // normals
  29064. for (n = 0; n < ln; n++) {
  29065. normals[n] = -normals[n];
  29066. }
  29067. break;
  29068. case BABYLON.Mesh.DOUBLESIDE:
  29069. // positions
  29070. var lp = positions.length;
  29071. var l = lp / 3;
  29072. for (var p = 0; p < lp; p++) {
  29073. positions[lp + p] = positions[p];
  29074. }
  29075. // indices
  29076. for (i = 0; i < li; i += 3) {
  29077. indices[i + li] = indices[i + 2] + l;
  29078. indices[i + 1 + li] = indices[i + 1] + l;
  29079. indices[i + 2 + li] = indices[i] + l;
  29080. }
  29081. // normals
  29082. for (n = 0; n < ln; n++) {
  29083. normals[ln + n] = -normals[n];
  29084. }
  29085. // uvs
  29086. var lu = uvs.length;
  29087. for (var u = 0; u < lu; u++) {
  29088. uvs[u + lu] = uvs[u];
  29089. }
  29090. break;
  29091. }
  29092. };
  29093. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29094. var vertexData = new VertexData();
  29095. // positions
  29096. var positions = parsedVertexData.positions;
  29097. if (positions) {
  29098. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29099. }
  29100. // normals
  29101. var normals = parsedVertexData.normals;
  29102. if (normals) {
  29103. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29104. }
  29105. // uvs
  29106. var uvs = parsedVertexData.uvs;
  29107. if (uvs) {
  29108. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29109. }
  29110. // uv2s
  29111. var uv2s = parsedVertexData.uv2s;
  29112. if (uv2s) {
  29113. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29114. }
  29115. // uv3s
  29116. var uv3s = parsedVertexData.uv3s;
  29117. if (uv3s) {
  29118. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29119. }
  29120. // uv4s
  29121. var uv4s = parsedVertexData.uv4s;
  29122. if (uv4s) {
  29123. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29124. }
  29125. // uv5s
  29126. var uv5s = parsedVertexData.uv5s;
  29127. if (uv5s) {
  29128. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29129. }
  29130. // uv6s
  29131. var uv6s = parsedVertexData.uv6s;
  29132. if (uv6s) {
  29133. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29134. }
  29135. // colors
  29136. var colors = parsedVertexData.colors;
  29137. if (colors) {
  29138. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29139. }
  29140. // matricesIndices
  29141. var matricesIndices = parsedVertexData.matricesIndices;
  29142. if (matricesIndices) {
  29143. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29144. }
  29145. // matricesWeights
  29146. var matricesWeights = parsedVertexData.matricesWeights;
  29147. if (matricesWeights) {
  29148. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29149. }
  29150. // indices
  29151. var indices = parsedVertexData.indices;
  29152. if (indices) {
  29153. vertexData.indices = indices;
  29154. }
  29155. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29156. };
  29157. return VertexData;
  29158. }());
  29159. BABYLON.VertexData = VertexData;
  29160. })(BABYLON || (BABYLON = {}));
  29161. var BABYLON;
  29162. (function (BABYLON) {
  29163. var Tags = (function () {
  29164. function Tags() {
  29165. }
  29166. Tags.EnableFor = function (obj) {
  29167. obj._tags = obj._tags || {};
  29168. obj.hasTags = function () {
  29169. return Tags.HasTags(obj);
  29170. };
  29171. obj.addTags = function (tagsString) {
  29172. return Tags.AddTagsTo(obj, tagsString);
  29173. };
  29174. obj.removeTags = function (tagsString) {
  29175. return Tags.RemoveTagsFrom(obj, tagsString);
  29176. };
  29177. obj.matchesTagsQuery = function (tagsQuery) {
  29178. return Tags.MatchesQuery(obj, tagsQuery);
  29179. };
  29180. };
  29181. Tags.DisableFor = function (obj) {
  29182. delete obj._tags;
  29183. delete obj.hasTags;
  29184. delete obj.addTags;
  29185. delete obj.removeTags;
  29186. delete obj.matchesTagsQuery;
  29187. };
  29188. Tags.HasTags = function (obj) {
  29189. if (!obj._tags) {
  29190. return false;
  29191. }
  29192. return !BABYLON.Tools.IsEmpty(obj._tags);
  29193. };
  29194. Tags.GetTags = function (obj, asString) {
  29195. if (asString === void 0) { asString = true; }
  29196. if (!obj._tags) {
  29197. return null;
  29198. }
  29199. if (asString) {
  29200. var tagsArray = [];
  29201. for (var tag in obj._tags) {
  29202. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29203. tagsArray.push(tag);
  29204. }
  29205. }
  29206. return tagsArray.join(" ");
  29207. }
  29208. else {
  29209. return obj._tags;
  29210. }
  29211. };
  29212. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29213. // a tag cannot start with '||', '&&', and '!'
  29214. // it cannot contain whitespaces
  29215. Tags.AddTagsTo = function (obj, tagsString) {
  29216. if (!tagsString) {
  29217. return;
  29218. }
  29219. if (typeof tagsString !== "string") {
  29220. return;
  29221. }
  29222. var tags = tagsString.split(" ");
  29223. for (var t in tags) {
  29224. Tags._AddTagTo(obj, tags[t]);
  29225. }
  29226. };
  29227. Tags._AddTagTo = function (obj, tag) {
  29228. tag = tag.trim();
  29229. if (tag === "" || tag === "true" || tag === "false") {
  29230. return;
  29231. }
  29232. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29233. return;
  29234. }
  29235. Tags.EnableFor(obj);
  29236. obj._tags[tag] = true;
  29237. };
  29238. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29239. if (!Tags.HasTags(obj)) {
  29240. return;
  29241. }
  29242. var tags = tagsString.split(" ");
  29243. for (var t in tags) {
  29244. Tags._RemoveTagFrom(obj, tags[t]);
  29245. }
  29246. };
  29247. Tags._RemoveTagFrom = function (obj, tag) {
  29248. delete obj._tags[tag];
  29249. };
  29250. Tags.MatchesQuery = function (obj, tagsQuery) {
  29251. if (tagsQuery === undefined) {
  29252. return true;
  29253. }
  29254. if (tagsQuery === "") {
  29255. return Tags.HasTags(obj);
  29256. }
  29257. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29258. };
  29259. return Tags;
  29260. }());
  29261. BABYLON.Tags = Tags;
  29262. })(BABYLON || (BABYLON = {}));
  29263. var BABYLON;
  29264. (function (BABYLON) {
  29265. var Internals;
  29266. (function (Internals) {
  29267. var AndOrNotEvaluator = (function () {
  29268. function AndOrNotEvaluator() {
  29269. }
  29270. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29271. if (!query.match(/\([^\(\)]*\)/g)) {
  29272. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29273. }
  29274. else {
  29275. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29276. // remove parenthesis
  29277. r = r.slice(1, r.length - 1);
  29278. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29279. });
  29280. }
  29281. if (query === "true") {
  29282. return true;
  29283. }
  29284. if (query === "false") {
  29285. return false;
  29286. }
  29287. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29288. };
  29289. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29290. evaluateCallback = evaluateCallback || (function (r) {
  29291. return r === "true" ? true : false;
  29292. });
  29293. var result;
  29294. var or = parenthesisContent.split("||");
  29295. for (var i in or) {
  29296. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29297. var and = ori.split("&&");
  29298. if (and.length > 1) {
  29299. for (var j = 0; j < and.length; ++j) {
  29300. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29301. if (andj !== "true" && andj !== "false") {
  29302. if (andj[0] === "!") {
  29303. result = !evaluateCallback(andj.substring(1));
  29304. }
  29305. else {
  29306. result = evaluateCallback(andj);
  29307. }
  29308. }
  29309. else {
  29310. result = andj === "true" ? true : false;
  29311. }
  29312. if (!result) {
  29313. ori = "false";
  29314. break;
  29315. }
  29316. }
  29317. }
  29318. if (result || ori === "true") {
  29319. result = true;
  29320. break;
  29321. }
  29322. // result equals false (or undefined)
  29323. if (ori !== "true" && ori !== "false") {
  29324. if (ori[0] === "!") {
  29325. result = !evaluateCallback(ori.substring(1));
  29326. }
  29327. else {
  29328. result = evaluateCallback(ori);
  29329. }
  29330. }
  29331. else {
  29332. result = ori === "true" ? true : false;
  29333. }
  29334. }
  29335. // the whole parenthesis scope is replaced by 'true' or 'false'
  29336. return result ? "true" : "false";
  29337. };
  29338. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29339. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29340. // remove whitespaces
  29341. r = r.replace(/[\s]/g, function () { return ""; });
  29342. return r.length % 2 ? "!" : "";
  29343. });
  29344. booleanString = booleanString.trim();
  29345. if (booleanString === "!true") {
  29346. booleanString = "false";
  29347. }
  29348. else if (booleanString === "!false") {
  29349. booleanString = "true";
  29350. }
  29351. return booleanString;
  29352. };
  29353. return AndOrNotEvaluator;
  29354. }());
  29355. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29356. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29357. })(BABYLON || (BABYLON = {}));
  29358. var BABYLON;
  29359. (function (BABYLON) {
  29360. var PostProcessRenderPass = (function () {
  29361. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29362. this._enabled = true;
  29363. this._refCount = 0;
  29364. this._name = name;
  29365. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29366. this.setRenderList(renderList);
  29367. this._renderTexture.onBeforeRender = beforeRender;
  29368. this._renderTexture.onAfterRender = afterRender;
  29369. this._scene = scene;
  29370. this._renderList = renderList;
  29371. }
  29372. // private
  29373. PostProcessRenderPass.prototype._incRefCount = function () {
  29374. if (this._refCount === 0) {
  29375. this._scene.customRenderTargets.push(this._renderTexture);
  29376. }
  29377. return ++this._refCount;
  29378. };
  29379. PostProcessRenderPass.prototype._decRefCount = function () {
  29380. this._refCount--;
  29381. if (this._refCount <= 0) {
  29382. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29383. }
  29384. return this._refCount;
  29385. };
  29386. PostProcessRenderPass.prototype._update = function () {
  29387. this.setRenderList(this._renderList);
  29388. };
  29389. // public
  29390. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29391. this._renderTexture.renderList = renderList;
  29392. };
  29393. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29394. return this._renderTexture;
  29395. };
  29396. return PostProcessRenderPass;
  29397. }());
  29398. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29399. })(BABYLON || (BABYLON = {}));
  29400. var BABYLON;
  29401. (function (BABYLON) {
  29402. var PostProcessRenderEffect = (function () {
  29403. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29404. this._engine = engine;
  29405. this._name = name;
  29406. this._singleInstance = singleInstance || true;
  29407. this._getPostProcess = getPostProcess;
  29408. this._cameras = [];
  29409. this._indicesForCamera = [];
  29410. this._postProcesses = {};
  29411. this._renderPasses = {};
  29412. this._renderEffectAsPasses = {};
  29413. }
  29414. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29415. get: function () {
  29416. for (var index in this._postProcesses) {
  29417. if (!this._postProcesses[index].isSupported) {
  29418. return false;
  29419. }
  29420. }
  29421. return true;
  29422. },
  29423. enumerable: true,
  29424. configurable: true
  29425. });
  29426. PostProcessRenderEffect.prototype._update = function () {
  29427. for (var renderPassName in this._renderPasses) {
  29428. this._renderPasses[renderPassName]._update();
  29429. }
  29430. };
  29431. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29432. this._renderPasses[renderPass._name] = renderPass;
  29433. this._linkParameters();
  29434. };
  29435. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29436. delete this._renderPasses[renderPass._name];
  29437. this._linkParameters();
  29438. };
  29439. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29440. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29441. this._linkParameters();
  29442. };
  29443. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29444. for (var renderPassName in this._renderPasses) {
  29445. if (renderPassName === passName) {
  29446. return this._renderPasses[passName];
  29447. }
  29448. }
  29449. };
  29450. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29451. this._renderPasses = {};
  29452. this._linkParameters();
  29453. };
  29454. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29455. var cameraKey;
  29456. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29457. for (var i = 0; i < _cam.length; i++) {
  29458. var camera = _cam[i];
  29459. var cameraName = camera.name;
  29460. if (this._singleInstance) {
  29461. cameraKey = 0;
  29462. }
  29463. else {
  29464. cameraKey = cameraName;
  29465. }
  29466. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29467. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29468. if (!this._indicesForCamera[cameraName]) {
  29469. this._indicesForCamera[cameraName] = [];
  29470. }
  29471. this._indicesForCamera[cameraName].push(index);
  29472. if (this._cameras.indexOf(camera) === -1) {
  29473. this._cameras[cameraName] = camera;
  29474. }
  29475. for (var passName in this._renderPasses) {
  29476. this._renderPasses[passName]._incRefCount();
  29477. }
  29478. }
  29479. this._linkParameters();
  29480. };
  29481. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29482. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29483. for (var i = 0; i < _cam.length; i++) {
  29484. var camera = _cam[i];
  29485. var cameraName = camera.name;
  29486. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29487. var index = this._cameras.indexOf(cameraName);
  29488. this._indicesForCamera.splice(index, 1);
  29489. this._cameras.splice(index, 1);
  29490. for (var passName in this._renderPasses) {
  29491. this._renderPasses[passName]._decRefCount();
  29492. }
  29493. }
  29494. };
  29495. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29496. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29497. for (var i = 0; i < _cam.length; i++) {
  29498. var camera = _cam[i];
  29499. var cameraName = camera.name;
  29500. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29501. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29502. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29503. }
  29504. }
  29505. for (var passName in this._renderPasses) {
  29506. this._renderPasses[passName]._incRefCount();
  29507. }
  29508. }
  29509. };
  29510. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29511. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29512. for (var i = 0; i < _cam.length; i++) {
  29513. var camera = _cam[i];
  29514. var cameraName = camera.Name;
  29515. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29516. for (var passName in this._renderPasses) {
  29517. this._renderPasses[passName]._decRefCount();
  29518. }
  29519. }
  29520. };
  29521. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29522. if (this._singleInstance) {
  29523. return this._postProcesses[0];
  29524. }
  29525. else {
  29526. return this._postProcesses[camera.name];
  29527. }
  29528. };
  29529. PostProcessRenderEffect.prototype._linkParameters = function () {
  29530. var _this = this;
  29531. for (var index in this._postProcesses) {
  29532. if (this.applyParameters) {
  29533. this.applyParameters(this._postProcesses[index]);
  29534. }
  29535. this._postProcesses[index].onBeforeRender = function (effect) {
  29536. _this._linkTextures(effect);
  29537. };
  29538. }
  29539. };
  29540. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29541. for (var renderPassName in this._renderPasses) {
  29542. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29543. }
  29544. for (var renderEffectName in this._renderEffectAsPasses) {
  29545. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29546. }
  29547. };
  29548. return PostProcessRenderEffect;
  29549. }());
  29550. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29551. })(BABYLON || (BABYLON = {}));
  29552. var BABYLON;
  29553. (function (BABYLON) {
  29554. var PostProcessRenderPipeline = (function () {
  29555. function PostProcessRenderPipeline(engine, name) {
  29556. this._engine = engine;
  29557. this._name = name;
  29558. this._renderEffects = {};
  29559. this._renderEffectsForIsolatedPass = {};
  29560. this._cameras = [];
  29561. }
  29562. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29563. get: function () {
  29564. for (var renderEffectName in this._renderEffects) {
  29565. if (!this._renderEffects[renderEffectName].isSupported) {
  29566. return false;
  29567. }
  29568. }
  29569. return true;
  29570. },
  29571. enumerable: true,
  29572. configurable: true
  29573. });
  29574. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29575. this._renderEffects[renderEffect._name] = renderEffect;
  29576. };
  29577. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29578. var renderEffects = this._renderEffects[renderEffectName];
  29579. if (!renderEffects) {
  29580. return;
  29581. }
  29582. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29583. };
  29584. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29585. var renderEffects = this._renderEffects[renderEffectName];
  29586. if (!renderEffects) {
  29587. return;
  29588. }
  29589. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29590. };
  29591. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29593. var indicesToDelete = [];
  29594. var i;
  29595. for (i = 0; i < _cam.length; i++) {
  29596. var camera = _cam[i];
  29597. var cameraName = camera.name;
  29598. if (this._cameras.indexOf(camera) === -1) {
  29599. this._cameras[cameraName] = camera;
  29600. }
  29601. else if (unique) {
  29602. indicesToDelete.push(i);
  29603. }
  29604. }
  29605. for (i = 0; i < indicesToDelete.length; i++) {
  29606. cameras.splice(indicesToDelete[i], 1);
  29607. }
  29608. for (var renderEffectName in this._renderEffects) {
  29609. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29610. }
  29611. };
  29612. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29613. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29614. for (var renderEffectName in this._renderEffects) {
  29615. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29616. }
  29617. for (var i = 0; i < _cam.length; i++) {
  29618. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29619. }
  29620. };
  29621. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29622. var _this = this;
  29623. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29624. var pass = null;
  29625. var renderEffectName;
  29626. for (renderEffectName in this._renderEffects) {
  29627. pass = this._renderEffects[renderEffectName].getPass(passName);
  29628. if (pass != null) {
  29629. break;
  29630. }
  29631. }
  29632. if (pass === null) {
  29633. return;
  29634. }
  29635. for (renderEffectName in this._renderEffects) {
  29636. this._renderEffects[renderEffectName]._disable(_cam);
  29637. }
  29638. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29639. for (var i = 0; i < _cam.length; i++) {
  29640. var camera = _cam[i];
  29641. var cameraName = camera.name;
  29642. 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); });
  29643. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29644. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29645. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29646. }
  29647. };
  29648. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29649. var _this = this;
  29650. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29651. for (var i = 0; i < _cam.length; i++) {
  29652. var camera = _cam[i];
  29653. var cameraName = camera.name;
  29654. 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); });
  29655. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29656. }
  29657. for (var renderEffectName in this._renderEffects) {
  29658. this._renderEffects[renderEffectName]._enable(_cam);
  29659. }
  29660. };
  29661. PostProcessRenderPipeline.prototype._update = function () {
  29662. for (var renderEffectName in this._renderEffects) {
  29663. this._renderEffects[renderEffectName]._update();
  29664. }
  29665. for (var i = 0; i < this._cameras.length; i++) {
  29666. var cameraName = this._cameras[i].name;
  29667. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29668. this._renderEffectsForIsolatedPass[cameraName]._update();
  29669. }
  29670. }
  29671. };
  29672. PostProcessRenderPipeline.prototype.dispose = function () {
  29673. // Must be implemented by children
  29674. };
  29675. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29676. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29677. return PostProcessRenderPipeline;
  29678. }());
  29679. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29680. })(BABYLON || (BABYLON = {}));
  29681. var BABYLON;
  29682. (function (BABYLON) {
  29683. var PostProcessRenderPipelineManager = (function () {
  29684. function PostProcessRenderPipelineManager() {
  29685. this._renderPipelines = {};
  29686. }
  29687. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29688. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29689. };
  29690. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29691. var renderPipeline = this._renderPipelines[renderPipelineName];
  29692. if (!renderPipeline) {
  29693. return;
  29694. }
  29695. renderPipeline._attachCameras(cameras, unique);
  29696. };
  29697. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29698. var renderPipeline = this._renderPipelines[renderPipelineName];
  29699. if (!renderPipeline) {
  29700. return;
  29701. }
  29702. renderPipeline._detachCameras(cameras);
  29703. };
  29704. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29705. var renderPipeline = this._renderPipelines[renderPipelineName];
  29706. if (!renderPipeline) {
  29707. return;
  29708. }
  29709. renderPipeline._enableEffect(renderEffectName, cameras);
  29710. };
  29711. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29712. var renderPipeline = this._renderPipelines[renderPipelineName];
  29713. if (!renderPipeline) {
  29714. return;
  29715. }
  29716. renderPipeline._disableEffect(renderEffectName, cameras);
  29717. };
  29718. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29719. var renderPipeline = this._renderPipelines[renderPipelineName];
  29720. if (!renderPipeline) {
  29721. return;
  29722. }
  29723. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29724. };
  29725. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29726. var renderPipeline = this._renderPipelines[renderPipelineName];
  29727. if (!renderPipeline) {
  29728. return;
  29729. }
  29730. renderPipeline._disableDisplayOnlyPass(cameras);
  29731. };
  29732. PostProcessRenderPipelineManager.prototype.update = function () {
  29733. for (var renderPipelineName in this._renderPipelines) {
  29734. var pipeline = this._renderPipelines[renderPipelineName];
  29735. if (!pipeline.isSupported) {
  29736. pipeline.dispose();
  29737. delete this._renderPipelines[renderPipelineName];
  29738. }
  29739. else {
  29740. pipeline._update();
  29741. }
  29742. }
  29743. };
  29744. return PostProcessRenderPipelineManager;
  29745. }());
  29746. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29747. })(BABYLON || (BABYLON = {}));
  29748. var BABYLON;
  29749. (function (BABYLON) {
  29750. var BoundingBoxRenderer = (function () {
  29751. function BoundingBoxRenderer(scene) {
  29752. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29753. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29754. this.showBackLines = true;
  29755. this.renderList = new BABYLON.SmartArray(32);
  29756. this._scene = scene;
  29757. }
  29758. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29759. if (this._colorShader) {
  29760. return;
  29761. }
  29762. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29763. attributes: ["position"],
  29764. uniforms: ["worldViewProjection", "color"]
  29765. });
  29766. var engine = this._scene.getEngine();
  29767. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29768. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29769. 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]);
  29770. };
  29771. BoundingBoxRenderer.prototype.reset = function () {
  29772. this.renderList.reset();
  29773. };
  29774. BoundingBoxRenderer.prototype.render = function () {
  29775. if (this.renderList.length === 0) {
  29776. return;
  29777. }
  29778. this._prepareRessources();
  29779. if (!this._colorShader.isReady()) {
  29780. return;
  29781. }
  29782. var engine = this._scene.getEngine();
  29783. engine.setDepthWrite(false);
  29784. this._colorShader._preBind();
  29785. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29786. var boundingBox = this.renderList.data[boundingBoxIndex];
  29787. var min = boundingBox.minimum;
  29788. var max = boundingBox.maximum;
  29789. var diff = max.subtract(min);
  29790. var median = min.add(diff.scale(0.5));
  29791. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29792. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29793. .multiply(boundingBox.getWorldMatrix());
  29794. // VBOs
  29795. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29796. if (this.showBackLines) {
  29797. // Back
  29798. engine.setDepthFunctionToGreaterOrEqual();
  29799. this._scene.resetCachedMaterial();
  29800. this._colorShader.setColor4("color", this.backColor.toColor4());
  29801. this._colorShader.bind(worldMatrix);
  29802. // Draw order
  29803. engine.draw(false, 0, 24);
  29804. }
  29805. // Front
  29806. engine.setDepthFunctionToLess();
  29807. this._scene.resetCachedMaterial();
  29808. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29809. this._colorShader.bind(worldMatrix);
  29810. // Draw order
  29811. engine.draw(false, 0, 24);
  29812. }
  29813. this._colorShader.unbind();
  29814. engine.setDepthFunctionToLessOrEqual();
  29815. engine.setDepthWrite(true);
  29816. };
  29817. BoundingBoxRenderer.prototype.dispose = function () {
  29818. if (!this._colorShader) {
  29819. return;
  29820. }
  29821. this._colorShader.dispose();
  29822. this._vb.dispose();
  29823. this._scene.getEngine()._releaseBuffer(this._ib);
  29824. };
  29825. return BoundingBoxRenderer;
  29826. }());
  29827. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29828. })(BABYLON || (BABYLON = {}));
  29829. var BABYLON;
  29830. (function (BABYLON) {
  29831. var Condition = (function () {
  29832. function Condition(actionManager) {
  29833. this._actionManager = actionManager;
  29834. }
  29835. Condition.prototype.isValid = function () {
  29836. return true;
  29837. };
  29838. Condition.prototype._getProperty = function (propertyPath) {
  29839. return this._actionManager._getProperty(propertyPath);
  29840. };
  29841. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  29842. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29843. };
  29844. return Condition;
  29845. }());
  29846. BABYLON.Condition = Condition;
  29847. var ValueCondition = (function (_super) {
  29848. __extends(ValueCondition, _super);
  29849. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  29850. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  29851. _super.call(this, actionManager);
  29852. this.propertyPath = propertyPath;
  29853. this.value = value;
  29854. this.operator = operator;
  29855. this._target = this._getEffectiveTarget(target, this.propertyPath);
  29856. this._property = this._getProperty(this.propertyPath);
  29857. }
  29858. Object.defineProperty(ValueCondition, "IsEqual", {
  29859. get: function () {
  29860. return ValueCondition._IsEqual;
  29861. },
  29862. enumerable: true,
  29863. configurable: true
  29864. });
  29865. Object.defineProperty(ValueCondition, "IsDifferent", {
  29866. get: function () {
  29867. return ValueCondition._IsDifferent;
  29868. },
  29869. enumerable: true,
  29870. configurable: true
  29871. });
  29872. Object.defineProperty(ValueCondition, "IsGreater", {
  29873. get: function () {
  29874. return ValueCondition._IsGreater;
  29875. },
  29876. enumerable: true,
  29877. configurable: true
  29878. });
  29879. Object.defineProperty(ValueCondition, "IsLesser", {
  29880. get: function () {
  29881. return ValueCondition._IsLesser;
  29882. },
  29883. enumerable: true,
  29884. configurable: true
  29885. });
  29886. // Methods
  29887. ValueCondition.prototype.isValid = function () {
  29888. switch (this.operator) {
  29889. case ValueCondition.IsGreater:
  29890. return this._target[this._property] > this.value;
  29891. case ValueCondition.IsLesser:
  29892. return this._target[this._property] < this.value;
  29893. case ValueCondition.IsEqual:
  29894. case ValueCondition.IsDifferent:
  29895. var check;
  29896. if (this.value.equals) {
  29897. check = this.value.equals(this._target[this._property]);
  29898. }
  29899. else {
  29900. check = this.value === this._target[this._property];
  29901. }
  29902. return this.operator === ValueCondition.IsEqual ? check : !check;
  29903. }
  29904. return false;
  29905. };
  29906. // Statics
  29907. ValueCondition._IsEqual = 0;
  29908. ValueCondition._IsDifferent = 1;
  29909. ValueCondition._IsGreater = 2;
  29910. ValueCondition._IsLesser = 3;
  29911. return ValueCondition;
  29912. }(Condition));
  29913. BABYLON.ValueCondition = ValueCondition;
  29914. var PredicateCondition = (function (_super) {
  29915. __extends(PredicateCondition, _super);
  29916. function PredicateCondition(actionManager, predicate) {
  29917. _super.call(this, actionManager);
  29918. this.predicate = predicate;
  29919. }
  29920. PredicateCondition.prototype.isValid = function () {
  29921. return this.predicate();
  29922. };
  29923. return PredicateCondition;
  29924. }(Condition));
  29925. BABYLON.PredicateCondition = PredicateCondition;
  29926. var StateCondition = (function (_super) {
  29927. __extends(StateCondition, _super);
  29928. function StateCondition(actionManager, target, value) {
  29929. _super.call(this, actionManager);
  29930. this.value = value;
  29931. this._target = target;
  29932. }
  29933. // Methods
  29934. StateCondition.prototype.isValid = function () {
  29935. return this._target.state === this.value;
  29936. };
  29937. return StateCondition;
  29938. }(Condition));
  29939. BABYLON.StateCondition = StateCondition;
  29940. })(BABYLON || (BABYLON = {}));
  29941. var BABYLON;
  29942. (function (BABYLON) {
  29943. var Action = (function () {
  29944. function Action(triggerOptions, condition) {
  29945. this.triggerOptions = triggerOptions;
  29946. if (triggerOptions.parameter) {
  29947. this.trigger = triggerOptions.trigger;
  29948. this._triggerParameter = triggerOptions.parameter;
  29949. }
  29950. else {
  29951. this.trigger = triggerOptions;
  29952. }
  29953. this._nextActiveAction = this;
  29954. this._condition = condition;
  29955. }
  29956. // Methods
  29957. Action.prototype._prepare = function () {
  29958. };
  29959. Action.prototype.getTriggerParameter = function () {
  29960. return this._triggerParameter;
  29961. };
  29962. Action.prototype._executeCurrent = function (evt) {
  29963. if (this._nextActiveAction._condition) {
  29964. var condition = this._nextActiveAction._condition;
  29965. var currentRenderId = this._actionManager.getScene().getRenderId();
  29966. // We cache the current evaluation for the current frame
  29967. if (condition._evaluationId === currentRenderId) {
  29968. if (!condition._currentResult) {
  29969. return;
  29970. }
  29971. }
  29972. else {
  29973. condition._evaluationId = currentRenderId;
  29974. if (!condition.isValid()) {
  29975. condition._currentResult = false;
  29976. return;
  29977. }
  29978. condition._currentResult = true;
  29979. }
  29980. }
  29981. this._nextActiveAction.execute(evt);
  29982. this.skipToNextActiveAction();
  29983. };
  29984. Action.prototype.execute = function (evt) {
  29985. };
  29986. Action.prototype.skipToNextActiveAction = function () {
  29987. if (this._nextActiveAction._child) {
  29988. if (!this._nextActiveAction._child._actionManager) {
  29989. this._nextActiveAction._child._actionManager = this._actionManager;
  29990. }
  29991. this._nextActiveAction = this._nextActiveAction._child;
  29992. }
  29993. else {
  29994. this._nextActiveAction = this;
  29995. }
  29996. };
  29997. Action.prototype.then = function (action) {
  29998. this._child = action;
  29999. action._actionManager = this._actionManager;
  30000. action._prepare();
  30001. return action;
  30002. };
  30003. Action.prototype._getProperty = function (propertyPath) {
  30004. return this._actionManager._getProperty(propertyPath);
  30005. };
  30006. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30007. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30008. };
  30009. return Action;
  30010. }());
  30011. BABYLON.Action = Action;
  30012. })(BABYLON || (BABYLON = {}));
  30013. var BABYLON;
  30014. (function (BABYLON) {
  30015. /**
  30016. * ActionEvent is the event beint sent when an action is triggered.
  30017. */
  30018. var ActionEvent = (function () {
  30019. /**
  30020. * @constructor
  30021. * @param source The mesh or sprite that triggered the action.
  30022. * @param pointerX The X mouse cursor position at the time of the event
  30023. * @param pointerY The Y mouse cursor position at the time of the event
  30024. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30025. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30026. */
  30027. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30028. this.source = source;
  30029. this.pointerX = pointerX;
  30030. this.pointerY = pointerY;
  30031. this.meshUnderPointer = meshUnderPointer;
  30032. this.sourceEvent = sourceEvent;
  30033. this.additionalData = additionalData;
  30034. }
  30035. /**
  30036. * Helper function to auto-create an ActionEvent from a source mesh.
  30037. * @param source The source mesh that triggered the event
  30038. * @param evt {Event} The original (browser) event
  30039. */
  30040. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30041. var scene = source.getScene();
  30042. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30043. };
  30044. /**
  30045. * Helper function to auto-create an ActionEvent from a source mesh.
  30046. * @param source The source sprite that triggered the event
  30047. * @param scene Scene associated with the sprite
  30048. * @param evt {Event} The original (browser) event
  30049. */
  30050. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30051. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30052. };
  30053. /**
  30054. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30055. * @param scene the scene where the event occurred
  30056. * @param evt {Event} The original (browser) event
  30057. */
  30058. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30059. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30060. };
  30061. return ActionEvent;
  30062. }());
  30063. BABYLON.ActionEvent = ActionEvent;
  30064. /**
  30065. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30066. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30067. */
  30068. var ActionManager = (function () {
  30069. function ActionManager(scene) {
  30070. // Members
  30071. this.actions = new Array();
  30072. this._scene = scene;
  30073. scene._actionManagers.push(this);
  30074. }
  30075. Object.defineProperty(ActionManager, "NothingTrigger", {
  30076. get: function () {
  30077. return ActionManager._NothingTrigger;
  30078. },
  30079. enumerable: true,
  30080. configurable: true
  30081. });
  30082. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30083. get: function () {
  30084. return ActionManager._OnPickTrigger;
  30085. },
  30086. enumerable: true,
  30087. configurable: true
  30088. });
  30089. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30090. get: function () {
  30091. return ActionManager._OnLeftPickTrigger;
  30092. },
  30093. enumerable: true,
  30094. configurable: true
  30095. });
  30096. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30097. get: function () {
  30098. return ActionManager._OnRightPickTrigger;
  30099. },
  30100. enumerable: true,
  30101. configurable: true
  30102. });
  30103. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30104. get: function () {
  30105. return ActionManager._OnCenterPickTrigger;
  30106. },
  30107. enumerable: true,
  30108. configurable: true
  30109. });
  30110. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30111. get: function () {
  30112. return ActionManager._OnPickDownTrigger;
  30113. },
  30114. enumerable: true,
  30115. configurable: true
  30116. });
  30117. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30118. get: function () {
  30119. return ActionManager._OnPickUpTrigger;
  30120. },
  30121. enumerable: true,
  30122. configurable: true
  30123. });
  30124. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30125. /// This trigger will only be raised if you also declared a OnPickDown
  30126. get: function () {
  30127. return ActionManager._OnPickOutTrigger;
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30133. get: function () {
  30134. return ActionManager._OnLongPressTrigger;
  30135. },
  30136. enumerable: true,
  30137. configurable: true
  30138. });
  30139. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30140. get: function () {
  30141. return ActionManager._OnPointerOverTrigger;
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30147. get: function () {
  30148. return ActionManager._OnPointerOutTrigger;
  30149. },
  30150. enumerable: true,
  30151. configurable: true
  30152. });
  30153. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30154. get: function () {
  30155. return ActionManager._OnEveryFrameTrigger;
  30156. },
  30157. enumerable: true,
  30158. configurable: true
  30159. });
  30160. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30161. get: function () {
  30162. return ActionManager._OnIntersectionEnterTrigger;
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30168. get: function () {
  30169. return ActionManager._OnIntersectionExitTrigger;
  30170. },
  30171. enumerable: true,
  30172. configurable: true
  30173. });
  30174. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30175. get: function () {
  30176. return ActionManager._OnKeyDownTrigger;
  30177. },
  30178. enumerable: true,
  30179. configurable: true
  30180. });
  30181. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30182. get: function () {
  30183. return ActionManager._OnKeyUpTrigger;
  30184. },
  30185. enumerable: true,
  30186. configurable: true
  30187. });
  30188. // Methods
  30189. ActionManager.prototype.dispose = function () {
  30190. var index = this._scene._actionManagers.indexOf(this);
  30191. if (index > -1) {
  30192. this._scene._actionManagers.splice(index, 1);
  30193. }
  30194. };
  30195. ActionManager.prototype.getScene = function () {
  30196. return this._scene;
  30197. };
  30198. /**
  30199. * Does this action manager handles actions of any of the given triggers
  30200. * @param {number[]} triggers - the triggers to be tested
  30201. * @return {boolean} whether one (or more) of the triggers is handeled
  30202. */
  30203. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30204. for (var index = 0; index < this.actions.length; index++) {
  30205. var action = this.actions[index];
  30206. if (triggers.indexOf(action.trigger) > -1) {
  30207. return true;
  30208. }
  30209. }
  30210. return false;
  30211. };
  30212. /**
  30213. * Does this action manager handles actions of a given trigger
  30214. * @param {number} trigger - the trigger to be tested
  30215. * @return {boolean} whether the trigger is handeled
  30216. */
  30217. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30218. for (var index = 0; index < this.actions.length; index++) {
  30219. var action = this.actions[index];
  30220. if (action.trigger === trigger) {
  30221. return true;
  30222. }
  30223. }
  30224. return false;
  30225. };
  30226. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30227. /**
  30228. * Does this action manager has pointer triggers
  30229. * @return {boolean} whether or not it has pointer triggers
  30230. */
  30231. get: function () {
  30232. for (var index = 0; index < this.actions.length; index++) {
  30233. var action = this.actions[index];
  30234. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30235. return true;
  30236. }
  30237. }
  30238. return false;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30244. /**
  30245. * Does this action manager has pick triggers
  30246. * @return {boolean} whether or not it has pick triggers
  30247. */
  30248. get: function () {
  30249. for (var index = 0; index < this.actions.length; index++) {
  30250. var action = this.actions[index];
  30251. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30252. return true;
  30253. }
  30254. }
  30255. return false;
  30256. },
  30257. enumerable: true,
  30258. configurable: true
  30259. });
  30260. /**
  30261. * Registers an action to this action manager
  30262. * @param {BABYLON.Action} action - the action to be registered
  30263. * @return {BABYLON.Action} the action amended (prepared) after registration
  30264. */
  30265. ActionManager.prototype.registerAction = function (action) {
  30266. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30267. if (this.getScene().actionManager !== this) {
  30268. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30269. return null;
  30270. }
  30271. }
  30272. this.actions.push(action);
  30273. action._actionManager = this;
  30274. action._prepare();
  30275. return action;
  30276. };
  30277. /**
  30278. * Process a specific trigger
  30279. * @param {number} trigger - the trigger to process
  30280. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30281. */
  30282. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30283. for (var index = 0; index < this.actions.length; index++) {
  30284. var action = this.actions[index];
  30285. if (action.trigger === trigger) {
  30286. if (trigger === ActionManager.OnKeyUpTrigger
  30287. || trigger === ActionManager.OnKeyDownTrigger) {
  30288. var parameter = action.getTriggerParameter();
  30289. if (parameter) {
  30290. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30291. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30292. if (actualkey !== parameter.toLowerCase()) {
  30293. continue;
  30294. }
  30295. }
  30296. }
  30297. action._executeCurrent(evt);
  30298. }
  30299. }
  30300. };
  30301. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30302. var properties = propertyPath.split(".");
  30303. for (var index = 0; index < properties.length - 1; index++) {
  30304. target = target[properties[index]];
  30305. }
  30306. return target;
  30307. };
  30308. ActionManager.prototype._getProperty = function (propertyPath) {
  30309. var properties = propertyPath.split(".");
  30310. return properties[properties.length - 1];
  30311. };
  30312. ActionManager.Parse = function (parsedActions, object, scene) {
  30313. var actionManager = new BABYLON.ActionManager(scene);
  30314. if (object === null)
  30315. scene.actionManager = actionManager;
  30316. else
  30317. object.actionManager = actionManager;
  30318. // instanciate a new object
  30319. var instanciate = function (name, params) {
  30320. var newInstance = Object.create(BABYLON[name].prototype);
  30321. newInstance.constructor.apply(newInstance, params);
  30322. return newInstance;
  30323. };
  30324. var parseParameter = function (name, value, target, propertyPath) {
  30325. if (propertyPath === null) {
  30326. // String, boolean or float
  30327. var floatValue = parseFloat(value);
  30328. if (value === "true" || value === "false")
  30329. return value === "true";
  30330. else
  30331. return isNaN(floatValue) ? value : floatValue;
  30332. }
  30333. var effectiveTarget = propertyPath.split(".");
  30334. var values = value.split(",");
  30335. // Get effective Target
  30336. for (var i = 0; i < effectiveTarget.length; i++) {
  30337. target = target[effectiveTarget[i]];
  30338. }
  30339. // Return appropriate value with its type
  30340. if (typeof (target) === "boolean")
  30341. return values[0] === "true";
  30342. if (typeof (target) === "string")
  30343. return values[0];
  30344. // Parameters with multiple values such as Vector3 etc.
  30345. var split = new Array();
  30346. for (var i = 0; i < values.length; i++)
  30347. split.push(parseFloat(values[i]));
  30348. if (target instanceof BABYLON.Vector3)
  30349. return BABYLON.Vector3.FromArray(split);
  30350. if (target instanceof BABYLON.Vector4)
  30351. return BABYLON.Vector4.FromArray(split);
  30352. if (target instanceof BABYLON.Color3)
  30353. return BABYLON.Color3.FromArray(split);
  30354. if (target instanceof BABYLON.Color4)
  30355. return BABYLON.Color4.FromArray(split);
  30356. return parseFloat(values[0]);
  30357. };
  30358. // traverse graph per trigger
  30359. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30360. if (combineArray === void 0) { combineArray = null; }
  30361. if (parsedAction.detached)
  30362. return;
  30363. var parameters = new Array();
  30364. var target = null;
  30365. var propertyPath = null;
  30366. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30367. // Parameters
  30368. if (parsedAction.type === 2)
  30369. parameters.push(actionManager);
  30370. else
  30371. parameters.push(trigger);
  30372. if (combine) {
  30373. var actions = new Array();
  30374. for (var j = 0; j < parsedAction.combine.length; j++) {
  30375. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30376. }
  30377. parameters.push(actions);
  30378. }
  30379. else {
  30380. for (var i = 0; i < parsedAction.properties.length; i++) {
  30381. var value = parsedAction.properties[i].value;
  30382. var name = parsedAction.properties[i].name;
  30383. var targetType = parsedAction.properties[i].targetType;
  30384. if (name === "target")
  30385. if (targetType !== null && targetType === "SceneProperties")
  30386. value = target = scene;
  30387. else
  30388. value = target = scene.getNodeByName(value);
  30389. else if (name === "parent")
  30390. value = scene.getNodeByName(value);
  30391. else if (name === "sound")
  30392. value = scene.getSoundByName(value);
  30393. else if (name !== "propertyPath") {
  30394. if (parsedAction.type === 2 && name === "operator")
  30395. value = BABYLON.ValueCondition[value];
  30396. else
  30397. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30398. }
  30399. else {
  30400. propertyPath = value;
  30401. }
  30402. parameters.push(value);
  30403. }
  30404. }
  30405. if (combineArray === null) {
  30406. parameters.push(condition);
  30407. }
  30408. else {
  30409. parameters.push(null);
  30410. }
  30411. // If interpolate value action
  30412. if (parsedAction.name === "InterpolateValueAction") {
  30413. var param = parameters[parameters.length - 2];
  30414. parameters[parameters.length - 1] = param;
  30415. parameters[parameters.length - 2] = condition;
  30416. }
  30417. // Action or condition(s) and not CombineAction
  30418. var newAction = instanciate(parsedAction.name, parameters);
  30419. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30420. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30421. if (action)
  30422. action.then(nothing);
  30423. else
  30424. actionManager.registerAction(nothing);
  30425. action = nothing;
  30426. }
  30427. if (combineArray === null) {
  30428. if (newAction instanceof BABYLON.Condition) {
  30429. condition = newAction;
  30430. newAction = action;
  30431. }
  30432. else {
  30433. condition = null;
  30434. if (action)
  30435. action.then(newAction);
  30436. else
  30437. actionManager.registerAction(newAction);
  30438. }
  30439. }
  30440. else {
  30441. combineArray.push(newAction);
  30442. }
  30443. for (var i = 0; i < parsedAction.children.length; i++)
  30444. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30445. };
  30446. // triggers
  30447. for (var i = 0; i < parsedActions.children.length; i++) {
  30448. var triggerParams;
  30449. var trigger = parsedActions.children[i];
  30450. if (trigger.properties.length > 0) {
  30451. var param = trigger.properties[0].value;
  30452. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30453. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30454. }
  30455. else
  30456. triggerParams = BABYLON.ActionManager[trigger.name];
  30457. for (var j = 0; j < trigger.children.length; j++) {
  30458. if (!trigger.detached)
  30459. traverse(trigger.children[j], triggerParams, null, null);
  30460. }
  30461. }
  30462. };
  30463. // Statics
  30464. ActionManager._NothingTrigger = 0;
  30465. ActionManager._OnPickTrigger = 1;
  30466. ActionManager._OnLeftPickTrigger = 2;
  30467. ActionManager._OnRightPickTrigger = 3;
  30468. ActionManager._OnCenterPickTrigger = 4;
  30469. ActionManager._OnPickDownTrigger = 5;
  30470. ActionManager._OnPickUpTrigger = 6;
  30471. ActionManager._OnLongPressTrigger = 7;
  30472. ActionManager._OnPointerOverTrigger = 8;
  30473. ActionManager._OnPointerOutTrigger = 9;
  30474. ActionManager._OnEveryFrameTrigger = 10;
  30475. ActionManager._OnIntersectionEnterTrigger = 11;
  30476. ActionManager._OnIntersectionExitTrigger = 12;
  30477. ActionManager._OnKeyDownTrigger = 13;
  30478. ActionManager._OnKeyUpTrigger = 14;
  30479. ActionManager._OnPickOutTrigger = 15;
  30480. ActionManager.DragMovementThreshold = 10; // in pixels
  30481. ActionManager.LongPressDelay = 500; // in milliseconds
  30482. return ActionManager;
  30483. }());
  30484. BABYLON.ActionManager = ActionManager;
  30485. })(BABYLON || (BABYLON = {}));
  30486. var BABYLON;
  30487. (function (BABYLON) {
  30488. var InterpolateValueAction = (function (_super) {
  30489. __extends(InterpolateValueAction, _super);
  30490. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30491. if (duration === void 0) { duration = 1000; }
  30492. _super.call(this, triggerOptions, condition);
  30493. this.propertyPath = propertyPath;
  30494. this.value = value;
  30495. this.duration = duration;
  30496. this.stopOtherAnimations = stopOtherAnimations;
  30497. this.onInterpolationDone = onInterpolationDone;
  30498. this._target = target;
  30499. }
  30500. InterpolateValueAction.prototype._prepare = function () {
  30501. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30502. this._property = this._getProperty(this.propertyPath);
  30503. };
  30504. InterpolateValueAction.prototype.execute = function () {
  30505. var scene = this._actionManager.getScene();
  30506. var keys = [
  30507. {
  30508. frame: 0,
  30509. value: this._target[this._property]
  30510. }, {
  30511. frame: 100,
  30512. value: this.value
  30513. }
  30514. ];
  30515. var dataType;
  30516. if (typeof this.value === "number") {
  30517. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30518. }
  30519. else if (this.value instanceof BABYLON.Color3) {
  30520. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30521. }
  30522. else if (this.value instanceof BABYLON.Vector3) {
  30523. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30524. }
  30525. else if (this.value instanceof BABYLON.Matrix) {
  30526. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30527. }
  30528. else if (this.value instanceof BABYLON.Quaternion) {
  30529. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30530. }
  30531. else {
  30532. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30533. return;
  30534. }
  30535. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30536. animation.setKeys(keys);
  30537. if (this.stopOtherAnimations) {
  30538. scene.stopAnimation(this._target);
  30539. }
  30540. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30541. };
  30542. return InterpolateValueAction;
  30543. }(BABYLON.Action));
  30544. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30545. })(BABYLON || (BABYLON = {}));
  30546. var BABYLON;
  30547. (function (BABYLON) {
  30548. var SwitchBooleanAction = (function (_super) {
  30549. __extends(SwitchBooleanAction, _super);
  30550. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30551. _super.call(this, triggerOptions, condition);
  30552. this.propertyPath = propertyPath;
  30553. this._target = target;
  30554. }
  30555. SwitchBooleanAction.prototype._prepare = function () {
  30556. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30557. this._property = this._getProperty(this.propertyPath);
  30558. };
  30559. SwitchBooleanAction.prototype.execute = function () {
  30560. this._target[this._property] = !this._target[this._property];
  30561. };
  30562. return SwitchBooleanAction;
  30563. }(BABYLON.Action));
  30564. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30565. var SetStateAction = (function (_super) {
  30566. __extends(SetStateAction, _super);
  30567. function SetStateAction(triggerOptions, target, value, condition) {
  30568. _super.call(this, triggerOptions, condition);
  30569. this.value = value;
  30570. this._target = target;
  30571. }
  30572. SetStateAction.prototype.execute = function () {
  30573. this._target.state = this.value;
  30574. };
  30575. return SetStateAction;
  30576. }(BABYLON.Action));
  30577. BABYLON.SetStateAction = SetStateAction;
  30578. var SetValueAction = (function (_super) {
  30579. __extends(SetValueAction, _super);
  30580. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30581. _super.call(this, triggerOptions, condition);
  30582. this.propertyPath = propertyPath;
  30583. this.value = value;
  30584. this._target = target;
  30585. }
  30586. SetValueAction.prototype._prepare = function () {
  30587. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30588. this._property = this._getProperty(this.propertyPath);
  30589. };
  30590. SetValueAction.prototype.execute = function () {
  30591. this._target[this._property] = this.value;
  30592. };
  30593. return SetValueAction;
  30594. }(BABYLON.Action));
  30595. BABYLON.SetValueAction = SetValueAction;
  30596. var IncrementValueAction = (function (_super) {
  30597. __extends(IncrementValueAction, _super);
  30598. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30599. _super.call(this, triggerOptions, condition);
  30600. this.propertyPath = propertyPath;
  30601. this.value = value;
  30602. this._target = target;
  30603. }
  30604. IncrementValueAction.prototype._prepare = function () {
  30605. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30606. this._property = this._getProperty(this.propertyPath);
  30607. if (typeof this._target[this._property] !== "number") {
  30608. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30609. }
  30610. };
  30611. IncrementValueAction.prototype.execute = function () {
  30612. this._target[this._property] += this.value;
  30613. };
  30614. return IncrementValueAction;
  30615. }(BABYLON.Action));
  30616. BABYLON.IncrementValueAction = IncrementValueAction;
  30617. var PlayAnimationAction = (function (_super) {
  30618. __extends(PlayAnimationAction, _super);
  30619. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30620. _super.call(this, triggerOptions, condition);
  30621. this.from = from;
  30622. this.to = to;
  30623. this.loop = loop;
  30624. this._target = target;
  30625. }
  30626. PlayAnimationAction.prototype._prepare = function () {
  30627. };
  30628. PlayAnimationAction.prototype.execute = function () {
  30629. var scene = this._actionManager.getScene();
  30630. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30631. };
  30632. return PlayAnimationAction;
  30633. }(BABYLON.Action));
  30634. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30635. var StopAnimationAction = (function (_super) {
  30636. __extends(StopAnimationAction, _super);
  30637. function StopAnimationAction(triggerOptions, target, condition) {
  30638. _super.call(this, triggerOptions, condition);
  30639. this._target = target;
  30640. }
  30641. StopAnimationAction.prototype._prepare = function () {
  30642. };
  30643. StopAnimationAction.prototype.execute = function () {
  30644. var scene = this._actionManager.getScene();
  30645. scene.stopAnimation(this._target);
  30646. };
  30647. return StopAnimationAction;
  30648. }(BABYLON.Action));
  30649. BABYLON.StopAnimationAction = StopAnimationAction;
  30650. var DoNothingAction = (function (_super) {
  30651. __extends(DoNothingAction, _super);
  30652. function DoNothingAction(triggerOptions, condition) {
  30653. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30654. _super.call(this, triggerOptions, condition);
  30655. }
  30656. DoNothingAction.prototype.execute = function () {
  30657. };
  30658. return DoNothingAction;
  30659. }(BABYLON.Action));
  30660. BABYLON.DoNothingAction = DoNothingAction;
  30661. var CombineAction = (function (_super) {
  30662. __extends(CombineAction, _super);
  30663. function CombineAction(triggerOptions, children, condition) {
  30664. _super.call(this, triggerOptions, condition);
  30665. this.children = children;
  30666. }
  30667. CombineAction.prototype._prepare = function () {
  30668. for (var index = 0; index < this.children.length; index++) {
  30669. this.children[index]._actionManager = this._actionManager;
  30670. this.children[index]._prepare();
  30671. }
  30672. };
  30673. CombineAction.prototype.execute = function (evt) {
  30674. for (var index = 0; index < this.children.length; index++) {
  30675. this.children[index].execute(evt);
  30676. }
  30677. };
  30678. return CombineAction;
  30679. }(BABYLON.Action));
  30680. BABYLON.CombineAction = CombineAction;
  30681. var ExecuteCodeAction = (function (_super) {
  30682. __extends(ExecuteCodeAction, _super);
  30683. function ExecuteCodeAction(triggerOptions, func, condition) {
  30684. _super.call(this, triggerOptions, condition);
  30685. this.func = func;
  30686. }
  30687. ExecuteCodeAction.prototype.execute = function (evt) {
  30688. this.func(evt);
  30689. };
  30690. return ExecuteCodeAction;
  30691. }(BABYLON.Action));
  30692. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30693. var SetParentAction = (function (_super) {
  30694. __extends(SetParentAction, _super);
  30695. function SetParentAction(triggerOptions, target, parent, condition) {
  30696. _super.call(this, triggerOptions, condition);
  30697. this._target = target;
  30698. this._parent = parent;
  30699. }
  30700. SetParentAction.prototype._prepare = function () {
  30701. };
  30702. SetParentAction.prototype.execute = function () {
  30703. if (this._target.parent === this._parent) {
  30704. return;
  30705. }
  30706. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30707. invertParentWorldMatrix.invert();
  30708. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30709. this._target.parent = this._parent;
  30710. };
  30711. return SetParentAction;
  30712. }(BABYLON.Action));
  30713. BABYLON.SetParentAction = SetParentAction;
  30714. var PlaySoundAction = (function (_super) {
  30715. __extends(PlaySoundAction, _super);
  30716. function PlaySoundAction(triggerOptions, sound, condition) {
  30717. _super.call(this, triggerOptions, condition);
  30718. this._sound = sound;
  30719. }
  30720. PlaySoundAction.prototype._prepare = function () {
  30721. };
  30722. PlaySoundAction.prototype.execute = function () {
  30723. if (this._sound !== undefined)
  30724. this._sound.play();
  30725. };
  30726. return PlaySoundAction;
  30727. }(BABYLON.Action));
  30728. BABYLON.PlaySoundAction = PlaySoundAction;
  30729. var StopSoundAction = (function (_super) {
  30730. __extends(StopSoundAction, _super);
  30731. function StopSoundAction(triggerOptions, sound, condition) {
  30732. _super.call(this, triggerOptions, condition);
  30733. this._sound = sound;
  30734. }
  30735. StopSoundAction.prototype._prepare = function () {
  30736. };
  30737. StopSoundAction.prototype.execute = function () {
  30738. if (this._sound !== undefined)
  30739. this._sound.stop();
  30740. };
  30741. return StopSoundAction;
  30742. }(BABYLON.Action));
  30743. BABYLON.StopSoundAction = StopSoundAction;
  30744. })(BABYLON || (BABYLON = {}));
  30745. var BABYLON;
  30746. (function (BABYLON) {
  30747. var Geometry = (function () {
  30748. function Geometry(id, scene, vertexData, updatable, mesh) {
  30749. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30750. this._totalVertices = 0;
  30751. this._isDisposed = false;
  30752. this.id = id;
  30753. this._engine = scene.getEngine();
  30754. this._meshes = [];
  30755. this._scene = scene;
  30756. //Init vertex buffer cache
  30757. this._vertexBuffers = {};
  30758. this._indices = [];
  30759. // vertexData
  30760. if (vertexData) {
  30761. this.setAllVerticesData(vertexData, updatable);
  30762. }
  30763. else {
  30764. this._totalVertices = 0;
  30765. this._indices = [];
  30766. }
  30767. // applyToMesh
  30768. if (mesh) {
  30769. if (mesh instanceof BABYLON.LinesMesh) {
  30770. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30771. this.updateExtend();
  30772. }
  30773. this.applyToMesh(mesh);
  30774. mesh.computeWorldMatrix(true);
  30775. }
  30776. }
  30777. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30778. /**
  30779. * 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
  30780. * @returns The Bias Vector
  30781. */
  30782. get: function () {
  30783. return this._boundingBias;
  30784. },
  30785. set: function (value) {
  30786. if (this._boundingBias && this._boundingBias.equals(value)) {
  30787. return;
  30788. }
  30789. this._boundingBias = value.clone();
  30790. this.updateExtend();
  30791. },
  30792. enumerable: true,
  30793. configurable: true
  30794. });
  30795. Object.defineProperty(Geometry.prototype, "extend", {
  30796. get: function () {
  30797. return this._extend;
  30798. },
  30799. enumerable: true,
  30800. configurable: true
  30801. });
  30802. Geometry.prototype.getScene = function () {
  30803. return this._scene;
  30804. };
  30805. Geometry.prototype.getEngine = function () {
  30806. return this._engine;
  30807. };
  30808. Geometry.prototype.isReady = function () {
  30809. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30810. };
  30811. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30812. vertexData.applyToGeometry(this, updatable);
  30813. this.notifyUpdate();
  30814. };
  30815. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30816. if (this._vertexBuffers[kind]) {
  30817. this._vertexBuffers[kind].dispose();
  30818. }
  30819. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30820. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30821. stride = this._vertexBuffers[kind].getStrideSize();
  30822. this._totalVertices = data.length / stride;
  30823. this.updateExtend(data);
  30824. var meshes = this._meshes;
  30825. var numOfMeshes = meshes.length;
  30826. for (var index = 0; index < numOfMeshes; index++) {
  30827. var mesh = meshes[index];
  30828. mesh._resetPointsArrayCache();
  30829. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30830. mesh._createGlobalSubMesh();
  30831. mesh.computeWorldMatrix(true);
  30832. }
  30833. }
  30834. this.notifyUpdate(kind);
  30835. };
  30836. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30837. var vertexBuffer = this.getVertexBuffer(kind);
  30838. if (!vertexBuffer) {
  30839. return;
  30840. }
  30841. vertexBuffer.updateDirectly(data, offset);
  30842. this.notifyUpdate(kind);
  30843. };
  30844. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30845. var vertexBuffer = this.getVertexBuffer(kind);
  30846. if (!vertexBuffer) {
  30847. return;
  30848. }
  30849. vertexBuffer.update(data);
  30850. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30851. var stride = vertexBuffer.getStrideSize();
  30852. this._totalVertices = data.length / stride;
  30853. if (updateExtends) {
  30854. this.updateExtend(data);
  30855. }
  30856. var meshes = this._meshes;
  30857. var numOfMeshes = meshes.length;
  30858. for (var index = 0; index < numOfMeshes; index++) {
  30859. var mesh = meshes[index];
  30860. mesh._resetPointsArrayCache();
  30861. if (updateExtends) {
  30862. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30863. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30864. var subMesh = mesh.subMeshes[subIndex];
  30865. subMesh.refreshBoundingInfo();
  30866. }
  30867. }
  30868. }
  30869. }
  30870. this.notifyUpdate(kind);
  30871. };
  30872. Geometry.prototype.getTotalVertices = function () {
  30873. if (!this.isReady()) {
  30874. return 0;
  30875. }
  30876. return this._totalVertices;
  30877. };
  30878. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  30879. var vertexBuffer = this.getVertexBuffer(kind);
  30880. if (!vertexBuffer) {
  30881. return null;
  30882. }
  30883. var orig = vertexBuffer.getData();
  30884. if (!copyWhenShared || this._meshes.length === 1) {
  30885. return orig;
  30886. }
  30887. else {
  30888. var len = orig.length;
  30889. var copy = [];
  30890. for (var i = 0; i < len; i++) {
  30891. copy.push(orig[i]);
  30892. }
  30893. return copy;
  30894. }
  30895. };
  30896. Geometry.prototype.getVertexBuffer = function (kind) {
  30897. if (!this.isReady()) {
  30898. return null;
  30899. }
  30900. return this._vertexBuffers[kind];
  30901. };
  30902. Geometry.prototype.getVertexBuffers = function () {
  30903. if (!this.isReady()) {
  30904. return null;
  30905. }
  30906. return this._vertexBuffers;
  30907. };
  30908. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30909. if (!this._vertexBuffers) {
  30910. if (this._delayInfo) {
  30911. return this._delayInfo.indexOf(kind) !== -1;
  30912. }
  30913. return false;
  30914. }
  30915. return this._vertexBuffers[kind] !== undefined;
  30916. };
  30917. Geometry.prototype.getVerticesDataKinds = function () {
  30918. var result = [];
  30919. var kind;
  30920. if (!this._vertexBuffers && this._delayInfo) {
  30921. for (kind in this._delayInfo) {
  30922. result.push(kind);
  30923. }
  30924. }
  30925. else {
  30926. for (kind in this._vertexBuffers) {
  30927. result.push(kind);
  30928. }
  30929. }
  30930. return result;
  30931. };
  30932. Geometry.prototype.setIndices = function (indices, totalVertices) {
  30933. if (this._indexBuffer) {
  30934. this._engine._releaseBuffer(this._indexBuffer);
  30935. }
  30936. this._indices = indices;
  30937. if (this._meshes.length !== 0 && this._indices) {
  30938. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30939. }
  30940. if (totalVertices !== undefined) {
  30941. this._totalVertices = totalVertices;
  30942. }
  30943. var meshes = this._meshes;
  30944. var numOfMeshes = meshes.length;
  30945. for (var index = 0; index < numOfMeshes; index++) {
  30946. meshes[index]._createGlobalSubMesh();
  30947. }
  30948. this.notifyUpdate();
  30949. };
  30950. Geometry.prototype.getTotalIndices = function () {
  30951. if (!this.isReady()) {
  30952. return 0;
  30953. }
  30954. return this._indices.length;
  30955. };
  30956. Geometry.prototype.getIndices = function (copyWhenShared) {
  30957. if (!this.isReady()) {
  30958. return null;
  30959. }
  30960. var orig = this._indices;
  30961. if (!copyWhenShared || this._meshes.length === 1) {
  30962. return orig;
  30963. }
  30964. else {
  30965. var len = orig.length;
  30966. var copy = [];
  30967. for (var i = 0; i < len; i++) {
  30968. copy.push(orig[i]);
  30969. }
  30970. return copy;
  30971. }
  30972. };
  30973. Geometry.prototype.getIndexBuffer = function () {
  30974. if (!this.isReady()) {
  30975. return null;
  30976. }
  30977. return this._indexBuffer;
  30978. };
  30979. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30980. var meshes = this._meshes;
  30981. var index = meshes.indexOf(mesh);
  30982. if (index === -1) {
  30983. return;
  30984. }
  30985. for (var kind in this._vertexBuffers) {
  30986. this._vertexBuffers[kind].dispose();
  30987. }
  30988. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  30989. this._indexBuffer = null;
  30990. }
  30991. meshes.splice(index, 1);
  30992. mesh._geometry = null;
  30993. if (meshes.length === 0 && shouldDispose) {
  30994. this.dispose();
  30995. }
  30996. };
  30997. Geometry.prototype.applyToMesh = function (mesh) {
  30998. if (mesh._geometry === this) {
  30999. return;
  31000. }
  31001. var previousGeometry = mesh._geometry;
  31002. if (previousGeometry) {
  31003. previousGeometry.releaseForMesh(mesh);
  31004. }
  31005. var meshes = this._meshes;
  31006. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31007. mesh._geometry = this;
  31008. this._scene.pushGeometry(this);
  31009. meshes.push(mesh);
  31010. if (this.isReady()) {
  31011. this._applyToMesh(mesh);
  31012. }
  31013. else {
  31014. mesh._boundingInfo = this._boundingInfo;
  31015. }
  31016. };
  31017. Geometry.prototype.updateExtend = function (data) {
  31018. if (data === void 0) { data = null; }
  31019. if (!data) {
  31020. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31021. }
  31022. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31023. };
  31024. Geometry.prototype._applyToMesh = function (mesh) {
  31025. var numOfMeshes = this._meshes.length;
  31026. // vertexBuffers
  31027. for (var kind in this._vertexBuffers) {
  31028. if (numOfMeshes === 1) {
  31029. this._vertexBuffers[kind].create();
  31030. }
  31031. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31032. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31033. mesh._resetPointsArrayCache();
  31034. if (!this._extend) {
  31035. this.updateExtend(this._vertexBuffers[kind].getData());
  31036. }
  31037. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31038. mesh._createGlobalSubMesh();
  31039. //bounding info was just created again, world matrix should be applied again.
  31040. mesh._updateBoundingInfo();
  31041. }
  31042. }
  31043. // indexBuffer
  31044. if (numOfMeshes === 1 && this._indices) {
  31045. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31046. }
  31047. if (this._indexBuffer) {
  31048. this._indexBuffer.references = numOfMeshes;
  31049. }
  31050. };
  31051. Geometry.prototype.notifyUpdate = function (kind) {
  31052. if (this.onGeometryUpdated) {
  31053. this.onGeometryUpdated(this, kind);
  31054. }
  31055. };
  31056. Geometry.prototype.load = function (scene, onLoaded) {
  31057. var _this = this;
  31058. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31059. return;
  31060. }
  31061. if (this.isReady()) {
  31062. if (onLoaded) {
  31063. onLoaded();
  31064. }
  31065. return;
  31066. }
  31067. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31068. scene._addPendingData(this);
  31069. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31070. _this._delayLoadingFunction(JSON.parse(data), _this);
  31071. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31072. _this._delayInfo = [];
  31073. scene._removePendingData(_this);
  31074. var meshes = _this._meshes;
  31075. var numOfMeshes = meshes.length;
  31076. for (var index = 0; index < numOfMeshes; index++) {
  31077. _this._applyToMesh(meshes[index]);
  31078. }
  31079. if (onLoaded) {
  31080. onLoaded();
  31081. }
  31082. }, function () { }, scene.database);
  31083. };
  31084. Geometry.prototype.isDisposed = function () {
  31085. return this._isDisposed;
  31086. };
  31087. Geometry.prototype.dispose = function () {
  31088. var meshes = this._meshes;
  31089. var numOfMeshes = meshes.length;
  31090. var index;
  31091. for (index = 0; index < numOfMeshes; index++) {
  31092. this.releaseForMesh(meshes[index]);
  31093. }
  31094. this._meshes = [];
  31095. for (var kind in this._vertexBuffers) {
  31096. this._vertexBuffers[kind].dispose();
  31097. }
  31098. this._vertexBuffers = [];
  31099. this._totalVertices = 0;
  31100. if (this._indexBuffer) {
  31101. this._engine._releaseBuffer(this._indexBuffer);
  31102. }
  31103. this._indexBuffer = null;
  31104. this._indices = [];
  31105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31106. this.delayLoadingFile = null;
  31107. this._delayLoadingFunction = null;
  31108. this._delayInfo = [];
  31109. this._boundingInfo = null;
  31110. this._scene.removeGeometry(this);
  31111. this._isDisposed = true;
  31112. };
  31113. Geometry.prototype.copy = function (id) {
  31114. var vertexData = new BABYLON.VertexData();
  31115. vertexData.indices = [];
  31116. var indices = this.getIndices();
  31117. for (var index = 0; index < indices.length; index++) {
  31118. vertexData.indices.push(indices[index]);
  31119. }
  31120. var updatable = false;
  31121. var stopChecking = false;
  31122. var kind;
  31123. for (kind in this._vertexBuffers) {
  31124. // using slice() to make a copy of the array and not just reference it
  31125. var data = this.getVerticesData(kind);
  31126. if (data instanceof Float32Array) {
  31127. vertexData.set(new Float32Array(data), kind);
  31128. }
  31129. else {
  31130. vertexData.set(data.slice(0), kind);
  31131. }
  31132. if (!stopChecking) {
  31133. updatable = this.getVertexBuffer(kind).isUpdatable();
  31134. stopChecking = !updatable;
  31135. }
  31136. }
  31137. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31138. geometry.delayLoadState = this.delayLoadState;
  31139. geometry.delayLoadingFile = this.delayLoadingFile;
  31140. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31141. for (kind in this._delayInfo) {
  31142. geometry._delayInfo = geometry._delayInfo || [];
  31143. geometry._delayInfo.push(kind);
  31144. }
  31145. // Bounding info
  31146. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31147. return geometry;
  31148. };
  31149. Geometry.prototype.serialize = function () {
  31150. var serializationObject = {};
  31151. serializationObject.id = this.id;
  31152. if (BABYLON.Tags.HasTags(this)) {
  31153. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31154. }
  31155. return serializationObject;
  31156. };
  31157. Geometry.prototype.serializeVerticeData = function () {
  31158. var serializationObject = this.serialize();
  31159. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31160. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31161. }
  31162. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31163. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31164. }
  31165. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31166. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31167. }
  31168. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31169. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31170. }
  31171. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31172. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31173. }
  31174. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31175. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31176. }
  31177. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31178. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31179. }
  31180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31181. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31182. }
  31183. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31184. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31185. }
  31186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31187. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31188. serializationObject.matricesIndices._isExpanded = true;
  31189. }
  31190. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31191. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31192. }
  31193. serializationObject.indices = this.getIndices();
  31194. return serializationObject;
  31195. };
  31196. // Statics
  31197. Geometry.ExtractFromMesh = function (mesh, id) {
  31198. var geometry = mesh._geometry;
  31199. if (!geometry) {
  31200. return null;
  31201. }
  31202. return geometry.copy(id);
  31203. };
  31204. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31205. // be aware Math.random() could cause collisions
  31206. Geometry.RandomId = function () {
  31207. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31208. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31209. return v.toString(16);
  31210. });
  31211. };
  31212. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31213. var scene = mesh.getScene();
  31214. // Geometry
  31215. var geometryId = parsedGeometry.geometryId;
  31216. if (geometryId) {
  31217. var geometry = scene.getGeometryByID(geometryId);
  31218. if (geometry) {
  31219. geometry.applyToMesh(mesh);
  31220. }
  31221. }
  31222. else if (parsedGeometry instanceof ArrayBuffer) {
  31223. var binaryInfo = mesh._binaryInfo;
  31224. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31225. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31226. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31227. }
  31228. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31229. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31230. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31231. }
  31232. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31233. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31234. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31235. }
  31236. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31237. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31238. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31239. }
  31240. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31241. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31242. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31243. }
  31244. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31245. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31246. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31247. }
  31248. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31249. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31250. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31251. }
  31252. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31253. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31254. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31255. }
  31256. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31257. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31258. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31259. }
  31260. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31261. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31262. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31263. }
  31264. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31265. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31266. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31267. }
  31268. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31269. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31270. mesh.setIndices(indicesData);
  31271. }
  31272. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31273. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31274. mesh.subMeshes = [];
  31275. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31276. var materialIndex = subMeshesData[(i * 5) + 0];
  31277. var verticesStart = subMeshesData[(i * 5) + 1];
  31278. var verticesCount = subMeshesData[(i * 5) + 2];
  31279. var indexStart = subMeshesData[(i * 5) + 3];
  31280. var indexCount = subMeshesData[(i * 5) + 4];
  31281. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31282. }
  31283. }
  31284. }
  31285. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31286. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31287. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31288. if (parsedGeometry.uvs) {
  31289. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31290. }
  31291. if (parsedGeometry.uvs2) {
  31292. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31293. }
  31294. if (parsedGeometry.uvs3) {
  31295. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31296. }
  31297. if (parsedGeometry.uvs4) {
  31298. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31299. }
  31300. if (parsedGeometry.uvs5) {
  31301. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31302. }
  31303. if (parsedGeometry.uvs6) {
  31304. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31305. }
  31306. if (parsedGeometry.colors) {
  31307. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31308. }
  31309. if (parsedGeometry.matricesIndices) {
  31310. if (!parsedGeometry.matricesIndices._isExpanded) {
  31311. var floatIndices = [];
  31312. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31313. var matricesIndex = parsedGeometry.matricesIndices[i];
  31314. floatIndices.push(matricesIndex & 0x000000FF);
  31315. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31316. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31317. floatIndices.push(matricesIndex >> 24);
  31318. }
  31319. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31320. }
  31321. else {
  31322. delete parsedGeometry.matricesIndices._isExpanded;
  31323. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31324. }
  31325. }
  31326. if (parsedGeometry.matricesIndicesExtra) {
  31327. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31328. var floatIndices = [];
  31329. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31330. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31331. floatIndices.push(matricesIndex & 0x000000FF);
  31332. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31333. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31334. floatIndices.push(matricesIndex >> 24);
  31335. }
  31336. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31337. }
  31338. else {
  31339. delete parsedGeometry.matricesIndices._isExpanded;
  31340. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31341. }
  31342. }
  31343. if (parsedGeometry.matricesWeights) {
  31344. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31345. }
  31346. if (parsedGeometry.matricesWeightsExtra) {
  31347. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31348. }
  31349. mesh.setIndices(parsedGeometry.indices);
  31350. }
  31351. // SubMeshes
  31352. if (parsedGeometry.subMeshes) {
  31353. mesh.subMeshes = [];
  31354. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31355. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31356. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31357. }
  31358. }
  31359. // Flat shading
  31360. if (mesh._shouldGenerateFlatShading) {
  31361. mesh.convertToFlatShadedMesh();
  31362. delete mesh._shouldGenerateFlatShading;
  31363. }
  31364. // Update
  31365. mesh.computeWorldMatrix(true);
  31366. // Octree
  31367. if (scene['_selectionOctree']) {
  31368. scene['_selectionOctree'].addMesh(mesh);
  31369. }
  31370. };
  31371. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31372. if (scene.getGeometryByID(parsedVertexData.id)) {
  31373. return null; // null since geometry could be something else than a box...
  31374. }
  31375. var geometry = new Geometry(parsedVertexData.id, scene);
  31376. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31377. if (parsedVertexData.delayLoadingFile) {
  31378. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31379. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31380. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31381. geometry._delayInfo = [];
  31382. if (parsedVertexData.hasUVs) {
  31383. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31384. }
  31385. if (parsedVertexData.hasUVs2) {
  31386. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31387. }
  31388. if (parsedVertexData.hasUVs3) {
  31389. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31390. }
  31391. if (parsedVertexData.hasUVs4) {
  31392. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31393. }
  31394. if (parsedVertexData.hasUVs5) {
  31395. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31396. }
  31397. if (parsedVertexData.hasUVs6) {
  31398. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31399. }
  31400. if (parsedVertexData.hasColors) {
  31401. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31402. }
  31403. if (parsedVertexData.hasMatricesIndices) {
  31404. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31405. }
  31406. if (parsedVertexData.hasMatricesWeights) {
  31407. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31408. }
  31409. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31410. }
  31411. else {
  31412. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31413. }
  31414. scene.pushGeometry(geometry, true);
  31415. return geometry;
  31416. };
  31417. return Geometry;
  31418. }());
  31419. BABYLON.Geometry = Geometry;
  31420. /////// Primitives //////////////////////////////////////////////
  31421. var Geometry;
  31422. (function (Geometry) {
  31423. var Primitives;
  31424. (function (Primitives) {
  31425. /// Abstract class
  31426. var _Primitive = (function (_super) {
  31427. __extends(_Primitive, _super);
  31428. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31429. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31430. this._canBeRegenerated = _canBeRegenerated;
  31431. this._beingRegenerated = true;
  31432. this.regenerate();
  31433. this._beingRegenerated = false;
  31434. }
  31435. _Primitive.prototype.canBeRegenerated = function () {
  31436. return this._canBeRegenerated;
  31437. };
  31438. _Primitive.prototype.regenerate = function () {
  31439. if (!this._canBeRegenerated) {
  31440. return;
  31441. }
  31442. this._beingRegenerated = true;
  31443. this.setAllVerticesData(this._regenerateVertexData(), false);
  31444. this._beingRegenerated = false;
  31445. };
  31446. _Primitive.prototype.asNewGeometry = function (id) {
  31447. return _super.prototype.copy.call(this, id);
  31448. };
  31449. // overrides
  31450. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31451. if (!this._beingRegenerated) {
  31452. return;
  31453. }
  31454. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31455. };
  31456. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31457. if (!this._beingRegenerated) {
  31458. return;
  31459. }
  31460. _super.prototype.setVerticesData.call(this, kind, data, false);
  31461. };
  31462. // to override
  31463. // protected
  31464. _Primitive.prototype._regenerateVertexData = function () {
  31465. throw new Error("Abstract method");
  31466. };
  31467. _Primitive.prototype.copy = function (id) {
  31468. throw new Error("Must be overriden in sub-classes.");
  31469. };
  31470. _Primitive.prototype.serialize = function () {
  31471. var serializationObject = _super.prototype.serialize.call(this);
  31472. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31473. return serializationObject;
  31474. };
  31475. return _Primitive;
  31476. }(Geometry));
  31477. Primitives._Primitive = _Primitive;
  31478. var Ribbon = (function (_super) {
  31479. __extends(Ribbon, _super);
  31480. // Members
  31481. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31482. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31483. _super.call(this, id, scene, canBeRegenerated, mesh);
  31484. this.pathArray = pathArray;
  31485. this.closeArray = closeArray;
  31486. this.closePath = closePath;
  31487. this.offset = offset;
  31488. this.side = side;
  31489. }
  31490. Ribbon.prototype._regenerateVertexData = function () {
  31491. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31492. };
  31493. Ribbon.prototype.copy = function (id) {
  31494. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31495. };
  31496. return Ribbon;
  31497. }(_Primitive));
  31498. Primitives.Ribbon = Ribbon;
  31499. var Box = (function (_super) {
  31500. __extends(Box, _super);
  31501. // Members
  31502. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31503. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31504. _super.call(this, id, scene, canBeRegenerated, mesh);
  31505. this.size = size;
  31506. this.side = side;
  31507. }
  31508. Box.prototype._regenerateVertexData = function () {
  31509. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31510. };
  31511. Box.prototype.copy = function (id) {
  31512. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31513. };
  31514. Box.prototype.serialize = function () {
  31515. var serializationObject = _super.prototype.serialize.call(this);
  31516. serializationObject.size = this.size;
  31517. return serializationObject;
  31518. };
  31519. Box.Parse = function (parsedBox, scene) {
  31520. if (scene.getGeometryByID(parsedBox.id)) {
  31521. return null; // null since geometry could be something else than a box...
  31522. }
  31523. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31524. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31525. scene.pushGeometry(box, true);
  31526. return box;
  31527. };
  31528. return Box;
  31529. }(_Primitive));
  31530. Primitives.Box = Box;
  31531. var Sphere = (function (_super) {
  31532. __extends(Sphere, _super);
  31533. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31535. _super.call(this, id, scene, canBeRegenerated, mesh);
  31536. this.segments = segments;
  31537. this.diameter = diameter;
  31538. this.side = side;
  31539. }
  31540. Sphere.prototype._regenerateVertexData = function () {
  31541. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31542. };
  31543. Sphere.prototype.copy = function (id) {
  31544. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31545. };
  31546. Sphere.prototype.serialize = function () {
  31547. var serializationObject = _super.prototype.serialize.call(this);
  31548. serializationObject.segments = this.segments;
  31549. serializationObject.diameter = this.diameter;
  31550. return serializationObject;
  31551. };
  31552. Sphere.Parse = function (parsedSphere, scene) {
  31553. if (scene.getGeometryByID(parsedSphere.id)) {
  31554. return null; // null since geometry could be something else than a sphere...
  31555. }
  31556. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31557. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31558. scene.pushGeometry(sphere, true);
  31559. return sphere;
  31560. };
  31561. return Sphere;
  31562. }(_Primitive));
  31563. Primitives.Sphere = Sphere;
  31564. var Disc = (function (_super) {
  31565. __extends(Disc, _super);
  31566. // Members
  31567. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31568. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31569. _super.call(this, id, scene, canBeRegenerated, mesh);
  31570. this.radius = radius;
  31571. this.tessellation = tessellation;
  31572. this.side = side;
  31573. }
  31574. Disc.prototype._regenerateVertexData = function () {
  31575. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31576. };
  31577. Disc.prototype.copy = function (id) {
  31578. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31579. };
  31580. return Disc;
  31581. }(_Primitive));
  31582. Primitives.Disc = Disc;
  31583. var Cylinder = (function (_super) {
  31584. __extends(Cylinder, _super);
  31585. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31586. if (subdivisions === void 0) { subdivisions = 1; }
  31587. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31588. _super.call(this, id, scene, canBeRegenerated, mesh);
  31589. this.height = height;
  31590. this.diameterTop = diameterTop;
  31591. this.diameterBottom = diameterBottom;
  31592. this.tessellation = tessellation;
  31593. this.subdivisions = subdivisions;
  31594. this.side = side;
  31595. }
  31596. Cylinder.prototype._regenerateVertexData = function () {
  31597. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31598. };
  31599. Cylinder.prototype.copy = function (id) {
  31600. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31601. };
  31602. Cylinder.prototype.serialize = function () {
  31603. var serializationObject = _super.prototype.serialize.call(this);
  31604. serializationObject.height = this.height;
  31605. serializationObject.diameterTop = this.diameterTop;
  31606. serializationObject.diameterBottom = this.diameterBottom;
  31607. serializationObject.tessellation = this.tessellation;
  31608. return serializationObject;
  31609. };
  31610. Cylinder.Parse = function (parsedCylinder, scene) {
  31611. if (scene.getGeometryByID(parsedCylinder.id)) {
  31612. return null; // null since geometry could be something else than a cylinder...
  31613. }
  31614. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31615. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31616. scene.pushGeometry(cylinder, true);
  31617. return cylinder;
  31618. };
  31619. return Cylinder;
  31620. }(_Primitive));
  31621. Primitives.Cylinder = Cylinder;
  31622. var Torus = (function (_super) {
  31623. __extends(Torus, _super);
  31624. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31626. _super.call(this, id, scene, canBeRegenerated, mesh);
  31627. this.diameter = diameter;
  31628. this.thickness = thickness;
  31629. this.tessellation = tessellation;
  31630. this.side = side;
  31631. }
  31632. Torus.prototype._regenerateVertexData = function () {
  31633. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31634. };
  31635. Torus.prototype.copy = function (id) {
  31636. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31637. };
  31638. Torus.prototype.serialize = function () {
  31639. var serializationObject = _super.prototype.serialize.call(this);
  31640. serializationObject.diameter = this.diameter;
  31641. serializationObject.thickness = this.thickness;
  31642. serializationObject.tessellation = this.tessellation;
  31643. return serializationObject;
  31644. };
  31645. Torus.Parse = function (parsedTorus, scene) {
  31646. if (scene.getGeometryByID(parsedTorus.id)) {
  31647. return null; // null since geometry could be something else than a torus...
  31648. }
  31649. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31650. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31651. scene.pushGeometry(torus, true);
  31652. return torus;
  31653. };
  31654. return Torus;
  31655. }(_Primitive));
  31656. Primitives.Torus = Torus;
  31657. var Ground = (function (_super) {
  31658. __extends(Ground, _super);
  31659. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31660. _super.call(this, id, scene, canBeRegenerated, mesh);
  31661. this.width = width;
  31662. this.height = height;
  31663. this.subdivisions = subdivisions;
  31664. }
  31665. Ground.prototype._regenerateVertexData = function () {
  31666. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31667. };
  31668. Ground.prototype.copy = function (id) {
  31669. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31670. };
  31671. Ground.prototype.serialize = function () {
  31672. var serializationObject = _super.prototype.serialize.call(this);
  31673. serializationObject.width = this.width;
  31674. serializationObject.height = this.height;
  31675. serializationObject.subdivisions = this.subdivisions;
  31676. return serializationObject;
  31677. };
  31678. Ground.Parse = function (parsedGround, scene) {
  31679. if (scene.getGeometryByID(parsedGround.id)) {
  31680. return null; // null since geometry could be something else than a ground...
  31681. }
  31682. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31683. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31684. scene.pushGeometry(ground, true);
  31685. return ground;
  31686. };
  31687. return Ground;
  31688. }(_Primitive));
  31689. Primitives.Ground = Ground;
  31690. var TiledGround = (function (_super) {
  31691. __extends(TiledGround, _super);
  31692. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31693. _super.call(this, id, scene, canBeRegenerated, mesh);
  31694. this.xmin = xmin;
  31695. this.zmin = zmin;
  31696. this.xmax = xmax;
  31697. this.zmax = zmax;
  31698. this.subdivisions = subdivisions;
  31699. this.precision = precision;
  31700. }
  31701. TiledGround.prototype._regenerateVertexData = function () {
  31702. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31703. };
  31704. TiledGround.prototype.copy = function (id) {
  31705. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31706. };
  31707. return TiledGround;
  31708. }(_Primitive));
  31709. Primitives.TiledGround = TiledGround;
  31710. var Plane = (function (_super) {
  31711. __extends(Plane, _super);
  31712. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31714. _super.call(this, id, scene, canBeRegenerated, mesh);
  31715. this.size = size;
  31716. this.side = side;
  31717. }
  31718. Plane.prototype._regenerateVertexData = function () {
  31719. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31720. };
  31721. Plane.prototype.copy = function (id) {
  31722. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31723. };
  31724. Plane.prototype.serialize = function () {
  31725. var serializationObject = _super.prototype.serialize.call(this);
  31726. serializationObject.size = this.size;
  31727. return serializationObject;
  31728. };
  31729. Plane.Parse = function (parsedPlane, scene) {
  31730. if (scene.getGeometryByID(parsedPlane.id)) {
  31731. return null; // null since geometry could be something else than a ground...
  31732. }
  31733. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31734. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31735. scene.pushGeometry(plane, true);
  31736. return plane;
  31737. };
  31738. return Plane;
  31739. }(_Primitive));
  31740. Primitives.Plane = Plane;
  31741. var TorusKnot = (function (_super) {
  31742. __extends(TorusKnot, _super);
  31743. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31745. _super.call(this, id, scene, canBeRegenerated, mesh);
  31746. this.radius = radius;
  31747. this.tube = tube;
  31748. this.radialSegments = radialSegments;
  31749. this.tubularSegments = tubularSegments;
  31750. this.p = p;
  31751. this.q = q;
  31752. this.side = side;
  31753. }
  31754. TorusKnot.prototype._regenerateVertexData = function () {
  31755. 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 });
  31756. };
  31757. TorusKnot.prototype.copy = function (id) {
  31758. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31759. };
  31760. TorusKnot.prototype.serialize = function () {
  31761. var serializationObject = _super.prototype.serialize.call(this);
  31762. serializationObject.radius = this.radius;
  31763. serializationObject.tube = this.tube;
  31764. serializationObject.radialSegments = this.radialSegments;
  31765. serializationObject.tubularSegments = this.tubularSegments;
  31766. serializationObject.p = this.p;
  31767. serializationObject.q = this.q;
  31768. return serializationObject;
  31769. };
  31770. ;
  31771. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31772. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31773. return null; // null since geometry could be something else than a ground...
  31774. }
  31775. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31776. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31777. scene.pushGeometry(torusKnot, true);
  31778. return torusKnot;
  31779. };
  31780. return TorusKnot;
  31781. }(_Primitive));
  31782. Primitives.TorusKnot = TorusKnot;
  31783. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31784. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31785. })(BABYLON || (BABYLON = {}));
  31786. var BABYLON;
  31787. (function (BABYLON) {
  31788. var GroundMesh = (function (_super) {
  31789. __extends(GroundMesh, _super);
  31790. function GroundMesh(name, scene) {
  31791. _super.call(this, name, scene);
  31792. this.generateOctree = false;
  31793. this._worldInverse = new BABYLON.Matrix();
  31794. }
  31795. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31796. get: function () {
  31797. return this._subdivisions;
  31798. },
  31799. enumerable: true,
  31800. configurable: true
  31801. });
  31802. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31803. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31804. this._subdivisions = chunksCount;
  31805. this.subdivide(this._subdivisions);
  31806. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31807. };
  31808. /**
  31809. * Returns a height (y) value in the Worl system :
  31810. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31811. * Returns the ground y position if (x, z) are outside the ground surface.
  31812. * Not pertinent if the ground is rotated.
  31813. */
  31814. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31815. // express x and y in the ground local system
  31816. x -= this.position.x;
  31817. z -= this.position.z;
  31818. x /= this.scaling.x;
  31819. z /= this.scaling.z;
  31820. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31821. return this.position.y;
  31822. }
  31823. if (!this._heightQuads || this._heightQuads.length == 0) {
  31824. this._initHeightQuads();
  31825. this._computeHeightQuads();
  31826. }
  31827. var facet = this._getFacetAt(x, z);
  31828. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31829. // return y in the World system
  31830. return y * this.scaling.y + this.position.y;
  31831. };
  31832. /**
  31833. * Returns a normalized vector (Vector3) orthogonal to the ground
  31834. * at the ground coordinates (x, z) expressed in the World system.
  31835. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  31836. * Not pertinent if the ground is rotated.
  31837. */
  31838. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  31839. var normal = new BABYLON.Vector3(0, 1, 0);
  31840. this.getNormalAtCoordinatesToRef(x, z, normal);
  31841. return normal;
  31842. };
  31843. /**
  31844. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  31845. * at the ground coordinates (x, z) expressed in the World system.
  31846. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  31847. * Not pertinent if the ground is rotated.
  31848. */
  31849. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  31850. // express x and y in the ground local system
  31851. x -= this.position.x;
  31852. z -= this.position.z;
  31853. x /= this.scaling.x;
  31854. z /= this.scaling.z;
  31855. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31856. return;
  31857. }
  31858. if (!this._heightQuads || this._heightQuads.length == 0) {
  31859. this._initHeightQuads();
  31860. this._computeHeightQuads();
  31861. }
  31862. var facet = this._getFacetAt(x, z);
  31863. ref.x = facet.x;
  31864. ref.y = facet.y;
  31865. ref.z = facet.z;
  31866. };
  31867. /**
  31868. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  31869. * if the ground has been updated.
  31870. * This can be used in the render loop
  31871. */
  31872. GroundMesh.prototype.updateCoordinateHeights = function () {
  31873. if (!this._heightQuads || this._heightQuads.length == 0) {
  31874. this._initHeightQuads();
  31875. }
  31876. this._computeHeightQuads();
  31877. };
  31878. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  31879. GroundMesh.prototype._getFacetAt = function (x, z) {
  31880. // retrieve col and row from x, z coordinates in the ground local system
  31881. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  31882. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  31883. var quad = this._heightQuads[row * this._subdivisions + col];
  31884. var facet;
  31885. if (z < quad.slope.x * x + quad.slope.y) {
  31886. facet = quad.facet1;
  31887. }
  31888. else {
  31889. facet = quad.facet2;
  31890. }
  31891. return facet;
  31892. };
  31893. // Creates and populates the heightMap array with "facet" elements :
  31894. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  31895. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31896. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31897. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31898. GroundMesh.prototype._initHeightQuads = function () {
  31899. this._heightQuads = new Array();
  31900. for (var row = 0; row < this._subdivisions; row++) {
  31901. for (var col = 0; col < this._subdivisions; col++) {
  31902. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  31903. this._heightQuads[row * this._subdivisions + col] = quad;
  31904. }
  31905. }
  31906. };
  31907. // Compute each quad element values and update the the heightMap array :
  31908. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31909. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31910. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31911. GroundMesh.prototype._computeHeightQuads = function () {
  31912. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31913. var v1 = BABYLON.Tmp.Vector3[0];
  31914. var v2 = BABYLON.Tmp.Vector3[1];
  31915. var v3 = BABYLON.Tmp.Vector3[2];
  31916. var v4 = BABYLON.Tmp.Vector3[3];
  31917. var v1v2 = BABYLON.Tmp.Vector3[4];
  31918. var v1v3 = BABYLON.Tmp.Vector3[5];
  31919. var v1v4 = BABYLON.Tmp.Vector3[6];
  31920. var norm1 = BABYLON.Tmp.Vector3[7];
  31921. var norm2 = BABYLON.Tmp.Vector3[8];
  31922. var i = 0;
  31923. var j = 0;
  31924. var k = 0;
  31925. var cd = 0; // 2D slope coefficient : z = cd * x + h
  31926. var h = 0;
  31927. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  31928. var d2 = 0;
  31929. for (var row = 0; row < this._subdivisions; row++) {
  31930. for (var col = 0; col < this._subdivisions; col++) {
  31931. i = col * 3;
  31932. j = row * (this._subdivisions + 1) * 3;
  31933. k = (row + 1) * (this._subdivisions + 1) * 3;
  31934. v1.x = positions[j + i];
  31935. v1.y = positions[j + i + 1];
  31936. v1.z = positions[j + i + 2];
  31937. v2.x = positions[j + i + 3];
  31938. v2.y = positions[j + i + 4];
  31939. v2.z = positions[j + i + 5];
  31940. v3.x = positions[k + i];
  31941. v3.y = positions[k + i + 1];
  31942. v3.z = positions[k + i + 2];
  31943. v4.x = positions[k + i + 3];
  31944. v4.y = positions[k + i + 4];
  31945. v4.z = positions[k + i + 5];
  31946. // 2D slope V1V4
  31947. cd = (v4.z - v1.z) / (v4.x - v1.x);
  31948. h = v1.z - cd * v1.x; // v1 belongs to the slope
  31949. // facet equations :
  31950. // we compute each facet normal vector
  31951. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  31952. // we compute the value d by applying the equation to v1 which belongs to the plane
  31953. // then we store the facet equation in a Vector4
  31954. v2.subtractToRef(v1, v1v2);
  31955. v3.subtractToRef(v1, v1v3);
  31956. v4.subtractToRef(v1, v1v4);
  31957. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  31958. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  31959. norm1.normalize();
  31960. norm2.normalize();
  31961. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  31962. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  31963. var quad = this._heightQuads[row * this._subdivisions + col];
  31964. quad.slope.copyFromFloats(cd, h);
  31965. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  31966. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  31967. }
  31968. }
  31969. };
  31970. return GroundMesh;
  31971. }(BABYLON.Mesh));
  31972. BABYLON.GroundMesh = GroundMesh;
  31973. })(BABYLON || (BABYLON = {}));
  31974. var BABYLON;
  31975. (function (BABYLON) {
  31976. var LinesMesh = (function (_super) {
  31977. __extends(LinesMesh, _super);
  31978. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  31979. if (parent === void 0) { parent = null; }
  31980. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  31981. this.color = new BABYLON.Color3(1, 1, 1);
  31982. this.alpha = 1;
  31983. this._intersectionThreshold = 0.1;
  31984. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  31985. attributes: ["position"],
  31986. uniforms: ["worldViewProjection", "color"],
  31987. needAlphaBlending: true
  31988. });
  31989. }
  31990. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  31991. /**
  31992. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  31993. * This margin is expressed in world space coordinates, so its value may vary.
  31994. * Default value is 0.1
  31995. * @returns the intersection Threshold value.
  31996. */
  31997. get: function () {
  31998. return this._intersectionThreshold;
  31999. },
  32000. /**
  32001. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32002. * This margin is expressed in world space coordinates, so its value may vary.
  32003. * @param value the new threshold to apply
  32004. */
  32005. set: function (value) {
  32006. if (this._intersectionThreshold === value) {
  32007. return;
  32008. }
  32009. this._intersectionThreshold = value;
  32010. if (this.geometry) {
  32011. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32012. }
  32013. },
  32014. enumerable: true,
  32015. configurable: true
  32016. });
  32017. Object.defineProperty(LinesMesh.prototype, "material", {
  32018. get: function () {
  32019. return this._colorShader;
  32020. },
  32021. enumerable: true,
  32022. configurable: true
  32023. });
  32024. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  32025. get: function () {
  32026. return true;
  32027. },
  32028. enumerable: true,
  32029. configurable: true
  32030. });
  32031. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32032. get: function () {
  32033. return false;
  32034. },
  32035. enumerable: true,
  32036. configurable: true
  32037. });
  32038. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32039. var engine = this.getScene().getEngine();
  32040. var indexToBind = this._geometry.getIndexBuffer();
  32041. // VBOs
  32042. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32043. // Color
  32044. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32045. };
  32046. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32047. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32048. return;
  32049. }
  32050. var engine = this.getScene().getEngine();
  32051. // Draw order
  32052. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32053. };
  32054. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32055. this._colorShader.dispose();
  32056. _super.prototype.dispose.call(this, doNotRecurse);
  32057. };
  32058. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32059. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32060. };
  32061. return LinesMesh;
  32062. }(BABYLON.Mesh));
  32063. BABYLON.LinesMesh = LinesMesh;
  32064. })(BABYLON || (BABYLON = {}));
  32065. var BABYLON;
  32066. (function (BABYLON) {
  32067. var DebugLayer = (function () {
  32068. function DebugLayer(scene) {
  32069. var _this = this;
  32070. this._transformationMatrix = BABYLON.Matrix.Identity();
  32071. this._enabled = false;
  32072. this._labelsEnabled = false;
  32073. this._displayStatistics = true;
  32074. this._displayTree = false;
  32075. this._displayLogs = false;
  32076. this._skeletonViewers = new Array();
  32077. this._identityMatrix = BABYLON.Matrix.Identity();
  32078. this.axisRatio = 0.02;
  32079. this.accentColor = "orange";
  32080. this._scene = scene;
  32081. this._syncPositions = function () {
  32082. var engine = _this._scene.getEngine();
  32083. var canvasRect = engine.getRenderingCanvasClientRect();
  32084. if (_this._showUI) {
  32085. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32086. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32087. _this._statsDiv.style.width = "400px";
  32088. _this._statsDiv.style.height = "auto";
  32089. _this._statsSubsetDiv.style.maxHeight = "240px";
  32090. _this._optionsDiv.style.left = "0px";
  32091. _this._optionsDiv.style.top = "10px";
  32092. _this._optionsDiv.style.width = "200px";
  32093. _this._optionsDiv.style.height = "auto";
  32094. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32095. _this._logDiv.style.left = "0px";
  32096. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32097. _this._logDiv.style.width = "600px";
  32098. _this._logDiv.style.height = "160px";
  32099. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32100. _this._treeDiv.style.top = "10px";
  32101. _this._treeDiv.style.width = "300px";
  32102. _this._treeDiv.style.height = "auto";
  32103. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32104. }
  32105. _this._globalDiv.style.left = canvasRect.left + "px";
  32106. _this._globalDiv.style.top = canvasRect.top + "px";
  32107. _this._drawingCanvas.style.left = "0px";
  32108. _this._drawingCanvas.style.top = "0px";
  32109. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32110. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32111. var devicePixelRatio = window.devicePixelRatio || 1;
  32112. var context = _this._drawingContext;
  32113. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32114. context.mozBackingStorePixelRatio ||
  32115. context.msBackingStorePixelRatio ||
  32116. context.oBackingStorePixelRatio ||
  32117. context.backingStorePixelRatio || 1;
  32118. _this._ratio = devicePixelRatio / backingStoreRatio;
  32119. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32120. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32121. };
  32122. this._onCanvasClick = function (evt) {
  32123. _this._clickPosition = {
  32124. x: evt.clientX * _this._ratio,
  32125. y: evt.clientY * _this._ratio
  32126. };
  32127. };
  32128. this._syncUI = function () {
  32129. if (_this._showUI) {
  32130. if (_this._displayStatistics) {
  32131. _this._displayStats();
  32132. _this._statsDiv.style.display = "";
  32133. }
  32134. else {
  32135. _this._statsDiv.style.display = "none";
  32136. }
  32137. if (_this._displayLogs) {
  32138. _this._logDiv.style.display = "";
  32139. }
  32140. else {
  32141. _this._logDiv.style.display = "none";
  32142. }
  32143. if (_this._displayTree) {
  32144. _this._treeDiv.style.display = "";
  32145. if (_this._needToRefreshMeshesTree) {
  32146. _this._needToRefreshMeshesTree = false;
  32147. _this._refreshMeshesTreeContent();
  32148. }
  32149. }
  32150. else {
  32151. _this._treeDiv.style.display = "none";
  32152. }
  32153. }
  32154. };
  32155. this._syncData = function () {
  32156. if (_this._labelsEnabled || !_this._showUI) {
  32157. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32158. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32159. var engine = _this._scene.getEngine();
  32160. var viewport = _this._camera.viewport;
  32161. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32162. // Meshes
  32163. var meshes = _this._camera.getActiveMeshes();
  32164. var index;
  32165. var projectedPosition;
  32166. for (index = 0; index < meshes.length; index++) {
  32167. var mesh = meshes.data[index];
  32168. var position = mesh.getBoundingInfo().boundingSphere.center;
  32169. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32170. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32171. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32172. }
  32173. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32174. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32175. }
  32176. }
  32177. // Cameras
  32178. var cameras = _this._scene.cameras;
  32179. for (index = 0; index < cameras.length; index++) {
  32180. var camera = cameras[index];
  32181. if (camera === _this._camera) {
  32182. continue;
  32183. }
  32184. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32185. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32186. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32187. _this._camera.detachControl(engine.getRenderingCanvas());
  32188. _this._camera = camera;
  32189. _this._camera.attachControl(engine.getRenderingCanvas());
  32190. }, function () { return "purple"; });
  32191. }
  32192. }
  32193. // Lights
  32194. var lights = _this._scene.lights;
  32195. for (index = 0; index < lights.length; index++) {
  32196. var light = lights[index];
  32197. if (light.position) {
  32198. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32199. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32200. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32201. light.setEnabled(!light.isEnabled());
  32202. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32203. }
  32204. }
  32205. }
  32206. }
  32207. _this._clickPosition = undefined;
  32208. };
  32209. }
  32210. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32211. while (this._treeSubsetDiv.hasChildNodes()) {
  32212. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32213. }
  32214. // Add meshes
  32215. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32216. sortedArray.sort(function (a, b) {
  32217. if (a.name === b.name) {
  32218. return 0;
  32219. }
  32220. return (a.name > b.name) ? 1 : -1;
  32221. });
  32222. for (var index = 0; index < sortedArray.length; index++) {
  32223. var mesh = sortedArray[index];
  32224. if (!mesh.isEnabled()) {
  32225. continue;
  32226. }
  32227. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32228. m.isVisible = element.checked;
  32229. }, mesh);
  32230. }
  32231. };
  32232. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32233. this._drawingContext.beginPath();
  32234. this._drawingContext.moveTo(zero.x, zero.y);
  32235. this._drawingContext.lineTo(unit.x, unit.y);
  32236. this._drawingContext.strokeStyle = color;
  32237. this._drawingContext.lineWidth = 4;
  32238. this._drawingContext.stroke();
  32239. this._drawingContext.font = "normal 14px Segoe UI";
  32240. this._drawingContext.fillStyle = color;
  32241. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32242. };
  32243. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32244. var position = mesh.getBoundingInfo().boundingSphere.center;
  32245. var worldMatrix = mesh.getWorldMatrix();
  32246. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32247. var unit = (unprojectedVector.subtract(position)).length();
  32248. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32249. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32250. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32251. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32252. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32253. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32254. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32255. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32256. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32257. };
  32258. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32259. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32260. this._drawingContext.font = "normal 12px Segoe UI";
  32261. var textMetrics = this._drawingContext.measureText(text);
  32262. var centerX = projectedPosition.x - textMetrics.width / 2;
  32263. var centerY = projectedPosition.y;
  32264. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32265. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32266. onClick();
  32267. }
  32268. this._drawingContext.beginPath();
  32269. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32270. this._drawingContext.fillStyle = getFillStyle();
  32271. this._drawingContext.globalAlpha = 0.5;
  32272. this._drawingContext.fill();
  32273. this._drawingContext.globalAlpha = 1.0;
  32274. this._drawingContext.strokeStyle = '#FFFFFF';
  32275. this._drawingContext.lineWidth = 1;
  32276. this._drawingContext.stroke();
  32277. this._drawingContext.fillStyle = "#FFFFFF";
  32278. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32279. this._drawingContext.beginPath();
  32280. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32281. this._drawingContext.fill();
  32282. }
  32283. };
  32284. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32285. if (!this._clickPosition) {
  32286. return false;
  32287. }
  32288. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32289. return false;
  32290. }
  32291. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32292. return false;
  32293. }
  32294. return true;
  32295. };
  32296. DebugLayer.prototype.isVisible = function () {
  32297. return this._enabled;
  32298. };
  32299. DebugLayer.prototype.hide = function () {
  32300. if (!this._enabled) {
  32301. return;
  32302. }
  32303. this._enabled = false;
  32304. var engine = this._scene.getEngine();
  32305. this._scene.unregisterBeforeRender(this._syncData);
  32306. this._scene.unregisterAfterRender(this._syncUI);
  32307. this._rootElement.removeChild(this._globalDiv);
  32308. this._scene.forceShowBoundingBoxes = false;
  32309. this._scene.forceWireframe = false;
  32310. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32311. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32312. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32313. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32314. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32315. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32316. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32317. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32318. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32319. this._scene.shadowsEnabled = true;
  32320. this._scene.particlesEnabled = true;
  32321. this._scene.postProcessesEnabled = true;
  32322. this._scene.collisionsEnabled = true;
  32323. this._scene.lightsEnabled = true;
  32324. this._scene.texturesEnabled = true;
  32325. this._scene.lensFlaresEnabled = true;
  32326. this._scene.proceduralTexturesEnabled = true;
  32327. this._scene.renderTargetsEnabled = true;
  32328. this._scene.probesEnabled = true;
  32329. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32330. this._clearSkeletonViewers();
  32331. };
  32332. DebugLayer.prototype._clearSkeletonViewers = function () {
  32333. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32334. this._skeletonViewers[index].dispose();
  32335. }
  32336. this._skeletonViewers = [];
  32337. };
  32338. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32339. if (showUI === void 0) { showUI = true; }
  32340. if (camera === void 0) { camera = null; }
  32341. if (rootElement === void 0) { rootElement = null; }
  32342. if (this._enabled) {
  32343. return;
  32344. }
  32345. this._enabled = true;
  32346. if (camera) {
  32347. this._camera = camera;
  32348. }
  32349. else {
  32350. this._camera = this._scene.activeCamera;
  32351. }
  32352. this._showUI = showUI;
  32353. var engine = this._scene.getEngine();
  32354. this._globalDiv = document.createElement("div");
  32355. this._rootElement = rootElement || document.body;
  32356. this._rootElement.appendChild(this._globalDiv);
  32357. this._generateDOMelements();
  32358. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32359. this._syncPositions();
  32360. this._scene.registerBeforeRender(this._syncData);
  32361. this._scene.registerAfterRender(this._syncUI);
  32362. };
  32363. DebugLayer.prototype._clearLabels = function () {
  32364. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32365. for (var index = 0; index < this._scene.meshes.length; index++) {
  32366. var mesh = this._scene.meshes[index];
  32367. mesh.renderOverlay = false;
  32368. }
  32369. };
  32370. DebugLayer.prototype._generateheader = function (root, text) {
  32371. var header = document.createElement("div");
  32372. header.innerHTML = text + "&nbsp;";
  32373. header.style.textAlign = "right";
  32374. header.style.width = "100%";
  32375. header.style.color = "white";
  32376. header.style.backgroundColor = "Black";
  32377. header.style.padding = "5px 5px 4px 0px";
  32378. header.style.marginLeft = "-5px";
  32379. header.style.fontWeight = "bold";
  32380. root.appendChild(header);
  32381. };
  32382. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32383. var label = document.createElement("label");
  32384. label.style.display = "inline";
  32385. label.innerHTML = title;
  32386. label.style.color = color;
  32387. root.appendChild(label);
  32388. root.appendChild(document.createElement("br"));
  32389. };
  32390. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32391. if (tag === void 0) { tag = null; }
  32392. var label = document.createElement("label");
  32393. label.style.display = "inline";
  32394. var boundingBoxesCheckbox = document.createElement("input");
  32395. boundingBoxesCheckbox.type = "checkbox";
  32396. boundingBoxesCheckbox.checked = initialState;
  32397. boundingBoxesCheckbox.style.display = "inline";
  32398. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32399. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32400. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32401. task(evt.target, tag);
  32402. });
  32403. label.appendChild(boundingBoxesCheckbox);
  32404. var container = document.createElement("span");
  32405. var leftPart = document.createElement("span");
  32406. var rightPart = document.createElement("span");
  32407. rightPart.style.cssFloat = "right";
  32408. leftPart.innerHTML = leftTitle;
  32409. rightPart.innerHTML = rightTitle;
  32410. rightPart.style.fontSize = "12px";
  32411. rightPart.style.maxWidth = "200px";
  32412. container.appendChild(leftPart);
  32413. container.appendChild(rightPart);
  32414. label.appendChild(container);
  32415. root.appendChild(label);
  32416. root.appendChild(document.createElement("br"));
  32417. };
  32418. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32419. if (tag === void 0) { tag = null; }
  32420. var label = document.createElement("label");
  32421. label.style.display = "inline";
  32422. var checkBox = document.createElement("input");
  32423. checkBox.type = "checkbox";
  32424. checkBox.checked = initialState;
  32425. checkBox.style.display = "inline";
  32426. checkBox.style.margin = "0px 5px 0px 0px";
  32427. checkBox.style.verticalAlign = "sub";
  32428. checkBox.addEventListener("change", function (evt) {
  32429. task(evt.target, tag);
  32430. });
  32431. label.appendChild(checkBox);
  32432. label.appendChild(document.createTextNode(title));
  32433. root.appendChild(label);
  32434. root.appendChild(document.createElement("br"));
  32435. };
  32436. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  32437. if (tag === void 0) { tag = null; }
  32438. var button = document.createElement("button");
  32439. button.innerHTML = title;
  32440. button.style.height = "24px";
  32441. button.style.width = "150px";
  32442. button.style.marginBottom = "5px";
  32443. button.style.color = "#444444";
  32444. button.style.border = "1px solid white";
  32445. button.className = "debugLayerButton";
  32446. button.addEventListener("click", function (evt) {
  32447. task(evt.target, tag);
  32448. });
  32449. root.appendChild(button);
  32450. root.appendChild(document.createElement("br"));
  32451. };
  32452. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32453. if (tag === void 0) { tag = null; }
  32454. var label = document.createElement("label");
  32455. label.style.display = "inline";
  32456. var boundingBoxesRadio = document.createElement("input");
  32457. boundingBoxesRadio.type = "radio";
  32458. boundingBoxesRadio.name = name;
  32459. boundingBoxesRadio.checked = initialState;
  32460. boundingBoxesRadio.style.display = "inline";
  32461. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32462. boundingBoxesRadio.style.verticalAlign = "sub";
  32463. boundingBoxesRadio.addEventListener("change", function (evt) {
  32464. task(evt.target, tag);
  32465. });
  32466. label.appendChild(boundingBoxesRadio);
  32467. label.appendChild(document.createTextNode(title));
  32468. root.appendChild(label);
  32469. root.appendChild(document.createElement("br"));
  32470. };
  32471. DebugLayer.prototype._generateDOMelements = function () {
  32472. var _this = this;
  32473. this._globalDiv.id = "DebugLayer";
  32474. this._globalDiv.style.position = "absolute";
  32475. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32476. this._globalDiv.style.fontSize = "14px";
  32477. this._globalDiv.style.color = "white";
  32478. // Drawing canvas
  32479. this._drawingCanvas = document.createElement("canvas");
  32480. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32481. this._drawingCanvas.style.position = "absolute";
  32482. this._drawingCanvas.style.pointerEvents = "none";
  32483. this._drawingCanvas.style.backgroundColor = "transparent";
  32484. this._drawingContext = this._drawingCanvas.getContext("2d");
  32485. this._globalDiv.appendChild(this._drawingCanvas);
  32486. if (this._showUI) {
  32487. var background = "rgba(128, 128, 128, 0.4)";
  32488. var border = "rgb(180, 180, 180) solid 1px";
  32489. // Stats
  32490. this._statsDiv = document.createElement("div");
  32491. this._statsDiv.id = "DebugLayerStats";
  32492. this._statsDiv.style.border = border;
  32493. this._statsDiv.style.position = "absolute";
  32494. this._statsDiv.style.background = background;
  32495. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32496. this._generateheader(this._statsDiv, "STATISTICS");
  32497. this._statsSubsetDiv = document.createElement("div");
  32498. this._statsSubsetDiv.style.paddingTop = "5px";
  32499. this._statsSubsetDiv.style.paddingBottom = "5px";
  32500. this._statsSubsetDiv.style.overflowY = "auto";
  32501. this._statsDiv.appendChild(this._statsSubsetDiv);
  32502. // Tree
  32503. this._treeDiv = document.createElement("div");
  32504. this._treeDiv.id = "DebugLayerTree";
  32505. this._treeDiv.style.border = border;
  32506. this._treeDiv.style.position = "absolute";
  32507. this._treeDiv.style.background = background;
  32508. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32509. this._treeDiv.style.display = "none";
  32510. this._generateheader(this._treeDiv, "MESHES TREE");
  32511. this._treeSubsetDiv = document.createElement("div");
  32512. this._treeSubsetDiv.style.paddingTop = "5px";
  32513. this._treeSubsetDiv.style.paddingRight = "5px";
  32514. this._treeSubsetDiv.style.overflowY = "auto";
  32515. this._treeSubsetDiv.style.maxHeight = "300px";
  32516. this._treeDiv.appendChild(this._treeSubsetDiv);
  32517. this._needToRefreshMeshesTree = true;
  32518. // Logs
  32519. this._logDiv = document.createElement("div");
  32520. this._logDiv.style.border = border;
  32521. this._logDiv.id = "DebugLayerLogs";
  32522. this._logDiv.style.position = "absolute";
  32523. this._logDiv.style.background = background;
  32524. this._logDiv.style.padding = "0px 0px 0px 5px";
  32525. this._logDiv.style.display = "none";
  32526. this._generateheader(this._logDiv, "LOGS");
  32527. this._logSubsetDiv = document.createElement("div");
  32528. this._logSubsetDiv.style.height = "127px";
  32529. this._logSubsetDiv.style.paddingTop = "5px";
  32530. this._logSubsetDiv.style.overflowY = "auto";
  32531. this._logSubsetDiv.style.fontSize = "12px";
  32532. this._logSubsetDiv.style.fontFamily = "consolas";
  32533. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32534. this._logDiv.appendChild(this._logSubsetDiv);
  32535. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32536. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32537. };
  32538. // Options
  32539. this._optionsDiv = document.createElement("div");
  32540. this._optionsDiv.id = "DebugLayerOptions";
  32541. this._optionsDiv.style.border = border;
  32542. this._optionsDiv.style.position = "absolute";
  32543. this._optionsDiv.style.background = background;
  32544. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32545. this._optionsDiv.style.overflowY = "auto";
  32546. this._generateheader(this._optionsDiv, "OPTIONS");
  32547. this._optionsSubsetDiv = document.createElement("div");
  32548. this._optionsSubsetDiv.style.paddingTop = "5px";
  32549. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32550. this._optionsSubsetDiv.style.overflowY = "auto";
  32551. this._optionsSubsetDiv.style.maxHeight = "200px";
  32552. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32553. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32554. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32555. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32556. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32557. _this._displayTree = element.checked;
  32558. _this._needToRefreshMeshesTree = true;
  32559. });
  32560. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32561. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32562. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32563. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32564. _this._labelsEnabled = element.checked;
  32565. if (!_this._labelsEnabled) {
  32566. _this._clearLabels();
  32567. }
  32568. });
  32569. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32570. if (element.checked) {
  32571. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32572. }
  32573. else {
  32574. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32575. }
  32576. });
  32577. ;
  32578. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32579. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32580. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32581. if (element.checked) {
  32582. _this._scene.forceWireframe = false;
  32583. _this._scene.forcePointsCloud = false;
  32584. }
  32585. });
  32586. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32587. if (element.checked) {
  32588. _this._scene.forceWireframe = true;
  32589. _this._scene.forcePointsCloud = false;
  32590. }
  32591. });
  32592. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32593. if (element.checked) {
  32594. _this._scene.forceWireframe = false;
  32595. _this._scene.forcePointsCloud = true;
  32596. }
  32597. });
  32598. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32599. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32600. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32601. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32602. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32603. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32604. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32605. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32606. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32607. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32608. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32609. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32610. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32611. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32612. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32613. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32614. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32615. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32616. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32617. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32618. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32619. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32620. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32621. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32622. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32623. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32624. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32625. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32626. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32627. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32628. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32629. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32630. if (element.checked) {
  32631. _this._scene.headphone = true;
  32632. }
  32633. });
  32634. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32635. if (element.checked) {
  32636. _this._scene.headphone = false;
  32637. }
  32638. });
  32639. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32640. _this._scene.audioEnabled = !element.checked;
  32641. });
  32642. }
  32643. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32644. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32645. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32646. if (!element.checked) {
  32647. _this._clearSkeletonViewers();
  32648. return;
  32649. }
  32650. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32651. var mesh = _this._scene.meshes[index];
  32652. if (mesh.skeleton) {
  32653. var found = false;
  32654. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32655. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32656. found = true;
  32657. break;
  32658. }
  32659. }
  32660. if (found) {
  32661. continue;
  32662. }
  32663. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32664. viewer.isEnabled = true;
  32665. _this._skeletonViewers.push(viewer);
  32666. }
  32667. }
  32668. });
  32669. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32670. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32671. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32672. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32673. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32674. if (_this._camera) {
  32675. console.log(_this._camera);
  32676. }
  32677. else {
  32678. console.warn("No camera defined, or debug layer created before camera creation!");
  32679. }
  32680. });
  32681. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32682. this._globalDiv.appendChild(this._statsDiv);
  32683. this._globalDiv.appendChild(this._logDiv);
  32684. this._globalDiv.appendChild(this._optionsDiv);
  32685. this._globalDiv.appendChild(this._treeDiv);
  32686. }
  32687. };
  32688. DebugLayer.prototype._displayStats = function () {
  32689. var scene = this._scene;
  32690. var engine = scene.getEngine();
  32691. var glInfo = engine.getGlInfo();
  32692. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32693. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32694. + "<b>Count</b><br>"
  32695. + "Total meshes: " + scene.meshes.length + "<br>"
  32696. + "Total lights: " + scene.lights.length + "<br>"
  32697. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32698. + "Total materials: " + scene.materials.length + "<br>"
  32699. + "Total textures: " + scene.textures.length + "<br>"
  32700. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32701. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32702. + "Active bones: " + scene.getActiveBones() + "<br>"
  32703. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32704. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  32705. + "<b>Duration</b><br>"
  32706. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32707. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32708. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32709. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32710. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32711. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32712. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32713. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  32714. + "</div>"
  32715. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32716. + "<b>Extensions</b><br>"
  32717. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32718. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32719. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32720. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32721. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32722. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32723. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32724. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32725. + "</div><br>"
  32726. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32727. + "<b>Caps.</b><br>"
  32728. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32729. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32730. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32731. + "<b>Info</b><br>"
  32732. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32733. + glInfo.version + "<br>"
  32734. + "</div><br>"
  32735. + glInfo.renderer + "<br>";
  32736. if (this.customStatsFunction) {
  32737. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32738. }
  32739. };
  32740. return DebugLayer;
  32741. }());
  32742. BABYLON.DebugLayer = DebugLayer;
  32743. })(BABYLON || (BABYLON = {}));
  32744. var BABYLON;
  32745. (function (BABYLON) {
  32746. var DefaultLoadingScreen = (function () {
  32747. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32748. var _this = this;
  32749. if (_loadingText === void 0) { _loadingText = ""; }
  32750. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32751. this._renderingCanvas = _renderingCanvas;
  32752. this._loadingText = _loadingText;
  32753. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32754. // Resize
  32755. this._resizeLoadingUI = function () {
  32756. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32757. _this._loadingDiv.style.position = "absolute";
  32758. _this._loadingDiv.style.left = canvasRect.left + "px";
  32759. _this._loadingDiv.style.top = canvasRect.top + "px";
  32760. _this._loadingDiv.style.width = canvasRect.width + "px";
  32761. _this._loadingDiv.style.height = canvasRect.height + "px";
  32762. };
  32763. }
  32764. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32765. var _this = this;
  32766. if (this._loadingDiv) {
  32767. // Do not add a loading screen if there is already one
  32768. return;
  32769. }
  32770. this._loadingDiv = document.createElement("div");
  32771. this._loadingDiv.id = "babylonjsLoadingDiv";
  32772. this._loadingDiv.style.opacity = "0";
  32773. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32774. // Loading text
  32775. this._loadingTextDiv = document.createElement("div");
  32776. this._loadingTextDiv.style.position = "absolute";
  32777. this._loadingTextDiv.style.left = "0";
  32778. this._loadingTextDiv.style.top = "50%";
  32779. this._loadingTextDiv.style.marginTop = "80px";
  32780. this._loadingTextDiv.style.width = "100%";
  32781. this._loadingTextDiv.style.height = "20px";
  32782. this._loadingTextDiv.style.fontFamily = "Arial";
  32783. this._loadingTextDiv.style.fontSize = "14px";
  32784. this._loadingTextDiv.style.color = "white";
  32785. this._loadingTextDiv.style.textAlign = "center";
  32786. this._loadingTextDiv.innerHTML = "Loading";
  32787. this._loadingDiv.appendChild(this._loadingTextDiv);
  32788. //set the predefined text
  32789. this._loadingTextDiv.innerHTML = this._loadingText;
  32790. // Loading img
  32791. var imgBack = new Image();
  32792. 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==";
  32793. imgBack.style.position = "absolute";
  32794. imgBack.style.left = "50%";
  32795. imgBack.style.top = "50%";
  32796. imgBack.style.marginLeft = "-50px";
  32797. imgBack.style.marginTop = "-50px";
  32798. imgBack.style.transition = "transform 1.0s ease";
  32799. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32800. var deg = 360;
  32801. var onTransitionEnd = function () {
  32802. deg += 360;
  32803. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32804. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32805. };
  32806. imgBack.addEventListener("transitionend", onTransitionEnd);
  32807. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32808. this._loadingDiv.appendChild(imgBack);
  32809. // front image
  32810. var imgFront = new Image();
  32811. 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=";
  32812. imgFront.style.position = "absolute";
  32813. imgFront.style.left = "50%";
  32814. imgFront.style.top = "50%";
  32815. imgFront.style.marginLeft = "-50px";
  32816. imgFront.style.marginTop = "-50px";
  32817. this._loadingDiv.appendChild(imgFront);
  32818. this._resizeLoadingUI();
  32819. window.addEventListener("resize", this._resizeLoadingUI);
  32820. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32821. document.body.appendChild(this._loadingDiv);
  32822. setTimeout(function () {
  32823. _this._loadingDiv.style.opacity = "1";
  32824. imgBack.style.transform = "rotateZ(360deg)";
  32825. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32826. }, 0);
  32827. };
  32828. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  32829. var _this = this;
  32830. if (!this._loadingDiv) {
  32831. return;
  32832. }
  32833. var onTransitionEnd = function () {
  32834. if (!_this._loadingDiv) {
  32835. return;
  32836. }
  32837. document.body.removeChild(_this._loadingDiv);
  32838. window.removeEventListener("resize", _this._resizeLoadingUI);
  32839. _this._loadingDiv = null;
  32840. };
  32841. this._loadingDiv.style.opacity = "0";
  32842. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  32843. };
  32844. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  32845. set: function (text) {
  32846. this._loadingText = text;
  32847. if (this._loadingTextDiv) {
  32848. this._loadingTextDiv.innerHTML = this._loadingText;
  32849. }
  32850. },
  32851. enumerable: true,
  32852. configurable: true
  32853. });
  32854. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  32855. get: function () {
  32856. return this._loadingDivBackgroundColor;
  32857. },
  32858. set: function (color) {
  32859. this._loadingDivBackgroundColor = color;
  32860. if (!this._loadingDiv) {
  32861. return;
  32862. }
  32863. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32864. },
  32865. enumerable: true,
  32866. configurable: true
  32867. });
  32868. return DefaultLoadingScreen;
  32869. }());
  32870. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  32871. })(BABYLON || (BABYLON = {}));
  32872. var BABYLON;
  32873. (function (BABYLON) {
  32874. var AudioEngine = (function () {
  32875. function AudioEngine() {
  32876. this._audioContext = null;
  32877. this._audioContextInitialized = false;
  32878. this.canUseWebAudio = false;
  32879. this.WarnedWebAudioUnsupported = false;
  32880. this.unlocked = false;
  32881. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32882. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32883. this.canUseWebAudio = true;
  32884. }
  32885. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  32886. this._unlockiOSaudio();
  32887. }
  32888. else {
  32889. this.unlocked = true;
  32890. }
  32891. }
  32892. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32893. get: function () {
  32894. if (!this._audioContextInitialized) {
  32895. this._initializeAudioContext();
  32896. }
  32897. return this._audioContext;
  32898. },
  32899. enumerable: true,
  32900. configurable: true
  32901. });
  32902. AudioEngine.prototype._unlockiOSaudio = function () {
  32903. var _this = this;
  32904. var unlockaudio = function () {
  32905. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  32906. var source = _this.audioContext.createBufferSource();
  32907. source.buffer = buffer;
  32908. source.connect(_this.audioContext.destination);
  32909. source.start(0);
  32910. setTimeout(function () {
  32911. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  32912. _this.unlocked = true;
  32913. window.removeEventListener('touchend', unlockaudio, false);
  32914. if (_this.onAudioUnlocked) {
  32915. _this.onAudioUnlocked();
  32916. }
  32917. }
  32918. }, 0);
  32919. };
  32920. window.addEventListener('touchend', unlockaudio, false);
  32921. };
  32922. AudioEngine.prototype._initializeAudioContext = function () {
  32923. try {
  32924. if (this.canUseWebAudio) {
  32925. this._audioContext = new AudioContext();
  32926. // create a global volume gain node
  32927. this.masterGain = this._audioContext.createGain();
  32928. this.masterGain.gain.value = 1;
  32929. this.masterGain.connect(this._audioContext.destination);
  32930. this._audioContextInitialized = true;
  32931. }
  32932. }
  32933. catch (e) {
  32934. this.canUseWebAudio = false;
  32935. BABYLON.Tools.Error("Web Audio: " + e.message);
  32936. }
  32937. };
  32938. AudioEngine.prototype.dispose = function () {
  32939. if (this.canUseWebAudio && this._audioContextInitialized) {
  32940. if (this._connectedAnalyser) {
  32941. this._connectedAnalyser.stopDebugCanvas();
  32942. this._connectedAnalyser.dispose();
  32943. this.masterGain.disconnect();
  32944. this.masterGain.connect(this._audioContext.destination);
  32945. this._connectedAnalyser = null;
  32946. }
  32947. this.masterGain.gain.value = 1;
  32948. }
  32949. this.WarnedWebAudioUnsupported = false;
  32950. };
  32951. AudioEngine.prototype.getGlobalVolume = function () {
  32952. if (this.canUseWebAudio && this._audioContextInitialized) {
  32953. return this.masterGain.gain.value;
  32954. }
  32955. else {
  32956. return -1;
  32957. }
  32958. };
  32959. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  32960. if (this.canUseWebAudio && this._audioContextInitialized) {
  32961. this.masterGain.gain.value = newVolume;
  32962. }
  32963. };
  32964. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  32965. if (this._connectedAnalyser) {
  32966. this._connectedAnalyser.stopDebugCanvas();
  32967. }
  32968. if (this.canUseWebAudio && this._audioContextInitialized) {
  32969. this._connectedAnalyser = analyser;
  32970. this.masterGain.disconnect();
  32971. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  32972. }
  32973. };
  32974. return AudioEngine;
  32975. }());
  32976. BABYLON.AudioEngine = AudioEngine;
  32977. })(BABYLON || (BABYLON = {}));
  32978. var BABYLON;
  32979. (function (BABYLON) {
  32980. var Sound = (function () {
  32981. /**
  32982. * Create a sound and attach it to a scene
  32983. * @param name Name of your sound
  32984. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  32985. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  32986. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  32987. */
  32988. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  32989. var _this = this;
  32990. this.autoplay = false;
  32991. this.loop = false;
  32992. this.useCustomAttenuation = false;
  32993. this.spatialSound = false;
  32994. this.refDistance = 1;
  32995. this.rolloffFactor = 1;
  32996. this.maxDistance = 100;
  32997. this.distanceModel = "linear";
  32998. this._panningModel = "equalpower";
  32999. this._playbackRate = 1;
  33000. this._streaming = false;
  33001. this._startTime = 0;
  33002. this._startOffset = 0;
  33003. this._position = BABYLON.Vector3.Zero();
  33004. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33005. this._volume = 1;
  33006. this._isLoaded = false;
  33007. this._isReadyToPlay = false;
  33008. this.isPlaying = false;
  33009. this.isPaused = false;
  33010. this._isDirectional = false;
  33011. // Used if you'd like to create a directional sound.
  33012. // If not set, the sound will be omnidirectional
  33013. this._coneInnerAngle = 360;
  33014. this._coneOuterAngle = 360;
  33015. this._coneOuterGain = 0;
  33016. this._isOutputConnected = false;
  33017. this.name = name;
  33018. this._scene = scene;
  33019. this._readyToPlayCallback = readyToPlayCallback;
  33020. // Default custom attenuation function is a linear attenuation
  33021. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33022. if (currentDistance < maxDistance) {
  33023. return currentVolume * (1 - currentDistance / maxDistance);
  33024. }
  33025. else {
  33026. return 0;
  33027. }
  33028. };
  33029. if (options) {
  33030. this.autoplay = options.autoplay || false;
  33031. this.loop = options.loop || false;
  33032. // if volume === 0, we need another way to check this option
  33033. if (options.volume !== undefined) {
  33034. this._volume = options.volume;
  33035. }
  33036. this.spatialSound = options.spatialSound || false;
  33037. this.maxDistance = options.maxDistance || 100;
  33038. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33039. this.rolloffFactor = options.rolloffFactor || 1;
  33040. this.refDistance = options.refDistance || 1;
  33041. this.distanceModel = options.distanceModel || "linear";
  33042. this._playbackRate = options.playbackRate || 1;
  33043. this._streaming = options.streaming || false;
  33044. }
  33045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33046. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33047. this._soundGain.gain.value = this._volume;
  33048. this._inputAudioNode = this._soundGain;
  33049. this._ouputAudioNode = this._soundGain;
  33050. if (this.spatialSound) {
  33051. this._createSpatialParameters();
  33052. }
  33053. this._scene.mainSoundTrack.AddSound(this);
  33054. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33055. if (urlOrArrayBuffer) {
  33056. // If it's an URL
  33057. if (typeof (urlOrArrayBuffer) === "string") {
  33058. // Loading sound using XHR2
  33059. if (!this._streaming) {
  33060. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33061. }
  33062. else {
  33063. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33064. this._htmlAudioElement.controls = false;
  33065. this._htmlAudioElement.loop = this.loop;
  33066. this._htmlAudioElement.crossOrigin = "anonymous";
  33067. this._htmlAudioElement.preload = "auto";
  33068. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33069. _this._isReadyToPlay = true;
  33070. if (_this.autoplay) {
  33071. _this.play();
  33072. }
  33073. if (_this._readyToPlayCallback) {
  33074. _this._readyToPlayCallback();
  33075. }
  33076. });
  33077. document.body.appendChild(this._htmlAudioElement);
  33078. }
  33079. }
  33080. else {
  33081. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33082. if (urlOrArrayBuffer.byteLength > 0) {
  33083. this._soundLoaded(urlOrArrayBuffer);
  33084. }
  33085. }
  33086. else {
  33087. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33088. }
  33089. }
  33090. }
  33091. }
  33092. else {
  33093. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33094. this._scene.mainSoundTrack.AddSound(this);
  33095. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33096. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33097. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33098. }
  33099. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33100. if (this._readyToPlayCallback) {
  33101. window.setTimeout(function () {
  33102. _this._readyToPlayCallback();
  33103. }, 1000);
  33104. }
  33105. }
  33106. }
  33107. Sound.prototype.dispose = function () {
  33108. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33109. if (this.isPlaying) {
  33110. this.stop();
  33111. }
  33112. this._isReadyToPlay = false;
  33113. if (this.soundTrackId === -1) {
  33114. this._scene.mainSoundTrack.RemoveSound(this);
  33115. }
  33116. else {
  33117. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33118. }
  33119. if (this._soundGain) {
  33120. this._soundGain.disconnect();
  33121. this._soundGain = null;
  33122. }
  33123. if (this._soundPanner) {
  33124. this._soundPanner.disconnect();
  33125. this._soundPanner = null;
  33126. }
  33127. if (this._soundSource) {
  33128. this._soundSource.disconnect();
  33129. this._soundSource = null;
  33130. }
  33131. this._audioBuffer = null;
  33132. if (this._htmlAudioElement) {
  33133. this._htmlAudioElement.pause();
  33134. this._htmlAudioElement.src = "";
  33135. document.body.removeChild(this._htmlAudioElement);
  33136. }
  33137. if (this._connectedMesh) {
  33138. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33139. this._connectedMesh = null;
  33140. }
  33141. }
  33142. };
  33143. Sound.prototype._soundLoaded = function (audioData) {
  33144. var _this = this;
  33145. this._isLoaded = true;
  33146. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33147. _this._audioBuffer = buffer;
  33148. _this._isReadyToPlay = true;
  33149. if (_this.autoplay) {
  33150. _this.play();
  33151. }
  33152. if (_this._readyToPlayCallback) {
  33153. _this._readyToPlayCallback();
  33154. }
  33155. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33156. };
  33157. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33158. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33159. this._audioBuffer = audioBuffer;
  33160. this._isReadyToPlay = true;
  33161. }
  33162. };
  33163. Sound.prototype.updateOptions = function (options) {
  33164. if (options) {
  33165. this.loop = options.loop || this.loop;
  33166. this.maxDistance = options.maxDistance || this.maxDistance;
  33167. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33168. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33169. this.refDistance = options.refDistance || this.refDistance;
  33170. this.distanceModel = options.distanceModel || this.distanceModel;
  33171. this._playbackRate = options.playbackRate || this._playbackRate;
  33172. this._updateSpatialParameters();
  33173. if (this.isPlaying) {
  33174. if (this._streaming) {
  33175. this._htmlAudioElement.playbackRate = this._playbackRate;
  33176. }
  33177. else {
  33178. this._soundSource.playbackRate.value = this._playbackRate;
  33179. }
  33180. }
  33181. }
  33182. };
  33183. Sound.prototype._createSpatialParameters = function () {
  33184. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33185. if (this._scene.headphone) {
  33186. this._panningModel = "HRTF";
  33187. }
  33188. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33189. this._updateSpatialParameters();
  33190. this._soundPanner.connect(this._ouputAudioNode);
  33191. this._inputAudioNode = this._soundPanner;
  33192. }
  33193. };
  33194. Sound.prototype._updateSpatialParameters = function () {
  33195. if (this.spatialSound) {
  33196. if (this.useCustomAttenuation) {
  33197. // Tricks to disable in a way embedded Web Audio attenuation
  33198. this._soundPanner.distanceModel = "linear";
  33199. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33200. this._soundPanner.refDistance = 1;
  33201. this._soundPanner.rolloffFactor = 1;
  33202. this._soundPanner.panningModel = this._panningModel;
  33203. }
  33204. else {
  33205. this._soundPanner.distanceModel = this.distanceModel;
  33206. this._soundPanner.maxDistance = this.maxDistance;
  33207. this._soundPanner.refDistance = this.refDistance;
  33208. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33209. this._soundPanner.panningModel = this._panningModel;
  33210. }
  33211. }
  33212. };
  33213. Sound.prototype.switchPanningModelToHRTF = function () {
  33214. this._panningModel = "HRTF";
  33215. this._switchPanningModel();
  33216. };
  33217. Sound.prototype.switchPanningModelToEqualPower = function () {
  33218. this._panningModel = "equalpower";
  33219. this._switchPanningModel();
  33220. };
  33221. Sound.prototype._switchPanningModel = function () {
  33222. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33223. this._soundPanner.panningModel = this._panningModel;
  33224. }
  33225. };
  33226. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33227. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33228. if (this._isOutputConnected) {
  33229. this._ouputAudioNode.disconnect();
  33230. }
  33231. this._ouputAudioNode.connect(soundTrackAudioNode);
  33232. this._isOutputConnected = true;
  33233. }
  33234. };
  33235. /**
  33236. * Transform this sound into a directional source
  33237. * @param coneInnerAngle Size of the inner cone in degree
  33238. * @param coneOuterAngle Size of the outer cone in degree
  33239. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33240. */
  33241. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33242. if (coneOuterAngle < coneInnerAngle) {
  33243. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33244. return;
  33245. }
  33246. this._coneInnerAngle = coneInnerAngle;
  33247. this._coneOuterAngle = coneOuterAngle;
  33248. this._coneOuterGain = coneOuterGain;
  33249. this._isDirectional = true;
  33250. if (this.isPlaying && this.loop) {
  33251. this.stop();
  33252. this.play();
  33253. }
  33254. };
  33255. Sound.prototype.setPosition = function (newPosition) {
  33256. this._position = newPosition;
  33257. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33258. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33259. }
  33260. };
  33261. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33262. this._localDirection = newLocalDirection;
  33263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33264. this._updateDirection();
  33265. }
  33266. };
  33267. Sound.prototype._updateDirection = function () {
  33268. var mat = this._connectedMesh.getWorldMatrix();
  33269. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33270. direction.normalize();
  33271. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33272. };
  33273. Sound.prototype.updateDistanceFromListener = function () {
  33274. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33275. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33276. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33277. }
  33278. };
  33279. Sound.prototype.setAttenuationFunction = function (callback) {
  33280. this._customAttenuationFunction = callback;
  33281. };
  33282. /**
  33283. * Play the sound
  33284. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33285. */
  33286. Sound.prototype.play = function (time) {
  33287. var _this = this;
  33288. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33289. try {
  33290. if (this._startOffset < 0) {
  33291. time = -this._startOffset;
  33292. this._startOffset = 0;
  33293. }
  33294. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33295. if (!this._soundSource || !this._streamingSource) {
  33296. if (this.spatialSound) {
  33297. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33298. if (this._isDirectional) {
  33299. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33300. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33301. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33302. if (this._connectedMesh) {
  33303. this._updateDirection();
  33304. }
  33305. else {
  33306. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33307. }
  33308. }
  33309. }
  33310. }
  33311. if (this._streaming) {
  33312. if (!this._streamingSource) {
  33313. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33314. this._htmlAudioElement.onended = function () { _this._onended(); };
  33315. this._htmlAudioElement.playbackRate = this._playbackRate;
  33316. }
  33317. this._streamingSource.disconnect();
  33318. this._streamingSource.connect(this._inputAudioNode);
  33319. this._htmlAudioElement.play();
  33320. }
  33321. else {
  33322. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33323. this._soundSource.buffer = this._audioBuffer;
  33324. this._soundSource.connect(this._inputAudioNode);
  33325. this._soundSource.loop = this.loop;
  33326. this._soundSource.playbackRate.value = this._playbackRate;
  33327. this._soundSource.onended = function () { _this._onended(); };
  33328. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33329. }
  33330. this._startTime = startTime;
  33331. this.isPlaying = true;
  33332. this.isPaused = false;
  33333. }
  33334. catch (ex) {
  33335. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33336. }
  33337. }
  33338. };
  33339. Sound.prototype._onended = function () {
  33340. this.isPlaying = false;
  33341. if (this.onended) {
  33342. this.onended();
  33343. }
  33344. };
  33345. /**
  33346. * Stop the sound
  33347. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33348. */
  33349. Sound.prototype.stop = function (time) {
  33350. if (this.isPlaying) {
  33351. if (this._streaming) {
  33352. this._htmlAudioElement.pause();
  33353. // Test needed for Firefox or it will generate an Invalid State Error
  33354. if (this._htmlAudioElement.currentTime > 0) {
  33355. this._htmlAudioElement.currentTime = 0;
  33356. }
  33357. }
  33358. else {
  33359. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33360. this._soundSource.stop(stopTime);
  33361. if (!this.isPaused) {
  33362. this._startOffset = 0;
  33363. }
  33364. }
  33365. this.isPlaying = false;
  33366. }
  33367. };
  33368. Sound.prototype.pause = function () {
  33369. if (this.isPlaying) {
  33370. this.isPaused = true;
  33371. if (this._streaming) {
  33372. this._htmlAudioElement.pause();
  33373. }
  33374. else {
  33375. this.stop(0);
  33376. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33377. }
  33378. }
  33379. };
  33380. Sound.prototype.setVolume = function (newVolume, time) {
  33381. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33382. if (time) {
  33383. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33384. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33385. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33386. }
  33387. else {
  33388. this._soundGain.gain.value = newVolume;
  33389. }
  33390. }
  33391. this._volume = newVolume;
  33392. };
  33393. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33394. this._playbackRate = newPlaybackRate;
  33395. if (this.isPlaying) {
  33396. if (this._streaming) {
  33397. this._htmlAudioElement.playbackRate = this._playbackRate;
  33398. }
  33399. else {
  33400. this._soundSource.playbackRate.value = this._playbackRate;
  33401. }
  33402. }
  33403. };
  33404. Sound.prototype.getVolume = function () {
  33405. return this._volume;
  33406. };
  33407. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33408. var _this = this;
  33409. if (this._connectedMesh) {
  33410. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33411. this._registerFunc = null;
  33412. }
  33413. this._connectedMesh = meshToConnectTo;
  33414. if (!this.spatialSound) {
  33415. this.spatialSound = true;
  33416. this._createSpatialParameters();
  33417. if (this.isPlaying && this.loop) {
  33418. this.stop();
  33419. this.play();
  33420. }
  33421. }
  33422. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33423. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33424. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33425. };
  33426. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33427. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33428. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33429. this._updateDirection();
  33430. }
  33431. };
  33432. Sound.prototype.clone = function () {
  33433. var _this = this;
  33434. if (!this._streaming) {
  33435. var setBufferAndRun = function () {
  33436. if (_this._isReadyToPlay) {
  33437. clonedSound._audioBuffer = _this.getAudioBuffer();
  33438. clonedSound._isReadyToPlay = true;
  33439. if (clonedSound.autoplay) {
  33440. clonedSound.play();
  33441. }
  33442. }
  33443. else {
  33444. window.setTimeout(setBufferAndRun, 300);
  33445. }
  33446. };
  33447. var currentOptions = {
  33448. autoplay: this.autoplay, loop: this.loop,
  33449. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33450. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33451. refDistance: this.refDistance, distanceModel: this.distanceModel
  33452. };
  33453. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33454. if (this.useCustomAttenuation) {
  33455. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33456. }
  33457. clonedSound.setPosition(this._position);
  33458. clonedSound.setPlaybackRate(this._playbackRate);
  33459. setBufferAndRun();
  33460. return clonedSound;
  33461. }
  33462. else {
  33463. return null;
  33464. }
  33465. };
  33466. Sound.prototype.getAudioBuffer = function () {
  33467. return this._audioBuffer;
  33468. };
  33469. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33470. var soundName = parsedSound.name;
  33471. var soundUrl;
  33472. if (parsedSound.url) {
  33473. soundUrl = rootUrl + parsedSound.url;
  33474. }
  33475. else {
  33476. soundUrl = rootUrl + soundName;
  33477. }
  33478. var options = {
  33479. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33480. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33481. rolloffFactor: parsedSound.rolloffFactor,
  33482. refDistance: parsedSound.refDistance,
  33483. distanceModel: parsedSound.distanceModel,
  33484. playbackRate: parsedSound.playbackRate
  33485. };
  33486. var newSound;
  33487. if (!sourceSound) {
  33488. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33489. scene._addPendingData(newSound);
  33490. }
  33491. else {
  33492. var setBufferAndRun = function () {
  33493. if (sourceSound._isReadyToPlay) {
  33494. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33495. newSound._isReadyToPlay = true;
  33496. if (newSound.autoplay) {
  33497. newSound.play();
  33498. }
  33499. }
  33500. else {
  33501. window.setTimeout(setBufferAndRun, 300);
  33502. }
  33503. };
  33504. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33505. setBufferAndRun();
  33506. }
  33507. if (parsedSound.position) {
  33508. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33509. newSound.setPosition(soundPosition);
  33510. }
  33511. if (parsedSound.isDirectional) {
  33512. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33513. if (parsedSound.localDirectionToMesh) {
  33514. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33515. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33516. }
  33517. }
  33518. if (parsedSound.connectedMeshId) {
  33519. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33520. if (connectedMesh) {
  33521. newSound.attachToMesh(connectedMesh);
  33522. }
  33523. }
  33524. return newSound;
  33525. };
  33526. return Sound;
  33527. }());
  33528. BABYLON.Sound = Sound;
  33529. })(BABYLON || (BABYLON = {}));
  33530. var BABYLON;
  33531. (function (BABYLON) {
  33532. var SoundTrack = (function () {
  33533. function SoundTrack(scene, options) {
  33534. this.id = -1;
  33535. this._isMainTrack = false;
  33536. this._isInitialized = false;
  33537. this._scene = scene;
  33538. this.soundCollection = new Array();
  33539. this._options = options;
  33540. if (!this._isMainTrack) {
  33541. this._scene.soundTracks.push(this);
  33542. this.id = this._scene.soundTracks.length - 1;
  33543. }
  33544. }
  33545. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33546. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33547. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33548. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33549. if (this._options) {
  33550. if (this._options.volume) {
  33551. this._outputAudioNode.gain.value = this._options.volume;
  33552. }
  33553. if (this._options.mainTrack) {
  33554. this._isMainTrack = this._options.mainTrack;
  33555. }
  33556. }
  33557. this._isInitialized = true;
  33558. }
  33559. };
  33560. SoundTrack.prototype.dispose = function () {
  33561. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33562. if (this._connectedAnalyser) {
  33563. this._connectedAnalyser.stopDebugCanvas();
  33564. }
  33565. while (this.soundCollection.length) {
  33566. this.soundCollection[0].dispose();
  33567. }
  33568. if (this._outputAudioNode) {
  33569. this._outputAudioNode.disconnect();
  33570. }
  33571. this._outputAudioNode = null;
  33572. }
  33573. };
  33574. SoundTrack.prototype.AddSound = function (sound) {
  33575. if (!this._isInitialized) {
  33576. this._initializeSoundTrackAudioGraph();
  33577. }
  33578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33579. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33580. }
  33581. if (sound.soundTrackId) {
  33582. if (sound.soundTrackId === -1) {
  33583. this._scene.mainSoundTrack.RemoveSound(sound);
  33584. }
  33585. else {
  33586. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33587. }
  33588. }
  33589. this.soundCollection.push(sound);
  33590. sound.soundTrackId = this.id;
  33591. };
  33592. SoundTrack.prototype.RemoveSound = function (sound) {
  33593. var index = this.soundCollection.indexOf(sound);
  33594. if (index !== -1) {
  33595. this.soundCollection.splice(index, 1);
  33596. }
  33597. };
  33598. SoundTrack.prototype.setVolume = function (newVolume) {
  33599. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33600. this._outputAudioNode.gain.value = newVolume;
  33601. }
  33602. };
  33603. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33604. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33605. for (var i = 0; i < this.soundCollection.length; i++) {
  33606. this.soundCollection[i].switchPanningModelToHRTF();
  33607. }
  33608. }
  33609. };
  33610. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33611. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33612. for (var i = 0; i < this.soundCollection.length; i++) {
  33613. this.soundCollection[i].switchPanningModelToEqualPower();
  33614. }
  33615. }
  33616. };
  33617. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33618. if (this._connectedAnalyser) {
  33619. this._connectedAnalyser.stopDebugCanvas();
  33620. }
  33621. this._connectedAnalyser = analyser;
  33622. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33623. this._outputAudioNode.disconnect();
  33624. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33625. }
  33626. };
  33627. return SoundTrack;
  33628. }());
  33629. BABYLON.SoundTrack = SoundTrack;
  33630. })(BABYLON || (BABYLON = {}));
  33631. var BABYLON;
  33632. (function (BABYLON) {
  33633. var SIMDVector3 = (function () {
  33634. function SIMDVector3() {
  33635. }
  33636. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33637. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33638. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33639. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33640. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33641. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33642. 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));
  33643. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33644. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33645. };
  33646. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33647. var v0 = SIMD.float32x4.splat(x);
  33648. var v1 = SIMD.float32x4.splat(y);
  33649. var v2 = SIMD.float32x4.splat(z);
  33650. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33651. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33652. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33653. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33654. 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));
  33655. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33656. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33657. };
  33658. return SIMDVector3;
  33659. }());
  33660. BABYLON.SIMDVector3 = SIMDVector3;
  33661. var SIMDMatrix = (function () {
  33662. function SIMDMatrix() {
  33663. }
  33664. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33665. if (offset === void 0) { offset = 0; }
  33666. var tm = this.m;
  33667. var om = other.m;
  33668. var om0 = SIMD.float32x4.load(om, 0);
  33669. var om1 = SIMD.float32x4.load(om, 4);
  33670. var om2 = SIMD.float32x4.load(om, 8);
  33671. var om3 = SIMD.float32x4.load(om, 12);
  33672. var tm0 = SIMD.float32x4.load(tm, 0);
  33673. 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)))));
  33674. var tm1 = SIMD.float32x4.load(tm, 4);
  33675. 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)))));
  33676. var tm2 = SIMD.float32x4.load(tm, 8);
  33677. 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)))));
  33678. var tm3 = SIMD.float32x4.load(tm, 12);
  33679. 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)))));
  33680. };
  33681. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33682. var src = this.m;
  33683. var dest = other.m;
  33684. var row0, row1, row2, row3;
  33685. var tmp1;
  33686. var minor0, minor1, minor2, minor3;
  33687. var det;
  33688. // Load the 4 rows
  33689. var src0 = SIMD.float32x4.load(src, 0);
  33690. var src1 = SIMD.float32x4.load(src, 4);
  33691. var src2 = SIMD.float32x4.load(src, 8);
  33692. var src3 = SIMD.float32x4.load(src, 12);
  33693. // Transpose the source matrix. Sort of. Not a true transpose operation
  33694. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33695. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33696. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33697. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33698. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33699. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33700. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33701. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33702. // This is a true transposition, but it will lead to an incorrect result
  33703. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33704. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33705. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33706. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33707. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33708. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33709. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33710. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33711. // ----
  33712. tmp1 = SIMD.float32x4.mul(row2, row3);
  33713. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33714. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33715. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33716. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33717. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33718. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33719. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33720. // ----
  33721. tmp1 = SIMD.float32x4.mul(row1, row2);
  33722. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33723. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33724. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33725. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33726. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33727. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33728. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33729. // ----
  33730. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33731. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33732. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33733. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33734. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33735. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33736. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33737. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33738. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33739. // ----
  33740. tmp1 = SIMD.float32x4.mul(row0, row1);
  33741. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33742. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33743. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33744. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33745. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33746. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33747. // ----
  33748. tmp1 = SIMD.float32x4.mul(row0, row3);
  33749. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33750. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33751. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33752. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33753. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33754. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33755. // ----
  33756. tmp1 = SIMD.float32x4.mul(row0, row2);
  33757. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33758. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33759. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33760. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33761. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33762. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33763. // Compute determinant
  33764. det = SIMD.float32x4.mul(row0, minor0);
  33765. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33766. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33767. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33768. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33769. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33770. // These shuffles aren't necessary if the faulty transposition is done
  33771. // up at the top of this function.
  33772. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33773. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33774. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33775. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33776. // Compute final values by multiplying with 1/det
  33777. minor0 = SIMD.float32x4.mul(det, minor0);
  33778. minor1 = SIMD.float32x4.mul(det, minor1);
  33779. minor2 = SIMD.float32x4.mul(det, minor2);
  33780. minor3 = SIMD.float32x4.mul(det, minor3);
  33781. SIMD.float32x4.store(dest, 0, minor0);
  33782. SIMD.float32x4.store(dest, 4, minor1);
  33783. SIMD.float32x4.store(dest, 8, minor2);
  33784. SIMD.float32x4.store(dest, 12, minor3);
  33785. return this;
  33786. };
  33787. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33788. var out = result.m;
  33789. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33790. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33791. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33792. // cc.kmVec3Subtract(f, pCenter, pEye);
  33793. var f = SIMD.float32x4.sub(center, eye);
  33794. // cc.kmVec3Normalize(f, f);
  33795. var tmp = SIMD.float32x4.mul(f, f);
  33796. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33797. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33798. // cc.kmVec3Assign(up, pUp);
  33799. // cc.kmVec3Normalize(up, up);
  33800. tmp = SIMD.float32x4.mul(up, up);
  33801. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33802. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33803. // cc.kmVec3Cross(s, f, up);
  33804. 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)));
  33805. // cc.kmVec3Normalize(s, s);
  33806. tmp = SIMD.float32x4.mul(s, s);
  33807. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33808. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33809. // cc.kmVec3Cross(u, s, f);
  33810. 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)));
  33811. // cc.kmVec3Normalize(s, s);
  33812. tmp = SIMD.float32x4.mul(s, s);
  33813. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33814. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33815. var zero = SIMD.float32x4.splat(0.0);
  33816. s = SIMD.float32x4.neg(s);
  33817. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33818. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33819. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33820. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33821. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33822. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33823. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33824. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33825. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33826. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33827. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33828. var b3 = SIMD.float32x4.neg(eye);
  33829. b3 = SIMD.float32x4.withW(b3, 1.0);
  33830. 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)))));
  33831. 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)))));
  33832. 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)))));
  33833. 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)))));
  33834. };
  33835. return SIMDMatrix;
  33836. }());
  33837. BABYLON.SIMDMatrix = SIMDMatrix;
  33838. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  33839. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  33840. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  33841. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  33842. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  33843. var SIMDHelper = (function () {
  33844. function SIMDHelper() {
  33845. }
  33846. Object.defineProperty(SIMDHelper, "IsEnabled", {
  33847. get: function () {
  33848. return SIMDHelper._isEnabled;
  33849. },
  33850. enumerable: true,
  33851. configurable: true
  33852. });
  33853. SIMDHelper.DisableSIMD = function () {
  33854. // Replace functions
  33855. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  33856. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  33857. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  33858. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  33859. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  33860. SIMDHelper._isEnabled = false;
  33861. };
  33862. SIMDHelper.EnableSIMD = function () {
  33863. if (window.SIMD === undefined) {
  33864. return;
  33865. }
  33866. // Replace functions
  33867. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  33868. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  33869. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  33870. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  33871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  33872. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  33873. get: function () { return this._data[0]; },
  33874. set: function (value) {
  33875. if (!this._data) {
  33876. this._data = new Float32Array(3);
  33877. }
  33878. this._data[0] = value;
  33879. }
  33880. });
  33881. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  33882. get: function () { return this._data[1]; },
  33883. set: function (value) {
  33884. this._data[1] = value;
  33885. }
  33886. });
  33887. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  33888. get: function () { return this._data[2]; },
  33889. set: function (value) {
  33890. this._data[2] = value;
  33891. }
  33892. });
  33893. SIMDHelper._isEnabled = true;
  33894. };
  33895. SIMDHelper._isEnabled = false;
  33896. return SIMDHelper;
  33897. }());
  33898. BABYLON.SIMDHelper = SIMDHelper;
  33899. })(BABYLON || (BABYLON = {}));
  33900. var BABYLON;
  33901. (function (BABYLON) {
  33902. var ShaderMaterial = (function (_super) {
  33903. __extends(ShaderMaterial, _super);
  33904. function ShaderMaterial(name, scene, shaderPath, options) {
  33905. _super.call(this, name, scene);
  33906. this._textures = {};
  33907. this._floats = {};
  33908. this._floatsArrays = {};
  33909. this._colors3 = {};
  33910. this._colors4 = {};
  33911. this._vectors2 = {};
  33912. this._vectors3 = {};
  33913. this._vectors4 = {};
  33914. this._matrices = {};
  33915. this._matrices3x3 = {};
  33916. this._matrices2x2 = {};
  33917. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  33918. this._shaderPath = shaderPath;
  33919. options.needAlphaBlending = options.needAlphaBlending || false;
  33920. options.needAlphaTesting = options.needAlphaTesting || false;
  33921. options.attributes = options.attributes || ["position", "normal", "uv"];
  33922. options.uniforms = options.uniforms || ["worldViewProjection"];
  33923. options.samplers = options.samplers || [];
  33924. options.defines = options.defines || [];
  33925. this._options = options;
  33926. }
  33927. ShaderMaterial.prototype.needAlphaBlending = function () {
  33928. return this._options.needAlphaBlending;
  33929. };
  33930. ShaderMaterial.prototype.needAlphaTesting = function () {
  33931. return this._options.needAlphaTesting;
  33932. };
  33933. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  33934. if (this._options.uniforms.indexOf(uniformName) === -1) {
  33935. this._options.uniforms.push(uniformName);
  33936. }
  33937. };
  33938. ShaderMaterial.prototype.setTexture = function (name, texture) {
  33939. if (this._options.samplers.indexOf(name) === -1) {
  33940. this._options.samplers.push(name);
  33941. }
  33942. this._textures[name] = texture;
  33943. return this;
  33944. };
  33945. ShaderMaterial.prototype.setFloat = function (name, value) {
  33946. this._checkUniform(name);
  33947. this._floats[name] = value;
  33948. return this;
  33949. };
  33950. ShaderMaterial.prototype.setFloats = function (name, value) {
  33951. this._checkUniform(name);
  33952. this._floatsArrays[name] = value;
  33953. return this;
  33954. };
  33955. ShaderMaterial.prototype.setColor3 = function (name, value) {
  33956. this._checkUniform(name);
  33957. this._colors3[name] = value;
  33958. return this;
  33959. };
  33960. ShaderMaterial.prototype.setColor4 = function (name, value) {
  33961. this._checkUniform(name);
  33962. this._colors4[name] = value;
  33963. return this;
  33964. };
  33965. ShaderMaterial.prototype.setVector2 = function (name, value) {
  33966. this._checkUniform(name);
  33967. this._vectors2[name] = value;
  33968. return this;
  33969. };
  33970. ShaderMaterial.prototype.setVector3 = function (name, value) {
  33971. this._checkUniform(name);
  33972. this._vectors3[name] = value;
  33973. return this;
  33974. };
  33975. ShaderMaterial.prototype.setVector4 = function (name, value) {
  33976. this._checkUniform(name);
  33977. this._vectors4[name] = value;
  33978. return this;
  33979. };
  33980. ShaderMaterial.prototype.setMatrix = function (name, value) {
  33981. this._checkUniform(name);
  33982. this._matrices[name] = value;
  33983. return this;
  33984. };
  33985. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  33986. this._checkUniform(name);
  33987. this._matrices3x3[name] = value;
  33988. return this;
  33989. };
  33990. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  33991. this._checkUniform(name);
  33992. this._matrices2x2[name] = value;
  33993. return this;
  33994. };
  33995. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  33996. var scene = this.getScene();
  33997. var engine = scene.getEngine();
  33998. if (!this.checkReadyOnEveryCall) {
  33999. if (this._renderId === scene.getRenderId()) {
  34000. return true;
  34001. }
  34002. }
  34003. // Instances
  34004. var defines = [];
  34005. var fallbacks = new BABYLON.EffectFallbacks();
  34006. if (useInstances) {
  34007. defines.push("#define INSTANCES");
  34008. }
  34009. for (var index = 0; index < this._options.defines.length; index++) {
  34010. defines.push(this._options.defines[index]);
  34011. }
  34012. // Bones
  34013. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34014. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34015. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34016. fallbacks.addCPUSkinningFallback(0, mesh);
  34017. }
  34018. // Alpha test
  34019. if (engine.getAlphaTesting()) {
  34020. defines.push("#define ALPHATEST");
  34021. }
  34022. var previousEffect = this._effect;
  34023. var join = defines.join("\n");
  34024. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34025. if (!this._effect.isReady()) {
  34026. return false;
  34027. }
  34028. if (previousEffect !== this._effect) {
  34029. scene.resetCachedMaterial();
  34030. }
  34031. this._renderId = scene.getRenderId();
  34032. return true;
  34033. };
  34034. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34035. var scene = this.getScene();
  34036. if (this._options.uniforms.indexOf("world") !== -1) {
  34037. this._effect.setMatrix("world", world);
  34038. }
  34039. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34040. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34041. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34042. }
  34043. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34044. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34045. }
  34046. };
  34047. ShaderMaterial.prototype.bind = function (world, mesh) {
  34048. // Std values
  34049. this.bindOnlyWorldMatrix(world);
  34050. if (this.getScene().getCachedMaterial() !== this) {
  34051. if (this._options.uniforms.indexOf("view") !== -1) {
  34052. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34053. }
  34054. if (this._options.uniforms.indexOf("projection") !== -1) {
  34055. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34056. }
  34057. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34058. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34059. }
  34060. // Bones
  34061. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34062. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34063. }
  34064. // Texture
  34065. for (var name in this._textures) {
  34066. this._effect.setTexture(name, this._textures[name]);
  34067. }
  34068. // Float
  34069. for (name in this._floats) {
  34070. this._effect.setFloat(name, this._floats[name]);
  34071. }
  34072. // Float s
  34073. for (name in this._floatsArrays) {
  34074. this._effect.setArray(name, this._floatsArrays[name]);
  34075. }
  34076. // Color3
  34077. for (name in this._colors3) {
  34078. this._effect.setColor3(name, this._colors3[name]);
  34079. }
  34080. // Color4
  34081. for (name in this._colors4) {
  34082. var color = this._colors4[name];
  34083. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34084. }
  34085. // Vector2
  34086. for (name in this._vectors2) {
  34087. this._effect.setVector2(name, this._vectors2[name]);
  34088. }
  34089. // Vector3
  34090. for (name in this._vectors3) {
  34091. this._effect.setVector3(name, this._vectors3[name]);
  34092. }
  34093. // Vector4
  34094. for (name in this._vectors4) {
  34095. this._effect.setVector4(name, this._vectors4[name]);
  34096. }
  34097. // Matrix
  34098. for (name in this._matrices) {
  34099. this._effect.setMatrix(name, this._matrices[name]);
  34100. }
  34101. // Matrix 3x3
  34102. for (name in this._matrices3x3) {
  34103. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34104. }
  34105. // Matrix 2x2
  34106. for (name in this._matrices2x2) {
  34107. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34108. }
  34109. }
  34110. _super.prototype.bind.call(this, world, mesh);
  34111. };
  34112. ShaderMaterial.prototype.clone = function (name) {
  34113. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34114. return newShaderMaterial;
  34115. };
  34116. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  34117. for (var name in this._textures) {
  34118. this._textures[name].dispose();
  34119. }
  34120. this._textures = {};
  34121. _super.prototype.dispose.call(this, forceDisposeEffect);
  34122. };
  34123. ShaderMaterial.prototype.serialize = function () {
  34124. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34125. serializationObject.customType = "BABYLON.ShaderMaterial";
  34126. serializationObject.options = this._options;
  34127. serializationObject.shaderPath = this._shaderPath;
  34128. // Texture
  34129. serializationObject.textures = {};
  34130. for (var name in this._textures) {
  34131. serializationObject.textures[name] = this._textures[name].serialize();
  34132. }
  34133. // Float
  34134. serializationObject.floats = {};
  34135. for (name in this._floats) {
  34136. serializationObject.floats[name] = this._floats[name];
  34137. }
  34138. // Float s
  34139. serializationObject.floatArrays = {};
  34140. for (name in this._floatsArrays) {
  34141. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34142. }
  34143. // Color3
  34144. serializationObject.colors3 = {};
  34145. for (name in this._colors3) {
  34146. serializationObject.colors3[name] = this._colors3[name].asArray();
  34147. }
  34148. // Color4
  34149. serializationObject.colors4 = {};
  34150. for (name in this._colors4) {
  34151. serializationObject.colors4[name] = this._colors4[name].asArray();
  34152. }
  34153. // Vector2
  34154. serializationObject.vectors2 = {};
  34155. for (name in this._vectors2) {
  34156. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34157. }
  34158. // Vector3
  34159. serializationObject.vectors3 = {};
  34160. for (name in this._vectors3) {
  34161. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34162. }
  34163. // Vector4
  34164. serializationObject.vectors4 = {};
  34165. for (name in this._vectors4) {
  34166. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34167. }
  34168. // Matrix
  34169. serializationObject.matrices = {};
  34170. for (name in this._matrices) {
  34171. serializationObject.matrices[name] = this._matrices[name].asArray();
  34172. }
  34173. // Matrix 3x3
  34174. serializationObject.matrices3x3 = {};
  34175. for (name in this._matrices3x3) {
  34176. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34177. }
  34178. // Matrix 2x2
  34179. serializationObject.matrices2x2 = {};
  34180. for (name in this._matrices2x2) {
  34181. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34182. }
  34183. return serializationObject;
  34184. };
  34185. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34186. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34187. // Texture
  34188. for (var name in source.textures) {
  34189. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34190. }
  34191. // Float
  34192. for (name in source.floats) {
  34193. material.setFloat(name, source.floats[name]);
  34194. }
  34195. // Float s
  34196. for (name in source.floatsArrays) {
  34197. material.setFloats(name, source.floatsArrays[name]);
  34198. }
  34199. // Color3
  34200. for (name in source.colors3) {
  34201. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34202. }
  34203. // Color4
  34204. for (name in source.colors4) {
  34205. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34206. }
  34207. // Vector2
  34208. for (name in source.vectors2) {
  34209. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34210. }
  34211. // Vector3
  34212. for (name in source.vectors3) {
  34213. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34214. }
  34215. // Vector4
  34216. for (name in source.vectors4) {
  34217. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34218. }
  34219. // Matrix
  34220. for (name in source.matrices) {
  34221. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34222. }
  34223. // Matrix 3x3
  34224. for (name in source.matrices3x3) {
  34225. material.setMatrix3x3(name, source.matrices3x3[name]);
  34226. }
  34227. // Matrix 2x2
  34228. for (name in source.matrices2x2) {
  34229. material.setMatrix2x2(name, source.matrices2x2[name]);
  34230. }
  34231. return material;
  34232. };
  34233. return ShaderMaterial;
  34234. }(BABYLON.Material));
  34235. BABYLON.ShaderMaterial = ShaderMaterial;
  34236. })(BABYLON || (BABYLON = {}));
  34237. var BABYLON;
  34238. (function (BABYLON) {
  34239. var Internals;
  34240. (function (Internals) {
  34241. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34242. // All values and structures referenced from:
  34243. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34244. var DDS_MAGIC = 0x20534444;
  34245. 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;
  34246. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34247. 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;
  34248. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34249. function FourCCToInt32(value) {
  34250. return value.charCodeAt(0) +
  34251. (value.charCodeAt(1) << 8) +
  34252. (value.charCodeAt(2) << 16) +
  34253. (value.charCodeAt(3) << 24);
  34254. }
  34255. function Int32ToFourCC(value) {
  34256. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34257. }
  34258. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34259. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34260. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34261. var headerLengthInt = 31; // The header length in 32 bit ints
  34262. // Offsets into the header array
  34263. var off_magic = 0;
  34264. var off_size = 1;
  34265. var off_flags = 2;
  34266. var off_height = 3;
  34267. var off_width = 4;
  34268. var off_mipmapCount = 7;
  34269. var off_pfFlags = 20;
  34270. var off_pfFourCC = 21;
  34271. var off_RGBbpp = 22;
  34272. var off_RMask = 23;
  34273. var off_GMask = 24;
  34274. var off_BMask = 25;
  34275. var off_AMask = 26;
  34276. var off_caps1 = 27;
  34277. var off_caps2 = 28;
  34278. ;
  34279. var DDSTools = (function () {
  34280. function DDSTools() {
  34281. }
  34282. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34283. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34284. var mipmapCount = 1;
  34285. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34286. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34287. }
  34288. return {
  34289. width: header[off_width],
  34290. height: header[off_height],
  34291. mipmapCount: mipmapCount,
  34292. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34293. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34294. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34295. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34296. };
  34297. };
  34298. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34299. var byteArray = new Uint8Array(dataLength);
  34300. var srcData = new Uint8Array(arrayBuffer);
  34301. var index = 0;
  34302. for (var y = height - 1; y >= 0; y--) {
  34303. for (var x = 0; x < width; x++) {
  34304. var srcPos = dataOffset + (x + y * width) * 4;
  34305. byteArray[index + 2] = srcData[srcPos];
  34306. byteArray[index + 1] = srcData[srcPos + 1];
  34307. byteArray[index] = srcData[srcPos + 2];
  34308. byteArray[index + 3] = srcData[srcPos + 3];
  34309. index += 4;
  34310. }
  34311. }
  34312. return byteArray;
  34313. };
  34314. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34315. var byteArray = new Uint8Array(dataLength);
  34316. var srcData = new Uint8Array(arrayBuffer);
  34317. var index = 0;
  34318. for (var y = height - 1; y >= 0; y--) {
  34319. for (var x = 0; x < width; x++) {
  34320. var srcPos = dataOffset + (x + y * width) * 3;
  34321. byteArray[index + 2] = srcData[srcPos];
  34322. byteArray[index + 1] = srcData[srcPos + 1];
  34323. byteArray[index] = srcData[srcPos + 2];
  34324. index += 3;
  34325. }
  34326. }
  34327. return byteArray;
  34328. };
  34329. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34330. var byteArray = new Uint8Array(dataLength);
  34331. var srcData = new Uint8Array(arrayBuffer);
  34332. var index = 0;
  34333. for (var y = height - 1; y >= 0; y--) {
  34334. for (var x = 0; x < width; x++) {
  34335. var srcPos = dataOffset + (x + y * width);
  34336. byteArray[index] = srcData[srcPos];
  34337. index++;
  34338. }
  34339. }
  34340. return byteArray;
  34341. };
  34342. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34343. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34344. if (header[off_magic] != DDS_MAGIC) {
  34345. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34346. return;
  34347. }
  34348. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34349. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34350. return;
  34351. }
  34352. if (info.isFourCC) {
  34353. fourCC = header[off_pfFourCC];
  34354. switch (fourCC) {
  34355. case FOURCC_DXT1:
  34356. blockBytes = 8;
  34357. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34358. break;
  34359. case FOURCC_DXT3:
  34360. blockBytes = 16;
  34361. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34362. break;
  34363. case FOURCC_DXT5:
  34364. blockBytes = 16;
  34365. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34366. break;
  34367. default:
  34368. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34369. return;
  34370. }
  34371. }
  34372. mipmapCount = 1;
  34373. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34374. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34375. }
  34376. var bpp = header[off_RGBbpp];
  34377. for (var face = 0; face < faces; face++) {
  34378. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34379. width = header[off_width];
  34380. height = header[off_height];
  34381. dataOffset = header[off_size] + 4;
  34382. for (i = 0; i < mipmapCount; ++i) {
  34383. if (info.isRGB) {
  34384. if (bpp === 24) {
  34385. dataLength = width * height * 3;
  34386. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34387. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34388. }
  34389. else {
  34390. dataLength = width * height * 4;
  34391. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34392. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34393. }
  34394. }
  34395. else if (info.isLuminance) {
  34396. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34397. var unpaddedRowSize = width;
  34398. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34399. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34400. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34401. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34402. }
  34403. else {
  34404. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34405. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34406. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34407. }
  34408. dataOffset += dataLength;
  34409. width *= 0.5;
  34410. height *= 0.5;
  34411. width = Math.max(1.0, width);
  34412. height = Math.max(1.0, height);
  34413. }
  34414. }
  34415. };
  34416. return DDSTools;
  34417. }());
  34418. Internals.DDSTools = DDSTools;
  34419. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34420. })(BABYLON || (BABYLON = {}));
  34421. var BABYLON;
  34422. (function (BABYLON) {
  34423. var CannonJSPlugin = (function () {
  34424. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  34425. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  34426. if (iterations === void 0) { iterations = 10; }
  34427. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  34428. this.name = "CannonJSPlugin";
  34429. this._physicsMaterials = [];
  34430. this._fixedTimeStep = 1 / 60;
  34431. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34432. this._currentCollisionGroup = 2;
  34433. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  34434. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  34435. this._tmpPosition = BABYLON.Vector3.Zero();
  34436. this._tmpQuaternion = new BABYLON.Quaternion();
  34437. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  34438. this._tmpDeltaRotation = new BABYLON.Quaternion();
  34439. this._tmpUnityRotation = new BABYLON.Quaternion();
  34440. if (!this.isSupported()) {
  34441. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  34442. return;
  34443. }
  34444. this.world = new CANNON.World();
  34445. this.world.broadphase = new CANNON.NaiveBroadphase();
  34446. this.world.solver.iterations = iterations;
  34447. }
  34448. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34449. this.world.gravity.copy(gravity);
  34450. };
  34451. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34452. this._fixedTimeStep = timeStep;
  34453. };
  34454. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34455. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34456. };
  34457. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34458. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34459. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34460. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34461. };
  34462. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34463. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34464. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34465. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34466. };
  34467. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34468. //parent-child relationship. Does this impostor has a parent impostor?
  34469. if (impostor.parent) {
  34470. if (impostor.physicsBody) {
  34471. this.removePhysicsBody(impostor);
  34472. //TODO is that needed?
  34473. impostor.forceUpdate();
  34474. }
  34475. return;
  34476. }
  34477. //should a new body be created for this impostor?
  34478. if (impostor.isBodyInitRequired()) {
  34479. var shape = this._createShape(impostor);
  34480. //unregister events, if body is being changed
  34481. var oldBody = impostor.physicsBody;
  34482. if (oldBody) {
  34483. this.removePhysicsBody(impostor);
  34484. }
  34485. //create the body and material
  34486. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34487. var bodyCreationObject = {
  34488. mass: impostor.getParam("mass"),
  34489. material: material
  34490. };
  34491. // A simple extend, in case native options were used.
  34492. var nativeOptions = impostor.getParam("nativeOptions");
  34493. for (var key in nativeOptions) {
  34494. if (nativeOptions.hasOwnProperty(key)) {
  34495. bodyCreationObject[key] = nativeOptions[key];
  34496. }
  34497. }
  34498. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34499. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34500. this.world.addEventListener("preStep", impostor.beforeStep);
  34501. this.world.addEventListener("postStep", impostor.afterStep);
  34502. impostor.physicsBody.addShape(shape);
  34503. this.world.add(impostor.physicsBody);
  34504. //try to keep the body moving in the right direction by taking old properties.
  34505. //Should be tested!
  34506. if (oldBody) {
  34507. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34508. impostor.physicsBody[param].copy(oldBody[param]);
  34509. });
  34510. }
  34511. this._processChildMeshes(impostor);
  34512. }
  34513. //now update the body's transformation
  34514. this._updatePhysicsBodyTransformation(impostor);
  34515. };
  34516. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34517. var _this = this;
  34518. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34519. if (meshChildren.length) {
  34520. var processMesh = function (localPosition, mesh) {
  34521. var childImpostor = mesh.getPhysicsImpostor();
  34522. if (childImpostor) {
  34523. var parent = childImpostor.parent;
  34524. if (parent !== mainImpostor) {
  34525. var localPosition = mesh.position;
  34526. if (childImpostor.physicsBody) {
  34527. _this.removePhysicsBody(childImpostor);
  34528. childImpostor.physicsBody = null;
  34529. }
  34530. childImpostor.parent = mainImpostor;
  34531. childImpostor.resetUpdateFlags();
  34532. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34533. //Add the mass of the children.
  34534. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34535. }
  34536. }
  34537. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34538. };
  34539. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34540. }
  34541. };
  34542. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34543. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34544. this.world.removeEventListener("preStep", impostor.beforeStep);
  34545. this.world.removeEventListener("postStep", impostor.afterStep);
  34546. this.world.remove(impostor.physicsBody);
  34547. };
  34548. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34549. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34550. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34551. if (!mainBody || !connectedBody) {
  34552. return;
  34553. }
  34554. var constraint;
  34555. var jointData = impostorJoint.joint.jointData;
  34556. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34557. var constraintData = {
  34558. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34559. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34560. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34561. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34562. maxForce: jointData.nativeParams.maxForce,
  34563. collideConnected: !!jointData.collision
  34564. };
  34565. //Not needed, Cannon has a collideConnected flag
  34566. /*if (!jointData.collision) {
  34567. //add 1st body to a collision group of its own, if it is not in 1
  34568. if (mainBody.collisionFilterGroup === 1) {
  34569. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34570. this._currentCollisionGroup <<= 1;
  34571. }
  34572. if (connectedBody.collisionFilterGroup === 1) {
  34573. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34574. this._currentCollisionGroup <<= 1;
  34575. }
  34576. //add their mask to the collisionFilterMask of each other:
  34577. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34578. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34579. }*/
  34580. switch (impostorJoint.joint.type) {
  34581. case BABYLON.PhysicsJoint.HingeJoint:
  34582. case BABYLON.PhysicsJoint.Hinge2Joint:
  34583. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34584. break;
  34585. case BABYLON.PhysicsJoint.DistanceJoint:
  34586. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34587. break;
  34588. case BABYLON.PhysicsJoint.SpringJoint:
  34589. var springData = jointData;
  34590. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34591. restLength: springData.length,
  34592. stiffness: springData.stiffness,
  34593. damping: springData.damping,
  34594. localAnchorA: constraintData.pivotA,
  34595. localAnchorB: constraintData.pivotB
  34596. });
  34597. break;
  34598. case BABYLON.PhysicsJoint.PointToPointJoint:
  34599. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34600. default:
  34601. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34602. break;
  34603. }
  34604. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34605. constraint.collideConnected = !!jointData.collision;
  34606. impostorJoint.joint.physicsJoint = constraint;
  34607. //don't add spring as constraint, as it is not one.
  34608. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34609. this.world.addConstraint(constraint);
  34610. }
  34611. else {
  34612. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34613. constraint.applyForce();
  34614. });
  34615. }
  34616. };
  34617. CannonJSPlugin.prototype.removeJoint = function (joint) {
  34618. //TODO
  34619. };
  34620. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34621. var index;
  34622. var mat;
  34623. for (index = 0; index < this._physicsMaterials.length; index++) {
  34624. mat = this._physicsMaterials[index];
  34625. if (mat.friction === friction && mat.restitution === restitution) {
  34626. return mat;
  34627. }
  34628. }
  34629. var currentMat = new CANNON.Material("mat");
  34630. currentMat.friction = friction;
  34631. currentMat.restitution = restitution;
  34632. this._physicsMaterials.push(currentMat);
  34633. return currentMat;
  34634. };
  34635. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34636. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34637. };
  34638. CannonJSPlugin.prototype._createShape = function (impostor) {
  34639. var object = impostor.object;
  34640. var returnValue;
  34641. var extendSize = impostor.getObjectExtendSize();
  34642. switch (impostor.type) {
  34643. case BABYLON.PhysicsEngine.SphereImpostor:
  34644. var radiusX = extendSize.x;
  34645. var radiusY = extendSize.y;
  34646. var radiusZ = extendSize.z;
  34647. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34648. break;
  34649. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34650. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34651. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34652. break;
  34653. case BABYLON.PhysicsImpostor.BoxImpostor:
  34654. var box = extendSize.scale(0.5);
  34655. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34656. break;
  34657. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34658. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34659. returnValue = new CANNON.Plane();
  34660. break;
  34661. case BABYLON.PhysicsImpostor.MeshImpostor:
  34662. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34663. var rawFaces = object.getIndices ? object.getIndices() : [];
  34664. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34665. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34666. break;
  34667. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34668. returnValue = this._createHeightmap(object);
  34669. break;
  34670. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34671. returnValue = new CANNON.Particle();
  34672. break;
  34673. }
  34674. return returnValue;
  34675. };
  34676. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34677. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34678. var matrix = [];
  34679. //For now pointDepth will not be used and will be automatically calculated.
  34680. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34681. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34682. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34683. var elementSize = dim * 2 / arraySize;
  34684. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34685. for (var i = 0; i < pos.length; i = i + 3) {
  34686. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34687. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34688. var y = pos[i + 1] + minY;
  34689. if (!matrix[x]) {
  34690. matrix[x] = [];
  34691. }
  34692. if (!matrix[x][z]) {
  34693. matrix[x][z] = y;
  34694. }
  34695. matrix[x][z] = Math.max(y, matrix[x][z]);
  34696. }
  34697. for (var x = 0; x <= arraySize; ++x) {
  34698. if (!matrix[x]) {
  34699. var loc = 1;
  34700. while (!matrix[(x + loc) % arraySize]) {
  34701. loc++;
  34702. }
  34703. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34704. }
  34705. for (var z = 0; z <= arraySize; ++z) {
  34706. if (!matrix[x][z]) {
  34707. var loc = 1;
  34708. var newValue;
  34709. while (newValue === undefined) {
  34710. newValue = matrix[x][(z + loc++) % arraySize];
  34711. }
  34712. matrix[x][z] = newValue;
  34713. }
  34714. }
  34715. }
  34716. var shape = new CANNON.Heightfield(matrix, {
  34717. elementSize: elementSize
  34718. });
  34719. //For future reference, needed for body transformation
  34720. shape.minY = minY;
  34721. return shape;
  34722. };
  34723. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34724. var object = impostor.object;
  34725. //make sure it is updated...
  34726. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34727. // The delta between the mesh position and the mesh bounding box center
  34728. var center = impostor.getObjectCenter();
  34729. var extendSize = impostor.getObjectExtendSize();
  34730. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34731. this._tmpPosition.copyFrom(center);
  34732. var quaternion = object.rotationQuaternion;
  34733. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34734. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34735. //-90 DEG in X, precalculated
  34736. quaternion = quaternion.multiply(this._minus90X);
  34737. //Invert! (Precalculated, 90 deg in X)
  34738. //No need to clone. this will never change.
  34739. impostor.setDeltaRotation(this._plus90X);
  34740. }
  34741. //If it is a heightfield, if should be centered.
  34742. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34743. var mesh = object;
  34744. //calculate the correct body position:
  34745. var rotationQuaternion = mesh.rotationQuaternion;
  34746. mesh.rotationQuaternion = this._tmpUnityRotation;
  34747. mesh.computeWorldMatrix(true);
  34748. //get original center with no rotation
  34749. var c = center.clone();
  34750. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34751. //rotation is back
  34752. mesh.rotationQuaternion = rotationQuaternion;
  34753. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34754. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34755. mesh.setPivotMatrix(p);
  34756. mesh.computeWorldMatrix(true);
  34757. //calculate the translation
  34758. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34759. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34760. //add it inverted to the delta
  34761. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34762. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34763. mesh.setPivotMatrix(oldPivot);
  34764. mesh.computeWorldMatrix(true);
  34765. }
  34766. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34767. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34768. this._tmpPosition.copyFrom(object.position);
  34769. }
  34770. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34771. //Now update the impostor object
  34772. impostor.physicsBody.position.copy(this._tmpPosition);
  34773. impostor.physicsBody.quaternion.copy(quaternion);
  34774. };
  34775. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34776. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34777. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34778. };
  34779. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34780. impostor.physicsBody.position.copy(newPosition);
  34781. impostor.physicsBody.quaternion.copy(newRotation);
  34782. };
  34783. CannonJSPlugin.prototype.isSupported = function () {
  34784. return window.CANNON !== undefined;
  34785. };
  34786. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34787. impostor.physicsBody.velocity.copy(velocity);
  34788. };
  34789. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34790. impostor.physicsBody.angularVelocity.copy(velocity);
  34791. };
  34792. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34793. var v = impostor.physicsBody.velocity;
  34794. if (!v)
  34795. return null;
  34796. return new BABYLON.Vector3(v.x, v.y, v.z);
  34797. };
  34798. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34799. var v = impostor.physicsBody.angularVelocity;
  34800. if (!v)
  34801. return null;
  34802. return new BABYLON.Vector3(v.x, v.y, v.z);
  34803. };
  34804. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34805. impostor.physicsBody.mass = mass;
  34806. impostor.physicsBody.updateMassProperties();
  34807. };
  34808. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34809. impostor.physicsBody.sleep();
  34810. };
  34811. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34812. impostor.physicsBody.wakeUp();
  34813. };
  34814. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34815. joint.physicsJoint.distance = maxDistance;
  34816. };
  34817. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34818. if (!motorIndex) {
  34819. joint.physicsJoint.enableMotor();
  34820. }
  34821. };
  34822. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34823. if (!motorIndex) {
  34824. joint.physicsJoint.disableMotor();
  34825. }
  34826. };
  34827. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34828. if (!motorIndex) {
  34829. joint.physicsJoint.enableMotor();
  34830. joint.physicsJoint.setMotorSpeed(speed);
  34831. if (maxForce) {
  34832. this.setLimit(joint, maxForce);
  34833. }
  34834. }
  34835. };
  34836. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  34837. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  34838. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  34839. };
  34840. CannonJSPlugin.prototype.dispose = function () {
  34841. //nothing to do, actually.
  34842. };
  34843. return CannonJSPlugin;
  34844. }());
  34845. BABYLON.CannonJSPlugin = CannonJSPlugin;
  34846. })(BABYLON || (BABYLON = {}));
  34847. var BABYLON;
  34848. (function (BABYLON) {
  34849. var OimoJSPlugin = (function () {
  34850. function OimoJSPlugin(iterations) {
  34851. this.name = "OimoJSPlugin";
  34852. this._tmpImpostorsArray = [];
  34853. this._tmpPositionVector = BABYLON.Vector3.Zero();
  34854. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  34855. this.world.clear();
  34856. //making sure no stats are calculated
  34857. this.world.isNoStat = true;
  34858. }
  34859. OimoJSPlugin.prototype.setGravity = function (gravity) {
  34860. this.world.gravity.copy(gravity);
  34861. };
  34862. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  34863. this.world.timeStep = timeStep;
  34864. };
  34865. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  34866. var _this = this;
  34867. impostors.forEach(function (impostor) {
  34868. impostor.beforeStep();
  34869. });
  34870. this.world.step();
  34871. impostors.forEach(function (impostor) {
  34872. impostor.afterStep();
  34873. //update the ordered impostors array
  34874. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  34875. });
  34876. //check for collisions
  34877. var contact = this.world.contacts;
  34878. while (contact !== null) {
  34879. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  34880. contact = contact.next;
  34881. continue;
  34882. }
  34883. //is this body colliding with any other? get the impostor
  34884. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  34885. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  34886. if (!mainImpostor || !collidingImpostor) {
  34887. contact = contact.next;
  34888. continue;
  34889. }
  34890. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  34891. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  34892. contact = contact.next;
  34893. }
  34894. };
  34895. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34896. var mass = impostor.physicsBody.massInfo.mass;
  34897. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  34898. };
  34899. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34900. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  34901. this.applyImpulse(impostor, force, contactPoint);
  34902. };
  34903. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34904. var _this = this;
  34905. //parent-child relationship. Does this impostor has a parent impostor?
  34906. if (impostor.parent) {
  34907. if (impostor.physicsBody) {
  34908. this.removePhysicsBody(impostor);
  34909. //TODO is that needed?
  34910. impostor.forceUpdate();
  34911. }
  34912. return;
  34913. }
  34914. if (impostor.isBodyInitRequired()) {
  34915. var bodyConfig = {
  34916. name: impostor.uniqueId,
  34917. //Oimo must have mass, also for static objects.
  34918. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  34919. size: [],
  34920. type: [],
  34921. pos: [],
  34922. rot: [],
  34923. move: impostor.getParam("mass") !== 0,
  34924. //Supporting older versions of Oimo
  34925. world: this.world
  34926. };
  34927. var impostors = [impostor];
  34928. function addToArray(parent) {
  34929. if (!parent.getChildMeshes)
  34930. return;
  34931. parent.getChildMeshes().forEach(function (m) {
  34932. if (m.physicsImpostor) {
  34933. impostors.push(m.physicsImpostor);
  34934. m.physicsImpostor._init();
  34935. }
  34936. });
  34937. }
  34938. addToArray(impostor.object);
  34939. function checkWithEpsilon(value) {
  34940. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  34941. }
  34942. impostors.forEach(function (i) {
  34943. //get the correct bounding box
  34944. var oldQuaternion = i.object.rotationQuaternion;
  34945. var rot = new OIMO.Euler().setFromQuaternion({
  34946. x: impostor.object.rotationQuaternion.x,
  34947. y: impostor.object.rotationQuaternion.y,
  34948. z: impostor.object.rotationQuaternion.z,
  34949. s: impostor.object.rotationQuaternion.w });
  34950. var extendSize = i.getObjectExtendSize();
  34951. if (i === impostor) {
  34952. var center = impostor.getObjectCenter();
  34953. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  34954. //Can also use Array.prototype.push.apply
  34955. bodyConfig.pos.push(center.x);
  34956. bodyConfig.pos.push(center.y);
  34957. bodyConfig.pos.push(center.z);
  34958. //tmp solution
  34959. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  34960. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  34961. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  34962. }
  34963. else {
  34964. bodyConfig.pos.push(i.object.position.x);
  34965. bodyConfig.pos.push(i.object.position.y);
  34966. bodyConfig.pos.push(i.object.position.z);
  34967. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  34968. bodyConfig.rot.push(0);
  34969. bodyConfig.rot.push(0);
  34970. bodyConfig.rot.push(0);
  34971. }
  34972. // register mesh
  34973. switch (i.type) {
  34974. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34975. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  34976. case BABYLON.PhysicsImpostor.SphereImpostor:
  34977. var radiusX = extendSize.x;
  34978. var radiusY = extendSize.y;
  34979. var radiusZ = extendSize.z;
  34980. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  34981. bodyConfig.type.push('sphere');
  34982. //due to the way oimo works with compounds, add 3 times
  34983. bodyConfig.size.push(size);
  34984. bodyConfig.size.push(size);
  34985. bodyConfig.size.push(size);
  34986. break;
  34987. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34988. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  34989. var sizeY = checkWithEpsilon(extendSize.y);
  34990. bodyConfig.type.push('cylinder');
  34991. bodyConfig.size.push(sizeX);
  34992. bodyConfig.size.push(sizeY);
  34993. //due to the way oimo works with compounds, add one more value.
  34994. bodyConfig.size.push(sizeY);
  34995. break;
  34996. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34997. case BABYLON.PhysicsImpostor.BoxImpostor:
  34998. default:
  34999. var sizeX = checkWithEpsilon(extendSize.x);
  35000. var sizeY = checkWithEpsilon(extendSize.y);
  35001. var sizeZ = checkWithEpsilon(extendSize.z);
  35002. bodyConfig.type.push('box');
  35003. bodyConfig.size.push(sizeX);
  35004. bodyConfig.size.push(sizeY);
  35005. bodyConfig.size.push(sizeZ);
  35006. break;
  35007. }
  35008. //actually not needed, but hey...
  35009. i.object.rotationQuaternion = oldQuaternion;
  35010. });
  35011. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  35012. }
  35013. else {
  35014. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  35015. }
  35016. impostor.setDeltaPosition(this._tmpPositionVector);
  35017. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  35018. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  35019. };
  35020. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35021. //impostor.physicsBody.dispose();
  35022. //Same as : (older oimo versions)
  35023. this.world.removeRigidBody(impostor.physicsBody);
  35024. };
  35025. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35026. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35027. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35028. if (!mainBody || !connectedBody) {
  35029. return;
  35030. }
  35031. var jointData = impostorJoint.joint.jointData;
  35032. var options = jointData.nativeParams || {};
  35033. var type;
  35034. var nativeJointData = {
  35035. body1: mainBody,
  35036. body2: connectedBody,
  35037. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35038. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35039. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35040. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35041. min: options.min,
  35042. max: options.max,
  35043. collision: options.collision || jointData.collision,
  35044. spring: options.spring,
  35045. //supporting older version of Oimo
  35046. world: this.world
  35047. };
  35048. switch (impostorJoint.joint.type) {
  35049. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35050. type = "jointBall";
  35051. break;
  35052. case BABYLON.PhysicsJoint.SpringJoint:
  35053. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35054. var springData = jointData;
  35055. nativeJointData.min = springData.length || nativeJointData.min;
  35056. //Max should also be set, just make sure it is at least min
  35057. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35058. case BABYLON.PhysicsJoint.DistanceJoint:
  35059. type = "jointDistance";
  35060. nativeJointData.max = jointData.maxDistance;
  35061. break;
  35062. case BABYLON.PhysicsJoint.PrismaticJoint:
  35063. type = "jointPrisme";
  35064. break;
  35065. case BABYLON.PhysicsJoint.SliderJoint:
  35066. type = "jointSlide";
  35067. break;
  35068. case BABYLON.PhysicsJoint.WheelJoint:
  35069. type = "jointWheel";
  35070. break;
  35071. case BABYLON.PhysicsJoint.HingeJoint:
  35072. default:
  35073. type = "jointHinge";
  35074. break;
  35075. }
  35076. nativeJointData.type = type;
  35077. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35078. };
  35079. OimoJSPlugin.prototype.removeJoint = function (joint) {
  35080. joint.joint.physicsJoint.dispose();
  35081. };
  35082. OimoJSPlugin.prototype.isSupported = function () {
  35083. return OIMO !== undefined;
  35084. };
  35085. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35086. if (!impostor.physicsBody.sleeping) {
  35087. //TODO check that
  35088. if (impostor.physicsBody.shapes.next) {
  35089. var parentShape = this._getLastShape(impostor.physicsBody);
  35090. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35091. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35092. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35093. }
  35094. else {
  35095. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35096. }
  35097. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35098. }
  35099. };
  35100. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35101. var body = impostor.physicsBody;
  35102. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35103. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35104. body.syncShapes();
  35105. body.awake();
  35106. };
  35107. OimoJSPlugin.prototype._getLastShape = function (body) {
  35108. var lastShape = body.shapes;
  35109. while (lastShape.next) {
  35110. lastShape = lastShape.next;
  35111. }
  35112. return lastShape;
  35113. };
  35114. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35115. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35116. };
  35117. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35118. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35119. };
  35120. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35121. var v = impostor.physicsBody.linearVelocity;
  35122. if (!v)
  35123. return null;
  35124. return new BABYLON.Vector3(v.x, v.y, v.z);
  35125. };
  35126. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35127. var v = impostor.physicsBody.angularVelocity;
  35128. if (!v)
  35129. return null;
  35130. return new BABYLON.Vector3(v.x, v.y, v.z);
  35131. };
  35132. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35133. var staticBody = mass === 0;
  35134. //this will actually set the body's density and not its mass.
  35135. //But this is how oimo treats the mass variable.
  35136. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35137. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35138. };
  35139. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35140. impostor.physicsBody.sleep();
  35141. };
  35142. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35143. impostor.physicsBody.awake();
  35144. };
  35145. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35146. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35147. if (minDistance !== void 0) {
  35148. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35149. }
  35150. };
  35151. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35152. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35153. if (motor) {
  35154. motor.setMotor(speed, maxForce);
  35155. }
  35156. };
  35157. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35158. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35159. if (motor) {
  35160. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35161. }
  35162. };
  35163. OimoJSPlugin.prototype.dispose = function () {
  35164. this.world.clear();
  35165. };
  35166. return OimoJSPlugin;
  35167. }());
  35168. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35169. })(BABYLON || (BABYLON = {}));
  35170. var BABYLON;
  35171. (function (BABYLON) {
  35172. var DisplayPassPostProcess = (function (_super) {
  35173. __extends(DisplayPassPostProcess, _super);
  35174. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35175. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35176. }
  35177. return DisplayPassPostProcess;
  35178. }(BABYLON.PostProcess));
  35179. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35180. })(BABYLON || (BABYLON = {}));
  35181. var BABYLON;
  35182. (function (BABYLON) {
  35183. var SimplificationSettings = (function () {
  35184. function SimplificationSettings(quality, distance, optimizeMesh) {
  35185. this.quality = quality;
  35186. this.distance = distance;
  35187. this.optimizeMesh = optimizeMesh;
  35188. }
  35189. return SimplificationSettings;
  35190. }());
  35191. BABYLON.SimplificationSettings = SimplificationSettings;
  35192. var SimplificationQueue = (function () {
  35193. function SimplificationQueue() {
  35194. this.running = false;
  35195. this._simplificationArray = [];
  35196. }
  35197. SimplificationQueue.prototype.addTask = function (task) {
  35198. this._simplificationArray.push(task);
  35199. };
  35200. SimplificationQueue.prototype.executeNext = function () {
  35201. var task = this._simplificationArray.pop();
  35202. if (task) {
  35203. this.running = true;
  35204. this.runSimplification(task);
  35205. }
  35206. else {
  35207. this.running = false;
  35208. }
  35209. };
  35210. SimplificationQueue.prototype.runSimplification = function (task) {
  35211. var _this = this;
  35212. if (task.parallelProcessing) {
  35213. //parallel simplifier
  35214. task.settings.forEach(function (setting) {
  35215. var simplifier = _this.getSimplifier(task);
  35216. simplifier.simplify(setting, function (newMesh) {
  35217. task.mesh.addLODLevel(setting.distance, newMesh);
  35218. newMesh.isVisible = true;
  35219. //check if it is the last
  35220. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35221. //all done, run the success callback.
  35222. task.successCallback();
  35223. }
  35224. _this.executeNext();
  35225. });
  35226. });
  35227. }
  35228. else {
  35229. //single simplifier.
  35230. var simplifier = this.getSimplifier(task);
  35231. var runDecimation = function (setting, callback) {
  35232. simplifier.simplify(setting, function (newMesh) {
  35233. task.mesh.addLODLevel(setting.distance, newMesh);
  35234. newMesh.isVisible = true;
  35235. //run the next quality level
  35236. callback();
  35237. });
  35238. };
  35239. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35240. runDecimation(task.settings[loop.index], function () {
  35241. loop.executeNext();
  35242. });
  35243. }, function () {
  35244. //execution ended, run the success callback.
  35245. if (task.successCallback) {
  35246. task.successCallback();
  35247. }
  35248. _this.executeNext();
  35249. });
  35250. }
  35251. };
  35252. SimplificationQueue.prototype.getSimplifier = function (task) {
  35253. switch (task.simplificationType) {
  35254. case SimplificationType.QUADRATIC:
  35255. default:
  35256. return new QuadraticErrorSimplification(task.mesh);
  35257. }
  35258. };
  35259. return SimplificationQueue;
  35260. }());
  35261. BABYLON.SimplificationQueue = SimplificationQueue;
  35262. /**
  35263. * The implemented types of simplification.
  35264. * At the moment only Quadratic Error Decimation is implemented.
  35265. */
  35266. (function (SimplificationType) {
  35267. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35268. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35269. var SimplificationType = BABYLON.SimplificationType;
  35270. var DecimationTriangle = (function () {
  35271. function DecimationTriangle(vertices) {
  35272. this.vertices = vertices;
  35273. this.error = new Array(4);
  35274. this.deleted = false;
  35275. this.isDirty = false;
  35276. this.deletePending = false;
  35277. this.borderFactor = 0;
  35278. }
  35279. return DecimationTriangle;
  35280. }());
  35281. BABYLON.DecimationTriangle = DecimationTriangle;
  35282. var DecimationVertex = (function () {
  35283. function DecimationVertex(position, id) {
  35284. this.position = position;
  35285. this.id = id;
  35286. this.isBorder = true;
  35287. this.q = new QuadraticMatrix();
  35288. this.triangleCount = 0;
  35289. this.triangleStart = 0;
  35290. this.originalOffsets = [];
  35291. }
  35292. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35293. this.position.copyFrom(newPosition);
  35294. };
  35295. return DecimationVertex;
  35296. }());
  35297. BABYLON.DecimationVertex = DecimationVertex;
  35298. var QuadraticMatrix = (function () {
  35299. function QuadraticMatrix(data) {
  35300. this.data = new Array(10);
  35301. for (var i = 0; i < 10; ++i) {
  35302. if (data && data[i]) {
  35303. this.data[i] = data[i];
  35304. }
  35305. else {
  35306. this.data[i] = 0;
  35307. }
  35308. }
  35309. }
  35310. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35311. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35312. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35313. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35314. return det;
  35315. };
  35316. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35317. for (var i = 0; i < 10; ++i) {
  35318. this.data[i] += matrix.data[i];
  35319. }
  35320. };
  35321. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35322. for (var i = 0; i < 10; ++i) {
  35323. this.data[i] += data[i];
  35324. }
  35325. };
  35326. QuadraticMatrix.prototype.add = function (matrix) {
  35327. var m = new QuadraticMatrix();
  35328. for (var i = 0; i < 10; ++i) {
  35329. m.data[i] = this.data[i] + matrix.data[i];
  35330. }
  35331. return m;
  35332. };
  35333. QuadraticMatrix.FromData = function (a, b, c, d) {
  35334. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35335. };
  35336. //returning an array to avoid garbage collection
  35337. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35338. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35339. };
  35340. return QuadraticMatrix;
  35341. }());
  35342. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35343. var Reference = (function () {
  35344. function Reference(vertexId, triangleId) {
  35345. this.vertexId = vertexId;
  35346. this.triangleId = triangleId;
  35347. }
  35348. return Reference;
  35349. }());
  35350. BABYLON.Reference = Reference;
  35351. /**
  35352. * An implementation of the Quadratic Error simplification algorithm.
  35353. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35354. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35355. * @author RaananW
  35356. */
  35357. var QuadraticErrorSimplification = (function () {
  35358. function QuadraticErrorSimplification(_mesh) {
  35359. this._mesh = _mesh;
  35360. this.initialized = false;
  35361. this.syncIterations = 5000;
  35362. this.aggressiveness = 7;
  35363. this.decimationIterations = 100;
  35364. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35365. }
  35366. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35367. var _this = this;
  35368. this.initDecimatedMesh();
  35369. //iterating through the submeshes array, one after the other.
  35370. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35371. _this.initWithMesh(loop.index, function () {
  35372. _this.runDecimation(settings, loop.index, function () {
  35373. loop.executeNext();
  35374. });
  35375. }, settings.optimizeMesh);
  35376. }, function () {
  35377. setTimeout(function () {
  35378. successCallback(_this._reconstructedMesh);
  35379. }, 0);
  35380. });
  35381. };
  35382. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35383. var _this = this;
  35384. var gCount = 0;
  35385. triangle.vertices.forEach(function (vertex) {
  35386. var count = 0;
  35387. var vPos = vertex.position;
  35388. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35389. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35390. ++count;
  35391. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35392. ++count;
  35393. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35394. ++count;
  35395. if (count > 1) {
  35396. ++gCount;
  35397. }
  35398. ;
  35399. });
  35400. if (gCount > 1) {
  35401. console.log(triangle, gCount);
  35402. }
  35403. return gCount > 1;
  35404. };
  35405. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35406. var _this = this;
  35407. var targetCount = ~~(this.triangles.length * settings.quality);
  35408. var deletedTriangles = 0;
  35409. var triangleCount = this.triangles.length;
  35410. var iterationFunction = function (iteration, callback) {
  35411. setTimeout(function () {
  35412. if (iteration % 5 === 0) {
  35413. _this.updateMesh(iteration === 0);
  35414. }
  35415. for (var i = 0; i < _this.triangles.length; ++i) {
  35416. _this.triangles[i].isDirty = false;
  35417. }
  35418. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  35419. var trianglesIterator = function (i) {
  35420. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  35421. var t = _this.triangles[tIdx];
  35422. if (!t)
  35423. return;
  35424. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  35425. return;
  35426. }
  35427. for (var j = 0; j < 3; ++j) {
  35428. if (t.error[j] < threshold) {
  35429. var deleted0 = [];
  35430. var deleted1 = [];
  35431. var v0 = t.vertices[j];
  35432. var v1 = t.vertices[(j + 1) % 3];
  35433. if (v0.isBorder || v1.isBorder)
  35434. continue;
  35435. var p = BABYLON.Vector3.Zero();
  35436. var n = BABYLON.Vector3.Zero();
  35437. var uv = BABYLON.Vector2.Zero();
  35438. var color = new BABYLON.Color4(0, 0, 0, 1);
  35439. _this.calculateError(v0, v1, p, n, uv, color);
  35440. var delTr = [];
  35441. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  35442. continue;
  35443. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  35444. continue;
  35445. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  35446. continue;
  35447. var uniqueArray = [];
  35448. delTr.forEach(function (deletedT) {
  35449. if (uniqueArray.indexOf(deletedT) === -1) {
  35450. deletedT.deletePending = true;
  35451. uniqueArray.push(deletedT);
  35452. }
  35453. });
  35454. if (uniqueArray.length % 2 !== 0) {
  35455. continue;
  35456. }
  35457. v0.q = v1.q.add(v0.q);
  35458. v0.updatePosition(p);
  35459. var tStart = _this.references.length;
  35460. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35461. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35462. var tCount = _this.references.length - tStart;
  35463. if (tCount <= v0.triangleCount) {
  35464. if (tCount) {
  35465. for (var c = 0; c < tCount; c++) {
  35466. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35467. }
  35468. }
  35469. }
  35470. else {
  35471. v0.triangleStart = tStart;
  35472. }
  35473. v0.triangleCount = tCount;
  35474. break;
  35475. }
  35476. }
  35477. };
  35478. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35479. }, 0);
  35480. };
  35481. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35482. if (triangleCount - deletedTriangles <= targetCount)
  35483. loop.breakLoop();
  35484. else {
  35485. iterationFunction(loop.index, function () {
  35486. loop.executeNext();
  35487. });
  35488. }
  35489. }, function () {
  35490. setTimeout(function () {
  35491. //reconstruct this part of the mesh
  35492. _this.reconstructMesh(submeshIndex);
  35493. successCallback();
  35494. }, 0);
  35495. });
  35496. };
  35497. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35498. var _this = this;
  35499. this.vertices = [];
  35500. this.triangles = [];
  35501. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35502. var indices = this._mesh.getIndices();
  35503. var submesh = this._mesh.subMeshes[submeshIndex];
  35504. var findInVertices = function (positionToSearch) {
  35505. if (optimizeMesh) {
  35506. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35507. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35508. return _this.vertices[ii];
  35509. }
  35510. }
  35511. }
  35512. return null;
  35513. };
  35514. var vertexReferences = [];
  35515. var vertexInit = function (i) {
  35516. var offset = i + submesh.verticesStart;
  35517. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35518. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35519. vertex.originalOffsets.push(offset);
  35520. if (vertex.id === _this.vertices.length) {
  35521. _this.vertices.push(vertex);
  35522. }
  35523. vertexReferences.push(vertex.id);
  35524. };
  35525. //var totalVertices = mesh.getTotalVertices();
  35526. var totalVertices = submesh.verticesCount;
  35527. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35528. var indicesInit = function (i) {
  35529. var offset = (submesh.indexStart / 3) + i;
  35530. var pos = (offset * 3);
  35531. var i0 = indices[pos + 0];
  35532. var i1 = indices[pos + 1];
  35533. var i2 = indices[pos + 2];
  35534. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35535. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35536. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35537. var triangle = new DecimationTriangle([v0, v1, v2]);
  35538. triangle.originalOffset = pos;
  35539. _this.triangles.push(triangle);
  35540. };
  35541. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35542. _this.init(callback);
  35543. });
  35544. });
  35545. };
  35546. QuadraticErrorSimplification.prototype.init = function (callback) {
  35547. var _this = this;
  35548. var triangleInit1 = function (i) {
  35549. var t = _this.triangles[i];
  35550. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35551. for (var j = 0; j < 3; j++) {
  35552. 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))));
  35553. }
  35554. };
  35555. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35556. var triangleInit2 = function (i) {
  35557. var t = _this.triangles[i];
  35558. for (var j = 0; j < 3; ++j) {
  35559. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35560. }
  35561. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35562. };
  35563. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35564. _this.initialized = true;
  35565. callback();
  35566. });
  35567. });
  35568. };
  35569. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35570. var newTriangles = [];
  35571. var i;
  35572. for (i = 0; i < this.vertices.length; ++i) {
  35573. this.vertices[i].triangleCount = 0;
  35574. }
  35575. var t;
  35576. var j;
  35577. for (i = 0; i < this.triangles.length; ++i) {
  35578. if (!this.triangles[i].deleted) {
  35579. t = this.triangles[i];
  35580. for (j = 0; j < 3; ++j) {
  35581. t.vertices[j].triangleCount = 1;
  35582. }
  35583. newTriangles.push(t);
  35584. }
  35585. }
  35586. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35587. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35588. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35589. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35590. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35591. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35592. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35593. var vertexCount = 0;
  35594. for (i = 0; i < this.vertices.length; ++i) {
  35595. var vertex = this.vertices[i];
  35596. vertex.id = vertexCount;
  35597. if (vertex.triangleCount) {
  35598. vertex.originalOffsets.forEach(function (originalOffset) {
  35599. newPositionData.push(vertex.position.x);
  35600. newPositionData.push(vertex.position.y);
  35601. newPositionData.push(vertex.position.z);
  35602. newNormalData.push(normalData[originalOffset * 3]);
  35603. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35604. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35605. if (uvs && uvs.length) {
  35606. newUVsData.push(uvs[(originalOffset * 2)]);
  35607. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35608. }
  35609. else if (colorsData && colorsData.length) {
  35610. newColorsData.push(colorsData[(originalOffset * 4)]);
  35611. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35612. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35613. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35614. }
  35615. ++vertexCount;
  35616. });
  35617. }
  35618. }
  35619. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35620. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35621. var submeshesArray = this._reconstructedMesh.subMeshes;
  35622. this._reconstructedMesh.subMeshes = [];
  35623. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35624. var originalIndices = this._mesh.getIndices();
  35625. for (i = 0; i < newTriangles.length; ++i) {
  35626. t = newTriangles[i]; //now get the new referencing point for each vertex
  35627. [0, 1, 2].forEach(function (idx) {
  35628. var id = originalIndices[t.originalOffset + idx];
  35629. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35630. if (offset < 0)
  35631. offset = 0;
  35632. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35633. });
  35634. }
  35635. //overwriting the old vertex buffers and indices.
  35636. this._reconstructedMesh.setIndices(newIndicesArray);
  35637. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35638. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35639. if (newUVsData.length > 0)
  35640. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35641. if (newColorsData.length > 0)
  35642. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35643. //create submesh
  35644. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35645. if (submeshIndex > 0) {
  35646. this._reconstructedMesh.subMeshes = [];
  35647. submeshesArray.forEach(function (submesh) {
  35648. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35649. });
  35650. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35651. }
  35652. };
  35653. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35654. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35655. this._reconstructedMesh.material = this._mesh.material;
  35656. this._reconstructedMesh.parent = this._mesh.parent;
  35657. this._reconstructedMesh.isVisible = false;
  35658. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35659. };
  35660. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35661. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35662. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35663. if (t.deleted)
  35664. continue;
  35665. var s = this.references[vertex1.triangleStart + i].vertexId;
  35666. var v1 = t.vertices[(s + 1) % 3];
  35667. var v2 = t.vertices[(s + 2) % 3];
  35668. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35669. deletedArray[i] = true;
  35670. delTr.push(t);
  35671. continue;
  35672. }
  35673. var d1 = v1.position.subtract(point);
  35674. d1 = d1.normalize();
  35675. var d2 = v2.position.subtract(point);
  35676. d2 = d2.normalize();
  35677. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35678. return true;
  35679. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35680. deletedArray[i] = false;
  35681. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35682. return true;
  35683. }
  35684. return false;
  35685. };
  35686. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35687. var newDeleted = deletedTriangles;
  35688. for (var i = 0; i < vertex.triangleCount; ++i) {
  35689. var ref = this.references[vertex.triangleStart + i];
  35690. var t = this.triangles[ref.triangleId];
  35691. if (t.deleted)
  35692. continue;
  35693. if (deletedArray[i] && t.deletePending) {
  35694. t.deleted = true;
  35695. newDeleted++;
  35696. continue;
  35697. }
  35698. t.vertices[ref.vertexId] = origVertex;
  35699. t.isDirty = true;
  35700. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35701. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35702. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35703. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35704. this.references.push(ref);
  35705. }
  35706. return newDeleted;
  35707. };
  35708. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35709. for (var i = 0; i < this.vertices.length; ++i) {
  35710. var vCount = [];
  35711. var vId = [];
  35712. var v = this.vertices[i];
  35713. var j;
  35714. for (j = 0; j < v.triangleCount; ++j) {
  35715. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35716. for (var ii = 0; ii < 3; ii++) {
  35717. var ofs = 0;
  35718. var vv = triangle.vertices[ii];
  35719. while (ofs < vCount.length) {
  35720. if (vId[ofs] === vv.id)
  35721. break;
  35722. ++ofs;
  35723. }
  35724. if (ofs === vCount.length) {
  35725. vCount.push(1);
  35726. vId.push(vv.id);
  35727. }
  35728. else {
  35729. vCount[ofs]++;
  35730. }
  35731. }
  35732. }
  35733. for (j = 0; j < vCount.length; ++j) {
  35734. if (vCount[j] === 1) {
  35735. this.vertices[vId[j]].isBorder = true;
  35736. }
  35737. else {
  35738. this.vertices[vId[j]].isBorder = false;
  35739. }
  35740. }
  35741. }
  35742. };
  35743. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35744. if (identifyBorders === void 0) { identifyBorders = false; }
  35745. var i;
  35746. if (!identifyBorders) {
  35747. var newTrianglesVector = [];
  35748. for (i = 0; i < this.triangles.length; ++i) {
  35749. if (!this.triangles[i].deleted) {
  35750. newTrianglesVector.push(this.triangles[i]);
  35751. }
  35752. }
  35753. this.triangles = newTrianglesVector;
  35754. }
  35755. for (i = 0; i < this.vertices.length; ++i) {
  35756. this.vertices[i].triangleCount = 0;
  35757. this.vertices[i].triangleStart = 0;
  35758. }
  35759. var t;
  35760. var j;
  35761. var v;
  35762. for (i = 0; i < this.triangles.length; ++i) {
  35763. t = this.triangles[i];
  35764. for (j = 0; j < 3; ++j) {
  35765. v = t.vertices[j];
  35766. v.triangleCount++;
  35767. }
  35768. }
  35769. var tStart = 0;
  35770. for (i = 0; i < this.vertices.length; ++i) {
  35771. this.vertices[i].triangleStart = tStart;
  35772. tStart += this.vertices[i].triangleCount;
  35773. this.vertices[i].triangleCount = 0;
  35774. }
  35775. var newReferences = new Array(this.triangles.length * 3);
  35776. for (i = 0; i < this.triangles.length; ++i) {
  35777. t = this.triangles[i];
  35778. for (j = 0; j < 3; ++j) {
  35779. v = t.vertices[j];
  35780. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35781. v.triangleCount++;
  35782. }
  35783. }
  35784. this.references = newReferences;
  35785. if (identifyBorders) {
  35786. this.identifyBorder();
  35787. }
  35788. };
  35789. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35790. var x = point.x;
  35791. var y = point.y;
  35792. var z = point.z;
  35793. 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
  35794. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35795. };
  35796. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35797. var q = vertex1.q.add(vertex2.q);
  35798. var border = vertex1.isBorder && vertex2.isBorder;
  35799. var error = 0;
  35800. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35801. if (qDet !== 0 && !border) {
  35802. if (!pointResult) {
  35803. pointResult = BABYLON.Vector3.Zero();
  35804. }
  35805. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35806. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35807. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35808. error = this.vertexError(q, pointResult);
  35809. }
  35810. else {
  35811. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35812. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35813. var error1 = this.vertexError(q, vertex1.position);
  35814. var error2 = this.vertexError(q, vertex2.position);
  35815. var error3 = this.vertexError(q, p3);
  35816. error = Math.min(error1, error2, error3);
  35817. if (error === error1) {
  35818. if (pointResult) {
  35819. pointResult.copyFrom(vertex1.position);
  35820. }
  35821. }
  35822. else if (error === error2) {
  35823. if (pointResult) {
  35824. pointResult.copyFrom(vertex2.position);
  35825. }
  35826. }
  35827. else {
  35828. if (pointResult) {
  35829. pointResult.copyFrom(p3);
  35830. }
  35831. }
  35832. }
  35833. return error;
  35834. };
  35835. return QuadraticErrorSimplification;
  35836. }());
  35837. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  35838. })(BABYLON || (BABYLON = {}));
  35839. var BABYLON;
  35840. (function (BABYLON) {
  35841. var serializedGeometries = [];
  35842. var serializeGeometry = function (geometry, serializationGeometries) {
  35843. if (serializedGeometries[geometry.id]) {
  35844. return;
  35845. }
  35846. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  35847. serializationGeometries.boxes.push(geometry.serialize());
  35848. }
  35849. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  35850. serializationGeometries.spheres.push(geometry.serialize());
  35851. }
  35852. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  35853. serializationGeometries.cylinders.push(geometry.serialize());
  35854. }
  35855. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  35856. serializationGeometries.toruses.push(geometry.serialize());
  35857. }
  35858. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  35859. serializationGeometries.grounds.push(geometry.serialize());
  35860. }
  35861. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  35862. serializationGeometries.planes.push(geometry.serialize());
  35863. }
  35864. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  35865. serializationGeometries.torusKnots.push(geometry.serialize());
  35866. }
  35867. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  35868. throw new Error("Unknown primitive type");
  35869. }
  35870. else {
  35871. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  35872. }
  35873. serializedGeometries[geometry.id] = true;
  35874. };
  35875. var serializeMesh = function (mesh, serializationScene) {
  35876. var serializationObject = {};
  35877. serializationObject.name = mesh.name;
  35878. serializationObject.id = mesh.id;
  35879. if (BABYLON.Tags.HasTags(mesh)) {
  35880. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  35881. }
  35882. serializationObject.position = mesh.position.asArray();
  35883. if (mesh.rotationQuaternion) {
  35884. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  35885. }
  35886. else if (mesh.rotation) {
  35887. serializationObject.rotation = mesh.rotation.asArray();
  35888. }
  35889. serializationObject.scaling = mesh.scaling.asArray();
  35890. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  35891. serializationObject.isEnabled = mesh.isEnabled();
  35892. serializationObject.isVisible = mesh.isVisible;
  35893. serializationObject.infiniteDistance = mesh.infiniteDistance;
  35894. serializationObject.pickable = mesh.isPickable;
  35895. serializationObject.receiveShadows = mesh.receiveShadows;
  35896. serializationObject.billboardMode = mesh.billboardMode;
  35897. serializationObject.visibility = mesh.visibility;
  35898. serializationObject.checkCollisions = mesh.checkCollisions;
  35899. // Parent
  35900. if (mesh.parent) {
  35901. serializationObject.parentId = mesh.parent.id;
  35902. }
  35903. // Geometry
  35904. var geometry = mesh._geometry;
  35905. if (geometry) {
  35906. var geometryId = geometry.id;
  35907. serializationObject.geometryId = geometryId;
  35908. if (!mesh.getScene().getGeometryByID(geometryId)) {
  35909. // 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
  35910. serializeGeometry(geometry, serializationScene.geometries);
  35911. }
  35912. // SubMeshes
  35913. serializationObject.subMeshes = [];
  35914. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35915. var subMesh = mesh.subMeshes[subIndex];
  35916. serializationObject.subMeshes.push({
  35917. materialIndex: subMesh.materialIndex,
  35918. verticesStart: subMesh.verticesStart,
  35919. verticesCount: subMesh.verticesCount,
  35920. indexStart: subMesh.indexStart,
  35921. indexCount: subMesh.indexCount
  35922. });
  35923. }
  35924. }
  35925. // Material
  35926. if (mesh.material) {
  35927. serializationObject.materialId = mesh.material.id;
  35928. }
  35929. else {
  35930. mesh.material = null;
  35931. }
  35932. // Skeleton
  35933. if (mesh.skeleton) {
  35934. serializationObject.skeletonId = mesh.skeleton.id;
  35935. }
  35936. // Physics
  35937. //TODO implement correct serialization for physics impostors.
  35938. if (mesh.getPhysicsImpostor()) {
  35939. serializationObject.physicsMass = mesh.getPhysicsMass();
  35940. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  35941. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  35942. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  35943. }
  35944. // Instances
  35945. serializationObject.instances = [];
  35946. for (var index = 0; index < mesh.instances.length; index++) {
  35947. var instance = mesh.instances[index];
  35948. var serializationInstance = {
  35949. name: instance.name,
  35950. position: instance.position.asArray(),
  35951. scaling: instance.scaling.asArray()
  35952. };
  35953. if (instance.rotationQuaternion) {
  35954. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  35955. }
  35956. else if (instance.rotation) {
  35957. serializationInstance.rotation = instance.rotation.asArray();
  35958. }
  35959. serializationObject.instances.push(serializationInstance);
  35960. // Animations
  35961. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  35962. serializationInstance.ranges = instance.serializeAnimationRanges();
  35963. }
  35964. // Animations
  35965. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  35966. serializationObject.ranges = mesh.serializeAnimationRanges();
  35967. // Layer mask
  35968. serializationObject.layerMask = mesh.layerMask;
  35969. return serializationObject;
  35970. };
  35971. var finalizeSingleMesh = function (mesh, serializationObject) {
  35972. //only works if the mesh is already loaded
  35973. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  35974. //serialize material
  35975. if (mesh.material) {
  35976. if (mesh.material instanceof BABYLON.StandardMaterial) {
  35977. serializationObject.materials = serializationObject.materials || [];
  35978. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  35979. serializationObject.materials.push(mesh.material.serialize());
  35980. }
  35981. }
  35982. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  35983. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  35984. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  35985. serializationObject.multiMaterials.push(mesh.material.serialize());
  35986. }
  35987. }
  35988. }
  35989. //serialize geometry
  35990. var geometry = mesh._geometry;
  35991. if (geometry) {
  35992. if (!serializationObject.geometries) {
  35993. serializationObject.geometries = {};
  35994. serializationObject.geometries.boxes = [];
  35995. serializationObject.geometries.spheres = [];
  35996. serializationObject.geometries.cylinders = [];
  35997. serializationObject.geometries.toruses = [];
  35998. serializationObject.geometries.grounds = [];
  35999. serializationObject.geometries.planes = [];
  36000. serializationObject.geometries.torusKnots = [];
  36001. serializationObject.geometries.vertexData = [];
  36002. }
  36003. serializeGeometry(geometry, serializationObject.geometries);
  36004. }
  36005. // Skeletons
  36006. if (mesh.skeleton) {
  36007. serializationObject.skeletons = serializationObject.skeletons || [];
  36008. serializationObject.skeletons.push(mesh.skeleton.serialize());
  36009. }
  36010. //serialize the actual mesh
  36011. serializationObject.meshes = serializationObject.meshes || [];
  36012. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36013. }
  36014. };
  36015. var SceneSerializer = (function () {
  36016. function SceneSerializer() {
  36017. }
  36018. SceneSerializer.ClearCache = function () {
  36019. serializedGeometries = [];
  36020. };
  36021. SceneSerializer.Serialize = function (scene) {
  36022. var serializationObject = {};
  36023. // Scene
  36024. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36025. serializationObject.autoClear = scene.autoClear;
  36026. serializationObject.clearColor = scene.clearColor.asArray();
  36027. serializationObject.ambientColor = scene.ambientColor.asArray();
  36028. serializationObject.gravity = scene.gravity.asArray();
  36029. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36030. serializationObject.workerCollisions = scene.workerCollisions;
  36031. // Fog
  36032. if (scene.fogMode && scene.fogMode !== 0) {
  36033. serializationObject.fogMode = scene.fogMode;
  36034. serializationObject.fogColor = scene.fogColor.asArray();
  36035. serializationObject.fogStart = scene.fogStart;
  36036. serializationObject.fogEnd = scene.fogEnd;
  36037. serializationObject.fogDensity = scene.fogDensity;
  36038. }
  36039. //Physics
  36040. if (scene.isPhysicsEnabled()) {
  36041. serializationObject.physicsEnabled = true;
  36042. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36043. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36044. }
  36045. // Lights
  36046. serializationObject.lights = [];
  36047. var index;
  36048. var light;
  36049. for (index = 0; index < scene.lights.length; index++) {
  36050. light = scene.lights[index];
  36051. serializationObject.lights.push(light.serialize());
  36052. }
  36053. // Cameras
  36054. serializationObject.cameras = [];
  36055. for (index = 0; index < scene.cameras.length; index++) {
  36056. var camera = scene.cameras[index];
  36057. serializationObject.cameras.push(camera.serialize());
  36058. }
  36059. if (scene.activeCamera) {
  36060. serializationObject.activeCameraID = scene.activeCamera.id;
  36061. }
  36062. // Animations
  36063. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36064. // Materials
  36065. serializationObject.materials = [];
  36066. serializationObject.multiMaterials = [];
  36067. var material;
  36068. for (index = 0; index < scene.materials.length; index++) {
  36069. material = scene.materials[index];
  36070. serializationObject.materials.push(material.serialize());
  36071. }
  36072. // MultiMaterials
  36073. serializationObject.multiMaterials = [];
  36074. for (index = 0; index < scene.multiMaterials.length; index++) {
  36075. var multiMaterial = scene.multiMaterials[index];
  36076. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36077. }
  36078. // Skeletons
  36079. serializationObject.skeletons = [];
  36080. for (index = 0; index < scene.skeletons.length; index++) {
  36081. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36082. }
  36083. // Geometries
  36084. serializationObject.geometries = {};
  36085. serializationObject.geometries.boxes = [];
  36086. serializationObject.geometries.spheres = [];
  36087. serializationObject.geometries.cylinders = [];
  36088. serializationObject.geometries.toruses = [];
  36089. serializationObject.geometries.grounds = [];
  36090. serializationObject.geometries.planes = [];
  36091. serializationObject.geometries.torusKnots = [];
  36092. serializationObject.geometries.vertexData = [];
  36093. serializedGeometries = [];
  36094. var geometries = scene.getGeometries();
  36095. for (index = 0; index < geometries.length; index++) {
  36096. var geometry = geometries[index];
  36097. if (geometry.isReady()) {
  36098. serializeGeometry(geometry, serializationObject.geometries);
  36099. }
  36100. }
  36101. // Meshes
  36102. serializationObject.meshes = [];
  36103. for (index = 0; index < scene.meshes.length; index++) {
  36104. var abstractMesh = scene.meshes[index];
  36105. if (abstractMesh instanceof BABYLON.Mesh) {
  36106. var mesh = abstractMesh;
  36107. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36108. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36109. }
  36110. }
  36111. }
  36112. // Particles Systems
  36113. serializationObject.particleSystems = [];
  36114. for (index = 0; index < scene.particleSystems.length; index++) {
  36115. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36116. }
  36117. // Lens flares
  36118. serializationObject.lensFlareSystems = [];
  36119. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36120. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36121. }
  36122. // Shadows
  36123. serializationObject.shadowGenerators = [];
  36124. for (index = 0; index < scene.lights.length; index++) {
  36125. light = scene.lights[index];
  36126. if (light.getShadowGenerator()) {
  36127. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36128. }
  36129. }
  36130. return serializationObject;
  36131. };
  36132. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36133. if (withParents === void 0) { withParents = false; }
  36134. if (withChildren === void 0) { withChildren = false; }
  36135. var serializationObject = {};
  36136. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36137. if (withParents || withChildren) {
  36138. //deliberate for loop! not for each, appended should be processed as well.
  36139. for (var i = 0; i < toSerialize.length; ++i) {
  36140. if (withChildren) {
  36141. toSerialize[i].getDescendants().forEach(function (node) {
  36142. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36143. toSerialize.push(node);
  36144. }
  36145. });
  36146. }
  36147. //make sure the array doesn't contain the object already
  36148. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36149. toSerialize.push(toSerialize[i].parent);
  36150. }
  36151. }
  36152. }
  36153. toSerialize.forEach(function (mesh) {
  36154. finalizeSingleMesh(mesh, serializationObject);
  36155. });
  36156. return serializationObject;
  36157. };
  36158. return SceneSerializer;
  36159. }());
  36160. BABYLON.SceneSerializer = SceneSerializer;
  36161. })(BABYLON || (BABYLON = {}));
  36162. var BABYLON;
  36163. (function (BABYLON) {
  36164. // Unique ID when we import meshes from Babylon to CSG
  36165. var currentCSGMeshId = 0;
  36166. // # class Vertex
  36167. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36168. // one to provide additional features like texture coordinates and vertex
  36169. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36170. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36171. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36172. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36173. // is not used anywhere else.
  36174. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36175. var Vertex = (function () {
  36176. function Vertex(pos, normal, uv) {
  36177. this.pos = pos;
  36178. this.normal = normal;
  36179. this.uv = uv;
  36180. }
  36181. Vertex.prototype.clone = function () {
  36182. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36183. };
  36184. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36185. // orientation of a polygon is flipped.
  36186. Vertex.prototype.flip = function () {
  36187. this.normal = this.normal.scale(-1);
  36188. };
  36189. // Create a new vertex between this vertex and `other` by linearly
  36190. // interpolating all properties using a parameter of `t`. Subclasses should
  36191. // override this to interpolate additional properties.
  36192. Vertex.prototype.interpolate = function (other, t) {
  36193. 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));
  36194. };
  36195. return Vertex;
  36196. }());
  36197. // # class Plane
  36198. // Represents a plane in 3D space.
  36199. var Plane = (function () {
  36200. function Plane(normal, w) {
  36201. this.normal = normal;
  36202. this.w = w;
  36203. }
  36204. Plane.FromPoints = function (a, b, c) {
  36205. var v0 = c.subtract(a);
  36206. var v1 = b.subtract(a);
  36207. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36208. return null;
  36209. }
  36210. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36211. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36212. };
  36213. Plane.prototype.clone = function () {
  36214. return new Plane(this.normal.clone(), this.w);
  36215. };
  36216. Plane.prototype.flip = function () {
  36217. this.normal.scaleInPlace(-1);
  36218. this.w = -this.w;
  36219. };
  36220. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36221. // fragments in the appropriate lists. Coplanar polygons go into either
  36222. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36223. // respect to this plane. Polygons in front or in back of this plane go into
  36224. // either `front` or `back`.
  36225. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36226. var COPLANAR = 0;
  36227. var FRONT = 1;
  36228. var BACK = 2;
  36229. var SPANNING = 3;
  36230. // Classify each point as well as the entire polygon into one of the above
  36231. // four classes.
  36232. var polygonType = 0;
  36233. var types = [];
  36234. var i;
  36235. var t;
  36236. for (i = 0; i < polygon.vertices.length; i++) {
  36237. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36238. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36239. polygonType |= type;
  36240. types.push(type);
  36241. }
  36242. // Put the polygon in the correct list, splitting it when necessary.
  36243. switch (polygonType) {
  36244. case COPLANAR:
  36245. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36246. break;
  36247. case FRONT:
  36248. front.push(polygon);
  36249. break;
  36250. case BACK:
  36251. back.push(polygon);
  36252. break;
  36253. case SPANNING:
  36254. var f = [], b = [];
  36255. for (i = 0; i < polygon.vertices.length; i++) {
  36256. var j = (i + 1) % polygon.vertices.length;
  36257. var ti = types[i], tj = types[j];
  36258. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36259. if (ti !== BACK)
  36260. f.push(vi);
  36261. if (ti !== FRONT)
  36262. b.push(ti !== BACK ? vi.clone() : vi);
  36263. if ((ti | tj) === SPANNING) {
  36264. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36265. var v = vi.interpolate(vj, t);
  36266. f.push(v);
  36267. b.push(v.clone());
  36268. }
  36269. }
  36270. var poly;
  36271. if (f.length >= 3) {
  36272. poly = new Polygon(f, polygon.shared);
  36273. if (poly.plane)
  36274. front.push(poly);
  36275. }
  36276. if (b.length >= 3) {
  36277. poly = new Polygon(b, polygon.shared);
  36278. if (poly.plane)
  36279. back.push(poly);
  36280. }
  36281. break;
  36282. }
  36283. };
  36284. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36285. // point is on the plane.
  36286. Plane.EPSILON = 1e-5;
  36287. return Plane;
  36288. }());
  36289. // # class Polygon
  36290. // Represents a convex polygon. The vertices used to initialize a polygon must
  36291. // be coplanar and form a convex loop.
  36292. //
  36293. // Each convex polygon has a `shared` property, which is shared between all
  36294. // polygons that are clones of each other or were split from the same polygon.
  36295. // This can be used to define per-polygon properties (such as surface color).
  36296. var Polygon = (function () {
  36297. function Polygon(vertices, shared) {
  36298. this.vertices = vertices;
  36299. this.shared = shared;
  36300. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36301. }
  36302. Polygon.prototype.clone = function () {
  36303. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36304. return new Polygon(vertices, this.shared);
  36305. };
  36306. Polygon.prototype.flip = function () {
  36307. this.vertices.reverse().map(function (v) { v.flip(); });
  36308. this.plane.flip();
  36309. };
  36310. return Polygon;
  36311. }());
  36312. // # class Node
  36313. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36314. // by picking a polygon to split along. That polygon (and all other coplanar
  36315. // polygons) are added directly to that node and the other polygons are added to
  36316. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36317. // no distinction between internal and leaf nodes.
  36318. var Node = (function () {
  36319. function Node(polygons) {
  36320. this.plane = null;
  36321. this.front = null;
  36322. this.back = null;
  36323. this.polygons = [];
  36324. if (polygons) {
  36325. this.build(polygons);
  36326. }
  36327. }
  36328. Node.prototype.clone = function () {
  36329. var node = new Node();
  36330. node.plane = this.plane && this.plane.clone();
  36331. node.front = this.front && this.front.clone();
  36332. node.back = this.back && this.back.clone();
  36333. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36334. return node;
  36335. };
  36336. // Convert solid space to empty space and empty space to solid space.
  36337. Node.prototype.invert = function () {
  36338. for (var i = 0; i < this.polygons.length; i++) {
  36339. this.polygons[i].flip();
  36340. }
  36341. if (this.plane) {
  36342. this.plane.flip();
  36343. }
  36344. if (this.front) {
  36345. this.front.invert();
  36346. }
  36347. if (this.back) {
  36348. this.back.invert();
  36349. }
  36350. var temp = this.front;
  36351. this.front = this.back;
  36352. this.back = temp;
  36353. };
  36354. // Recursively remove all polygons in `polygons` that are inside this BSP
  36355. // tree.
  36356. Node.prototype.clipPolygons = function (polygons) {
  36357. if (!this.plane)
  36358. return polygons.slice();
  36359. var front = [], back = [];
  36360. for (var i = 0; i < polygons.length; i++) {
  36361. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36362. }
  36363. if (this.front) {
  36364. front = this.front.clipPolygons(front);
  36365. }
  36366. if (this.back) {
  36367. back = this.back.clipPolygons(back);
  36368. }
  36369. else {
  36370. back = [];
  36371. }
  36372. return front.concat(back);
  36373. };
  36374. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36375. // `bsp`.
  36376. Node.prototype.clipTo = function (bsp) {
  36377. this.polygons = bsp.clipPolygons(this.polygons);
  36378. if (this.front)
  36379. this.front.clipTo(bsp);
  36380. if (this.back)
  36381. this.back.clipTo(bsp);
  36382. };
  36383. // Return a list of all polygons in this BSP tree.
  36384. Node.prototype.allPolygons = function () {
  36385. var polygons = this.polygons.slice();
  36386. if (this.front)
  36387. polygons = polygons.concat(this.front.allPolygons());
  36388. if (this.back)
  36389. polygons = polygons.concat(this.back.allPolygons());
  36390. return polygons;
  36391. };
  36392. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36393. // new polygons are filtered down to the bottom of the tree and become new
  36394. // nodes there. Each set of polygons is partitioned using the first polygon
  36395. // (no heuristic is used to pick a good split).
  36396. Node.prototype.build = function (polygons) {
  36397. if (!polygons.length)
  36398. return;
  36399. if (!this.plane)
  36400. this.plane = polygons[0].plane.clone();
  36401. var front = [], back = [];
  36402. for (var i = 0; i < polygons.length; i++) {
  36403. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  36404. }
  36405. if (front.length) {
  36406. if (!this.front)
  36407. this.front = new Node();
  36408. this.front.build(front);
  36409. }
  36410. if (back.length) {
  36411. if (!this.back)
  36412. this.back = new Node();
  36413. this.back.build(back);
  36414. }
  36415. };
  36416. return Node;
  36417. }());
  36418. var CSG = (function () {
  36419. function CSG() {
  36420. this.polygons = new Array();
  36421. }
  36422. // Convert BABYLON.Mesh to BABYLON.CSG
  36423. CSG.FromMesh = function (mesh) {
  36424. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  36425. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  36426. if (mesh instanceof BABYLON.Mesh) {
  36427. mesh.computeWorldMatrix(true);
  36428. matrix = mesh.getWorldMatrix();
  36429. meshPosition = mesh.position.clone();
  36430. meshRotation = mesh.rotation.clone();
  36431. if (mesh.rotationQuaternion) {
  36432. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  36433. }
  36434. meshScaling = mesh.scaling.clone();
  36435. }
  36436. else {
  36437. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  36438. }
  36439. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36440. var subMeshes = mesh.subMeshes;
  36441. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  36442. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  36443. vertices = [];
  36444. for (var j = 0; j < 3; j++) {
  36445. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36446. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  36447. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36448. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36449. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36450. vertex = new Vertex(position, normal, uv);
  36451. vertices.push(vertex);
  36452. }
  36453. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36454. // To handle the case of degenerated triangle
  36455. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36456. if (polygon.plane)
  36457. polygons.push(polygon);
  36458. }
  36459. }
  36460. var csg = CSG.FromPolygons(polygons);
  36461. csg.matrix = matrix;
  36462. csg.position = meshPosition;
  36463. csg.rotation = meshRotation;
  36464. csg.scaling = meshScaling;
  36465. csg.rotationQuaternion = meshRotationQuaternion;
  36466. currentCSGMeshId++;
  36467. return csg;
  36468. };
  36469. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36470. CSG.FromPolygons = function (polygons) {
  36471. var csg = new CSG();
  36472. csg.polygons = polygons;
  36473. return csg;
  36474. };
  36475. CSG.prototype.clone = function () {
  36476. var csg = new CSG();
  36477. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36478. csg.copyTransformAttributes(this);
  36479. return csg;
  36480. };
  36481. CSG.prototype.toPolygons = function () {
  36482. return this.polygons;
  36483. };
  36484. CSG.prototype.union = function (csg) {
  36485. var a = new Node(this.clone().polygons);
  36486. var b = new Node(csg.clone().polygons);
  36487. a.clipTo(b);
  36488. b.clipTo(a);
  36489. b.invert();
  36490. b.clipTo(a);
  36491. b.invert();
  36492. a.build(b.allPolygons());
  36493. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36494. };
  36495. CSG.prototype.unionInPlace = function (csg) {
  36496. var a = new Node(this.polygons);
  36497. var b = new Node(csg.polygons);
  36498. a.clipTo(b);
  36499. b.clipTo(a);
  36500. b.invert();
  36501. b.clipTo(a);
  36502. b.invert();
  36503. a.build(b.allPolygons());
  36504. this.polygons = a.allPolygons();
  36505. };
  36506. CSG.prototype.subtract = function (csg) {
  36507. var a = new Node(this.clone().polygons);
  36508. var b = new Node(csg.clone().polygons);
  36509. a.invert();
  36510. a.clipTo(b);
  36511. b.clipTo(a);
  36512. b.invert();
  36513. b.clipTo(a);
  36514. b.invert();
  36515. a.build(b.allPolygons());
  36516. a.invert();
  36517. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36518. };
  36519. CSG.prototype.subtractInPlace = function (csg) {
  36520. var a = new Node(this.polygons);
  36521. var b = new Node(csg.polygons);
  36522. a.invert();
  36523. a.clipTo(b);
  36524. b.clipTo(a);
  36525. b.invert();
  36526. b.clipTo(a);
  36527. b.invert();
  36528. a.build(b.allPolygons());
  36529. a.invert();
  36530. this.polygons = a.allPolygons();
  36531. };
  36532. CSG.prototype.intersect = function (csg) {
  36533. var a = new Node(this.clone().polygons);
  36534. var b = new Node(csg.clone().polygons);
  36535. a.invert();
  36536. b.clipTo(a);
  36537. b.invert();
  36538. a.clipTo(b);
  36539. b.clipTo(a);
  36540. a.build(b.allPolygons());
  36541. a.invert();
  36542. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36543. };
  36544. CSG.prototype.intersectInPlace = function (csg) {
  36545. var a = new Node(this.polygons);
  36546. var b = new Node(csg.polygons);
  36547. a.invert();
  36548. b.clipTo(a);
  36549. b.invert();
  36550. a.clipTo(b);
  36551. b.clipTo(a);
  36552. a.build(b.allPolygons());
  36553. a.invert();
  36554. this.polygons = a.allPolygons();
  36555. };
  36556. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36557. // not modified.
  36558. CSG.prototype.inverse = function () {
  36559. var csg = this.clone();
  36560. csg.inverseInPlace();
  36561. return csg;
  36562. };
  36563. CSG.prototype.inverseInPlace = function () {
  36564. this.polygons.map(function (p) { p.flip(); });
  36565. };
  36566. // This is used to keep meshes transformations so they can be restored
  36567. // when we build back a Babylon Mesh
  36568. // NB : All CSG operations are performed in world coordinates
  36569. CSG.prototype.copyTransformAttributes = function (csg) {
  36570. this.matrix = csg.matrix;
  36571. this.position = csg.position;
  36572. this.rotation = csg.rotation;
  36573. this.scaling = csg.scaling;
  36574. this.rotationQuaternion = csg.rotationQuaternion;
  36575. return this;
  36576. };
  36577. // Build Raw mesh from CSG
  36578. // Coordinates here are in world space
  36579. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36580. var matrix = this.matrix.clone();
  36581. matrix.invert();
  36582. 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;
  36583. if (keepSubMeshes) {
  36584. // Sort Polygons, since subMeshes are indices range
  36585. polygons.sort(function (a, b) {
  36586. if (a.shared.meshId === b.shared.meshId) {
  36587. return a.shared.subMeshId - b.shared.subMeshId;
  36588. }
  36589. else {
  36590. return a.shared.meshId - b.shared.meshId;
  36591. }
  36592. });
  36593. }
  36594. for (var i = 0, il = polygons.length; i < il; i++) {
  36595. polygon = polygons[i];
  36596. // Building SubMeshes
  36597. if (!subMesh_dict[polygon.shared.meshId]) {
  36598. subMesh_dict[polygon.shared.meshId] = {};
  36599. }
  36600. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36601. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36602. indexStart: +Infinity,
  36603. indexEnd: -Infinity,
  36604. materialIndex: polygon.shared.materialIndex
  36605. };
  36606. }
  36607. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36608. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36609. polygonIndices[0] = 0;
  36610. polygonIndices[1] = j - 1;
  36611. polygonIndices[2] = j;
  36612. for (var k = 0; k < 3; k++) {
  36613. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36614. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36615. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36616. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36617. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36618. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36619. // Check if 2 points can be merged
  36620. if (!(typeof vertex_idx !== 'undefined' &&
  36621. normals[vertex_idx * 3] === localNormal.x &&
  36622. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36623. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36624. uvs[vertex_idx * 2] === uv.x &&
  36625. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36626. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36627. uvs.push(uv.x, uv.y);
  36628. normals.push(normal.x, normal.y, normal.z);
  36629. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36630. }
  36631. indices.push(vertex_idx);
  36632. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36633. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36634. currentIndex++;
  36635. }
  36636. }
  36637. }
  36638. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36639. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36640. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36641. mesh.setIndices(indices);
  36642. if (keepSubMeshes) {
  36643. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36644. var materialIndexOffset = 0, materialMaxIndex;
  36645. mesh.subMeshes = new Array();
  36646. for (var m in subMesh_dict) {
  36647. materialMaxIndex = -1;
  36648. for (var sm in subMesh_dict[m]) {
  36649. subMesh_obj = subMesh_dict[m][sm];
  36650. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36651. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36652. }
  36653. materialIndexOffset += ++materialMaxIndex;
  36654. }
  36655. }
  36656. return mesh;
  36657. };
  36658. // Build Mesh from CSG taking material and transforms into account
  36659. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36660. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36661. mesh.material = material;
  36662. mesh.position.copyFrom(this.position);
  36663. mesh.rotation.copyFrom(this.rotation);
  36664. if (this.rotationQuaternion) {
  36665. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36666. }
  36667. mesh.scaling.copyFrom(this.scaling);
  36668. mesh.computeWorldMatrix(true);
  36669. return mesh;
  36670. };
  36671. return CSG;
  36672. }());
  36673. BABYLON.CSG = CSG;
  36674. })(BABYLON || (BABYLON = {}));
  36675. var BABYLON;
  36676. (function (BABYLON) {
  36677. var VRDistortionCorrectionPostProcess = (function (_super) {
  36678. __extends(VRDistortionCorrectionPostProcess, _super);
  36679. //ANY
  36680. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36681. var _this = this;
  36682. _super.call(this, name, "vrDistortionCorrection", [
  36683. 'LensCenter',
  36684. 'Scale',
  36685. 'ScaleIn',
  36686. 'HmdWarpParam'
  36687. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36688. this._isRightEye = isRightEye;
  36689. this._distortionFactors = vrMetrics.distortionK;
  36690. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36691. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36692. this.onSizeChanged = function () {
  36693. _this.aspectRatio = _this.width * .5 / _this.height;
  36694. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36695. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36696. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36697. };
  36698. this.onApply = function (effect) {
  36699. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36700. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36701. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36702. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36703. };
  36704. }
  36705. return VRDistortionCorrectionPostProcess;
  36706. }(BABYLON.PostProcess));
  36707. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36708. })(BABYLON || (BABYLON = {}));
  36709. // Mainly based on these 2 articles :
  36710. // 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
  36711. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36712. var BABYLON;
  36713. (function (BABYLON) {
  36714. (function (JoystickAxis) {
  36715. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36716. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36717. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36718. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36719. var JoystickAxis = BABYLON.JoystickAxis;
  36720. var VirtualJoystick = (function () {
  36721. function VirtualJoystick(leftJoystick) {
  36722. var _this = this;
  36723. if (leftJoystick) {
  36724. this._leftJoystick = true;
  36725. }
  36726. else {
  36727. this._leftJoystick = false;
  36728. }
  36729. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36730. VirtualJoystick._globalJoystickIndex++;
  36731. // By default left & right arrow keys are moving the X
  36732. // and up & down keys are moving the Y
  36733. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36734. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36735. this.reverseLeftRight = false;
  36736. this.reverseUpDown = false;
  36737. // collections of pointers
  36738. this._touches = new BABYLON.SmartCollection();
  36739. this.deltaPosition = BABYLON.Vector3.Zero();
  36740. this._joystickSensibility = 25;
  36741. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36742. this._rotationSpeed = 25;
  36743. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36744. this._rotateOnAxisRelativeToMesh = false;
  36745. this._onResize = function (evt) {
  36746. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36747. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36748. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36749. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36750. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36751. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36752. };
  36753. // injecting a canvas element on top of the canvas 3D game
  36754. if (!VirtualJoystick.vjCanvas) {
  36755. window.addEventListener("resize", this._onResize, false);
  36756. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36757. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36758. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36759. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36760. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36761. VirtualJoystick.vjCanvas.style.width = "100%";
  36762. VirtualJoystick.vjCanvas.style.height = "100%";
  36763. VirtualJoystick.vjCanvas.style.position = "absolute";
  36764. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36765. VirtualJoystick.vjCanvas.style.top = "0px";
  36766. VirtualJoystick.vjCanvas.style.left = "0px";
  36767. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36768. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36769. // Support for jQuery PEP polyfill
  36770. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36771. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36772. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36773. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36774. document.body.appendChild(VirtualJoystick.vjCanvas);
  36775. }
  36776. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36777. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36778. this.pressed = false;
  36779. // default joystick color
  36780. this._joystickColor = "cyan";
  36781. this._joystickPointerID = -1;
  36782. // current joystick position
  36783. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36784. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36785. // origin joystick position
  36786. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36787. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36788. this._onPointerDownHandlerRef = function (evt) {
  36789. _this._onPointerDown(evt);
  36790. };
  36791. this._onPointerMoveHandlerRef = function (evt) {
  36792. _this._onPointerMove(evt);
  36793. };
  36794. this._onPointerOutHandlerRef = function (evt) {
  36795. _this._onPointerUp(evt);
  36796. };
  36797. this._onPointerUpHandlerRef = function (evt) {
  36798. _this._onPointerUp(evt);
  36799. };
  36800. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36801. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36802. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36803. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36804. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36805. evt.preventDefault(); // Disables system menu
  36806. }, false);
  36807. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36808. }
  36809. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36810. this._joystickSensibility = newJoystickSensibility;
  36811. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36812. };
  36813. VirtualJoystick.prototype._onPointerDown = function (e) {
  36814. var positionOnScreenCondition;
  36815. e.preventDefault();
  36816. if (this._leftJoystick === true) {
  36817. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  36818. }
  36819. else {
  36820. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  36821. }
  36822. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  36823. // First contact will be dedicated to the virtual joystick
  36824. this._joystickPointerID = e.pointerId;
  36825. this._joystickPointerStartPos.x = e.clientX;
  36826. this._joystickPointerStartPos.y = e.clientY;
  36827. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  36828. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  36829. this._deltaJoystickVector.x = 0;
  36830. this._deltaJoystickVector.y = 0;
  36831. this.pressed = true;
  36832. this._touches.add(e.pointerId.toString(), e);
  36833. }
  36834. else {
  36835. // You can only trigger the action buttons with a joystick declared
  36836. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  36837. this._action();
  36838. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  36839. }
  36840. }
  36841. };
  36842. VirtualJoystick.prototype._onPointerMove = function (e) {
  36843. // If the current pointer is the one associated to the joystick (first touch contact)
  36844. if (this._joystickPointerID == e.pointerId) {
  36845. this._joystickPointerPos.x = e.clientX;
  36846. this._joystickPointerPos.y = e.clientY;
  36847. this._deltaJoystickVector = this._joystickPointerPos.clone();
  36848. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  36849. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  36850. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  36851. switch (this._axisTargetedByLeftAndRight) {
  36852. case JoystickAxis.X:
  36853. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  36854. break;
  36855. case JoystickAxis.Y:
  36856. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  36857. break;
  36858. case JoystickAxis.Z:
  36859. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  36860. break;
  36861. }
  36862. var directionUpDown = this.reverseUpDown ? 1 : -1;
  36863. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  36864. switch (this._axisTargetedByUpAndDown) {
  36865. case JoystickAxis.X:
  36866. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  36867. break;
  36868. case JoystickAxis.Y:
  36869. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  36870. break;
  36871. case JoystickAxis.Z:
  36872. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  36873. break;
  36874. }
  36875. }
  36876. else {
  36877. if (this._touches.item(e.pointerId.toString())) {
  36878. this._touches.item(e.pointerId.toString()).x = e.clientX;
  36879. this._touches.item(e.pointerId.toString()).y = e.clientY;
  36880. }
  36881. }
  36882. };
  36883. VirtualJoystick.prototype._onPointerUp = function (e) {
  36884. if (this._joystickPointerID == e.pointerId) {
  36885. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  36886. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  36887. this._joystickPointerID = -1;
  36888. this.pressed = false;
  36889. }
  36890. else {
  36891. var touch = this._touches.item(e.pointerId.toString());
  36892. if (touch) {
  36893. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36894. }
  36895. }
  36896. this._deltaJoystickVector.x = 0;
  36897. this._deltaJoystickVector.y = 0;
  36898. this._touches.remove(e.pointerId.toString());
  36899. };
  36900. /**
  36901. * Change the color of the virtual joystick
  36902. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  36903. */
  36904. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  36905. this._joystickColor = newColor;
  36906. };
  36907. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  36908. this._action = action;
  36909. };
  36910. // Define which axis you'd like to control for left & right
  36911. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  36912. switch (axis) {
  36913. case JoystickAxis.X:
  36914. case JoystickAxis.Y:
  36915. case JoystickAxis.Z:
  36916. this._axisTargetedByLeftAndRight = axis;
  36917. break;
  36918. default:
  36919. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36920. break;
  36921. }
  36922. };
  36923. // Define which axis you'd like to control for up & down
  36924. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  36925. switch (axis) {
  36926. case JoystickAxis.X:
  36927. case JoystickAxis.Y:
  36928. case JoystickAxis.Z:
  36929. this._axisTargetedByUpAndDown = axis;
  36930. break;
  36931. default:
  36932. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36933. break;
  36934. }
  36935. };
  36936. VirtualJoystick.prototype._clearCanvas = function () {
  36937. if (this._leftJoystick) {
  36938. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  36939. }
  36940. else {
  36941. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  36942. }
  36943. };
  36944. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  36945. var _this = this;
  36946. if (this.pressed) {
  36947. this._touches.forEach(function (touch) {
  36948. if (touch.pointerId === _this._joystickPointerID) {
  36949. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  36950. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  36951. VirtualJoystick.vjCanvasContext.beginPath();
  36952. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  36953. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36954. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  36955. VirtualJoystick.vjCanvasContext.stroke();
  36956. VirtualJoystick.vjCanvasContext.closePath();
  36957. VirtualJoystick.vjCanvasContext.beginPath();
  36958. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36959. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36960. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  36961. VirtualJoystick.vjCanvasContext.stroke();
  36962. VirtualJoystick.vjCanvasContext.closePath();
  36963. VirtualJoystick.vjCanvasContext.beginPath();
  36964. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  36965. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  36966. VirtualJoystick.vjCanvasContext.stroke();
  36967. VirtualJoystick.vjCanvasContext.closePath();
  36968. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  36969. }
  36970. else {
  36971. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36972. VirtualJoystick.vjCanvasContext.beginPath();
  36973. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  36974. VirtualJoystick.vjCanvasContext.beginPath();
  36975. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  36976. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  36977. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  36978. VirtualJoystick.vjCanvasContext.stroke();
  36979. VirtualJoystick.vjCanvasContext.closePath();
  36980. touch.prevX = touch.x;
  36981. touch.prevY = touch.y;
  36982. }
  36983. ;
  36984. });
  36985. }
  36986. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36987. };
  36988. VirtualJoystick.prototype.releaseCanvas = function () {
  36989. if (VirtualJoystick.vjCanvas) {
  36990. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  36991. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  36992. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  36993. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  36994. window.removeEventListener("resize", this._onResize);
  36995. document.body.removeChild(VirtualJoystick.vjCanvas);
  36996. VirtualJoystick.vjCanvas = null;
  36997. }
  36998. };
  36999. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  37000. VirtualJoystick._globalJoystickIndex = 0;
  37001. return VirtualJoystick;
  37002. }());
  37003. BABYLON.VirtualJoystick = VirtualJoystick;
  37004. })(BABYLON || (BABYLON = {}));
  37005. var BABYLON;
  37006. (function (BABYLON) {
  37007. // We're mainly based on the logic defined into the FreeCamera code
  37008. var VirtualJoysticksCamera = (function (_super) {
  37009. __extends(VirtualJoysticksCamera, _super);
  37010. function VirtualJoysticksCamera(name, position, scene) {
  37011. _super.call(this, name, position, scene);
  37012. this.inputs.addVirtualJoystick();
  37013. }
  37014. return VirtualJoysticksCamera;
  37015. }(BABYLON.FreeCamera));
  37016. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  37017. })(BABYLON || (BABYLON = {}));
  37018. var BABYLON;
  37019. (function (BABYLON) {
  37020. var AnaglyphPostProcess = (function (_super) {
  37021. __extends(AnaglyphPostProcess, _super);
  37022. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37023. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  37024. }
  37025. return AnaglyphPostProcess;
  37026. }(BABYLON.PostProcess));
  37027. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37028. })(BABYLON || (BABYLON = {}));
  37029. var BABYLON;
  37030. (function (BABYLON) {
  37031. var OutlineRenderer = (function () {
  37032. function OutlineRenderer(scene) {
  37033. this._scene = scene;
  37034. }
  37035. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37036. var _this = this;
  37037. if (useOverlay === void 0) { useOverlay = false; }
  37038. var scene = this._scene;
  37039. var engine = this._scene.getEngine();
  37040. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37041. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37042. return;
  37043. }
  37044. var mesh = subMesh.getRenderingMesh();
  37045. var material = subMesh.getMaterial();
  37046. engine.enableEffect(this._effect);
  37047. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37048. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37049. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37050. // Bones
  37051. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37052. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37053. }
  37054. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37055. // Alpha test
  37056. if (material && material.needAlphaTesting()) {
  37057. var alphaTexture = material.getAlphaTestTexture();
  37058. this._effect.setTexture("diffuseSampler", alphaTexture);
  37059. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37060. }
  37061. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37062. };
  37063. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37064. var defines = [];
  37065. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37066. var mesh = subMesh.getMesh();
  37067. var material = subMesh.getMaterial();
  37068. // Alpha test
  37069. if (material && material.needAlphaTesting()) {
  37070. defines.push("#define ALPHATEST");
  37071. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37072. attribs.push(BABYLON.VertexBuffer.UVKind);
  37073. defines.push("#define UV1");
  37074. }
  37075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37076. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37077. defines.push("#define UV2");
  37078. }
  37079. }
  37080. // Bones
  37081. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37082. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37083. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37084. if (mesh.numBoneInfluencers > 4) {
  37085. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37086. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37087. }
  37088. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37089. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37090. }
  37091. else {
  37092. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37093. }
  37094. // Instances
  37095. if (useInstances) {
  37096. defines.push("#define INSTANCES");
  37097. attribs.push("world0");
  37098. attribs.push("world1");
  37099. attribs.push("world2");
  37100. attribs.push("world3");
  37101. }
  37102. // Get correct effect
  37103. var join = defines.join("\n");
  37104. if (this._cachedDefines !== join) {
  37105. this._cachedDefines = join;
  37106. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37107. }
  37108. return this._effect.isReady();
  37109. };
  37110. return OutlineRenderer;
  37111. }());
  37112. BABYLON.OutlineRenderer = OutlineRenderer;
  37113. })(BABYLON || (BABYLON = {}));
  37114. var BABYLON;
  37115. (function (BABYLON) {
  37116. var MeshAssetTask = (function () {
  37117. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37118. this.name = name;
  37119. this.meshesNames = meshesNames;
  37120. this.rootUrl = rootUrl;
  37121. this.sceneFilename = sceneFilename;
  37122. this.isCompleted = false;
  37123. }
  37124. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37125. var _this = this;
  37126. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37127. _this.loadedMeshes = meshes;
  37128. _this.loadedParticleSystems = particleSystems;
  37129. _this.loadedSkeletons = skeletons;
  37130. _this.isCompleted = true;
  37131. if (_this.onSuccess) {
  37132. _this.onSuccess(_this);
  37133. }
  37134. onSuccess();
  37135. }, null, function () {
  37136. if (_this.onError) {
  37137. _this.onError(_this);
  37138. }
  37139. onError();
  37140. });
  37141. };
  37142. return MeshAssetTask;
  37143. }());
  37144. BABYLON.MeshAssetTask = MeshAssetTask;
  37145. var TextFileAssetTask = (function () {
  37146. function TextFileAssetTask(name, url) {
  37147. this.name = name;
  37148. this.url = url;
  37149. this.isCompleted = false;
  37150. }
  37151. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37152. var _this = this;
  37153. BABYLON.Tools.LoadFile(this.url, function (data) {
  37154. _this.text = data;
  37155. _this.isCompleted = true;
  37156. if (_this.onSuccess) {
  37157. _this.onSuccess(_this);
  37158. }
  37159. onSuccess();
  37160. }, null, scene.database, false, function () {
  37161. if (_this.onError) {
  37162. _this.onError(_this);
  37163. }
  37164. onError();
  37165. });
  37166. };
  37167. return TextFileAssetTask;
  37168. }());
  37169. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37170. var BinaryFileAssetTask = (function () {
  37171. function BinaryFileAssetTask(name, url) {
  37172. this.name = name;
  37173. this.url = url;
  37174. this.isCompleted = false;
  37175. }
  37176. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37177. var _this = this;
  37178. BABYLON.Tools.LoadFile(this.url, function (data) {
  37179. _this.data = data;
  37180. _this.isCompleted = true;
  37181. if (_this.onSuccess) {
  37182. _this.onSuccess(_this);
  37183. }
  37184. onSuccess();
  37185. }, null, scene.database, true, function () {
  37186. if (_this.onError) {
  37187. _this.onError(_this);
  37188. }
  37189. onError();
  37190. });
  37191. };
  37192. return BinaryFileAssetTask;
  37193. }());
  37194. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37195. var ImageAssetTask = (function () {
  37196. function ImageAssetTask(name, url) {
  37197. this.name = name;
  37198. this.url = url;
  37199. this.isCompleted = false;
  37200. }
  37201. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37202. var _this = this;
  37203. var img = new Image();
  37204. img.onload = function () {
  37205. _this.image = img;
  37206. _this.isCompleted = true;
  37207. if (_this.onSuccess) {
  37208. _this.onSuccess(_this);
  37209. }
  37210. onSuccess();
  37211. };
  37212. img.onerror = function () {
  37213. if (_this.onError) {
  37214. _this.onError(_this);
  37215. }
  37216. onError();
  37217. };
  37218. img.src = this.url;
  37219. };
  37220. return ImageAssetTask;
  37221. }());
  37222. BABYLON.ImageAssetTask = ImageAssetTask;
  37223. var TextureAssetTask = (function () {
  37224. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37226. this.name = name;
  37227. this.url = url;
  37228. this.noMipmap = noMipmap;
  37229. this.invertY = invertY;
  37230. this.samplingMode = samplingMode;
  37231. this.isCompleted = false;
  37232. }
  37233. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37234. var _this = this;
  37235. var onload = function () {
  37236. _this.isCompleted = true;
  37237. if (_this.onSuccess) {
  37238. _this.onSuccess(_this);
  37239. }
  37240. onSuccess();
  37241. };
  37242. var onerror = function () {
  37243. if (_this.onError) {
  37244. _this.onError(_this);
  37245. }
  37246. onError();
  37247. };
  37248. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37249. };
  37250. return TextureAssetTask;
  37251. }());
  37252. BABYLON.TextureAssetTask = TextureAssetTask;
  37253. var AssetsManager = (function () {
  37254. function AssetsManager(scene) {
  37255. this._tasks = new Array();
  37256. this._waitingTasksCount = 0;
  37257. this.useDefaultLoadingScreen = true;
  37258. this._scene = scene;
  37259. }
  37260. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37261. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37262. this._tasks.push(task);
  37263. return task;
  37264. };
  37265. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37266. var task = new TextFileAssetTask(taskName, url);
  37267. this._tasks.push(task);
  37268. return task;
  37269. };
  37270. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37271. var task = new BinaryFileAssetTask(taskName, url);
  37272. this._tasks.push(task);
  37273. return task;
  37274. };
  37275. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37276. var task = new ImageAssetTask(taskName, url);
  37277. this._tasks.push(task);
  37278. return task;
  37279. };
  37280. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37282. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37283. this._tasks.push(task);
  37284. return task;
  37285. };
  37286. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37287. this._waitingTasksCount--;
  37288. if (this._waitingTasksCount === 0) {
  37289. if (this.onFinish) {
  37290. this.onFinish(this._tasks);
  37291. }
  37292. this._scene.getEngine().hideLoadingUI();
  37293. }
  37294. };
  37295. AssetsManager.prototype._runTask = function (task) {
  37296. var _this = this;
  37297. task.run(this._scene, function () {
  37298. if (_this.onTaskSuccess) {
  37299. _this.onTaskSuccess(task);
  37300. }
  37301. _this._decreaseWaitingTasksCount();
  37302. }, function () {
  37303. if (_this.onTaskError) {
  37304. _this.onTaskError(task);
  37305. }
  37306. _this._decreaseWaitingTasksCount();
  37307. });
  37308. };
  37309. AssetsManager.prototype.reset = function () {
  37310. this._tasks = new Array();
  37311. return this;
  37312. };
  37313. AssetsManager.prototype.load = function () {
  37314. this._waitingTasksCount = this._tasks.length;
  37315. if (this._waitingTasksCount === 0) {
  37316. if (this.onFinish) {
  37317. this.onFinish(this._tasks);
  37318. }
  37319. return this;
  37320. }
  37321. if (this.useDefaultLoadingScreen) {
  37322. this._scene.getEngine().displayLoadingUI();
  37323. }
  37324. for (var index = 0; index < this._tasks.length; index++) {
  37325. var task = this._tasks[index];
  37326. this._runTask(task);
  37327. }
  37328. return this;
  37329. };
  37330. return AssetsManager;
  37331. }());
  37332. BABYLON.AssetsManager = AssetsManager;
  37333. })(BABYLON || (BABYLON = {}));
  37334. var BABYLON;
  37335. (function (BABYLON) {
  37336. var VRCameraMetrics = (function () {
  37337. function VRCameraMetrics() {
  37338. this.compensateDistortion = true;
  37339. }
  37340. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37341. get: function () {
  37342. return this.hResolution / (2 * this.vResolution);
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37348. get: function () {
  37349. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37350. },
  37351. enumerable: true,
  37352. configurable: true
  37353. });
  37354. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37355. get: function () {
  37356. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37357. var h = (4 * meters) / this.hScreenSize;
  37358. return BABYLON.Matrix.Translation(h, 0, 0);
  37359. },
  37360. enumerable: true,
  37361. configurable: true
  37362. });
  37363. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37364. get: function () {
  37365. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37366. var h = (4 * meters) / this.hScreenSize;
  37367. return BABYLON.Matrix.Translation(-h, 0, 0);
  37368. },
  37369. enumerable: true,
  37370. configurable: true
  37371. });
  37372. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37373. get: function () {
  37374. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37375. },
  37376. enumerable: true,
  37377. configurable: true
  37378. });
  37379. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37380. get: function () {
  37381. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37382. },
  37383. enumerable: true,
  37384. configurable: true
  37385. });
  37386. VRCameraMetrics.GetDefault = function () {
  37387. var result = new VRCameraMetrics();
  37388. result.hResolution = 1280;
  37389. result.vResolution = 800;
  37390. result.hScreenSize = 0.149759993;
  37391. result.vScreenSize = 0.0935999975;
  37392. result.vScreenCenter = 0.0467999987,
  37393. result.eyeToScreenDistance = 0.0410000011;
  37394. result.lensSeparationDistance = 0.0635000020;
  37395. result.interpupillaryDistance = 0.0640000030;
  37396. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37397. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  37398. result.postProcessScaleFactor = 1.714605507808412;
  37399. result.lensCenterOffset = 0.151976421;
  37400. return result;
  37401. };
  37402. return VRCameraMetrics;
  37403. }());
  37404. BABYLON.VRCameraMetrics = VRCameraMetrics;
  37405. })(BABYLON || (BABYLON = {}));
  37406. var BABYLON;
  37407. (function (BABYLON) {
  37408. var VRDeviceOrientationFreeCamera = (function (_super) {
  37409. __extends(VRDeviceOrientationFreeCamera, _super);
  37410. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  37411. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37412. _super.call(this, name, position, scene);
  37413. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37414. metrics.compensateDistortion = compensateDistortion;
  37415. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37416. this.inputs.addVRDeviceOrientation();
  37417. }
  37418. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  37419. return "VRDeviceOrientationFreeCamera";
  37420. };
  37421. return VRDeviceOrientationFreeCamera;
  37422. }(BABYLON.FreeCamera));
  37423. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  37424. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  37425. __extends(VRDeviceOrientationArcRotateCamera, _super);
  37426. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  37427. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37428. _super.call(this, name, alpha, beta, radius, target, scene);
  37429. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37430. metrics.compensateDistortion = compensateDistortion;
  37431. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37432. this.inputs.addVRDeviceOrientation();
  37433. }
  37434. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  37435. return "VRDeviceOrientationArcRotateCamera";
  37436. };
  37437. return VRDeviceOrientationArcRotateCamera;
  37438. }(BABYLON.ArcRotateCamera));
  37439. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  37440. })(BABYLON || (BABYLON = {}));
  37441. var BABYLON;
  37442. (function (BABYLON) {
  37443. var WebVRFreeCamera = (function (_super) {
  37444. __extends(WebVRFreeCamera, _super);
  37445. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  37446. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37447. _super.call(this, name, position, scene);
  37448. this._hmdDevice = null;
  37449. this._sensorDevice = null;
  37450. this._cacheState = null;
  37451. this._cacheQuaternion = new BABYLON.Quaternion();
  37452. this._cacheRotation = BABYLON.Vector3.Zero();
  37453. this._vrEnabled = false;
  37454. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37455. metrics.compensateDistortion = compensateDistortion;
  37456. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37457. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37458. }
  37459. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37460. var size = devices.length;
  37461. var i = 0;
  37462. // Reset devices.
  37463. this._sensorDevice = null;
  37464. this._hmdDevice = null;
  37465. // Search for a HmdDevice.
  37466. while (i < size && this._hmdDevice === null) {
  37467. if (devices[i] instanceof HMDVRDevice) {
  37468. this._hmdDevice = devices[i];
  37469. }
  37470. i++;
  37471. }
  37472. i = 0;
  37473. while (i < size && this._sensorDevice === null) {
  37474. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37475. this._sensorDevice = devices[i];
  37476. }
  37477. i++;
  37478. }
  37479. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37480. };
  37481. WebVRFreeCamera.prototype._checkInputs = function () {
  37482. if (this._vrEnabled) {
  37483. this._cacheState = this._sensorDevice.getState();
  37484. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37485. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37486. this.rotation.x = -this._cacheRotation.x;
  37487. this.rotation.y = -this._cacheRotation.y;
  37488. this.rotation.z = this._cacheRotation.z;
  37489. }
  37490. _super.prototype._checkInputs.call(this);
  37491. };
  37492. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37493. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37494. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37495. if (navigator.getVRDevices) {
  37496. navigator.getVRDevices().then(this._getWebVRDevices);
  37497. }
  37498. else if (navigator.mozGetVRDevices) {
  37499. navigator.mozGetVRDevices(this._getWebVRDevices);
  37500. }
  37501. };
  37502. WebVRFreeCamera.prototype.detachControl = function (element) {
  37503. _super.prototype.detachControl.call(this, element);
  37504. this._vrEnabled = false;
  37505. };
  37506. WebVRFreeCamera.prototype.getTypeName = function () {
  37507. return "WebVRFreeCamera";
  37508. };
  37509. return WebVRFreeCamera;
  37510. }(BABYLON.FreeCamera));
  37511. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37512. })(BABYLON || (BABYLON = {}));
  37513. var BABYLON;
  37514. (function (BABYLON) {
  37515. // Standard optimizations
  37516. var SceneOptimization = (function () {
  37517. function SceneOptimization(priority) {
  37518. if (priority === void 0) { priority = 0; }
  37519. this.priority = priority;
  37520. this.apply = function (scene) {
  37521. return true; // Return true if everything that can be done was applied
  37522. };
  37523. }
  37524. return SceneOptimization;
  37525. }());
  37526. BABYLON.SceneOptimization = SceneOptimization;
  37527. var TextureOptimization = (function (_super) {
  37528. __extends(TextureOptimization, _super);
  37529. function TextureOptimization(priority, maximumSize) {
  37530. var _this = this;
  37531. if (priority === void 0) { priority = 0; }
  37532. if (maximumSize === void 0) { maximumSize = 1024; }
  37533. _super.call(this, priority);
  37534. this.priority = priority;
  37535. this.maximumSize = maximumSize;
  37536. this.apply = function (scene) {
  37537. var allDone = true;
  37538. for (var index = 0; index < scene.textures.length; index++) {
  37539. var texture = scene.textures[index];
  37540. if (!texture.canRescale) {
  37541. continue;
  37542. }
  37543. var currentSize = texture.getSize();
  37544. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37545. if (maxDimension > _this.maximumSize) {
  37546. texture.scale(0.5);
  37547. allDone = false;
  37548. }
  37549. }
  37550. return allDone;
  37551. };
  37552. }
  37553. return TextureOptimization;
  37554. }(SceneOptimization));
  37555. BABYLON.TextureOptimization = TextureOptimization;
  37556. var HardwareScalingOptimization = (function (_super) {
  37557. __extends(HardwareScalingOptimization, _super);
  37558. function HardwareScalingOptimization(priority, maximumScale) {
  37559. var _this = this;
  37560. if (priority === void 0) { priority = 0; }
  37561. if (maximumScale === void 0) { maximumScale = 2; }
  37562. _super.call(this, priority);
  37563. this.priority = priority;
  37564. this.maximumScale = maximumScale;
  37565. this._currentScale = 1;
  37566. this.apply = function (scene) {
  37567. _this._currentScale++;
  37568. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37569. return _this._currentScale >= _this.maximumScale;
  37570. };
  37571. }
  37572. return HardwareScalingOptimization;
  37573. }(SceneOptimization));
  37574. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37575. var ShadowsOptimization = (function (_super) {
  37576. __extends(ShadowsOptimization, _super);
  37577. function ShadowsOptimization() {
  37578. _super.apply(this, arguments);
  37579. this.apply = function (scene) {
  37580. scene.shadowsEnabled = false;
  37581. return true;
  37582. };
  37583. }
  37584. return ShadowsOptimization;
  37585. }(SceneOptimization));
  37586. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37587. var PostProcessesOptimization = (function (_super) {
  37588. __extends(PostProcessesOptimization, _super);
  37589. function PostProcessesOptimization() {
  37590. _super.apply(this, arguments);
  37591. this.apply = function (scene) {
  37592. scene.postProcessesEnabled = false;
  37593. return true;
  37594. };
  37595. }
  37596. return PostProcessesOptimization;
  37597. }(SceneOptimization));
  37598. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37599. var LensFlaresOptimization = (function (_super) {
  37600. __extends(LensFlaresOptimization, _super);
  37601. function LensFlaresOptimization() {
  37602. _super.apply(this, arguments);
  37603. this.apply = function (scene) {
  37604. scene.lensFlaresEnabled = false;
  37605. return true;
  37606. };
  37607. }
  37608. return LensFlaresOptimization;
  37609. }(SceneOptimization));
  37610. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37611. var ParticlesOptimization = (function (_super) {
  37612. __extends(ParticlesOptimization, _super);
  37613. function ParticlesOptimization() {
  37614. _super.apply(this, arguments);
  37615. this.apply = function (scene) {
  37616. scene.particlesEnabled = false;
  37617. return true;
  37618. };
  37619. }
  37620. return ParticlesOptimization;
  37621. }(SceneOptimization));
  37622. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37623. var RenderTargetsOptimization = (function (_super) {
  37624. __extends(RenderTargetsOptimization, _super);
  37625. function RenderTargetsOptimization() {
  37626. _super.apply(this, arguments);
  37627. this.apply = function (scene) {
  37628. scene.renderTargetsEnabled = false;
  37629. return true;
  37630. };
  37631. }
  37632. return RenderTargetsOptimization;
  37633. }(SceneOptimization));
  37634. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37635. var MergeMeshesOptimization = (function (_super) {
  37636. __extends(MergeMeshesOptimization, _super);
  37637. function MergeMeshesOptimization() {
  37638. var _this = this;
  37639. _super.apply(this, arguments);
  37640. this._canBeMerged = function (abstractMesh) {
  37641. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37642. return false;
  37643. }
  37644. var mesh = abstractMesh;
  37645. if (!mesh.isVisible || !mesh.isEnabled()) {
  37646. return false;
  37647. }
  37648. if (mesh.instances.length > 0) {
  37649. return false;
  37650. }
  37651. if (mesh.skeleton || mesh.hasLODLevels) {
  37652. return false;
  37653. }
  37654. if (mesh.parent) {
  37655. return false;
  37656. }
  37657. return true;
  37658. };
  37659. this.apply = function (scene, updateSelectionTree) {
  37660. var globalPool = scene.meshes.slice(0);
  37661. var globalLength = globalPool.length;
  37662. for (var index = 0; index < globalLength; index++) {
  37663. var currentPool = new Array();
  37664. var current = globalPool[index];
  37665. // Checks
  37666. if (!_this._canBeMerged(current)) {
  37667. continue;
  37668. }
  37669. currentPool.push(current);
  37670. // Find compatible meshes
  37671. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37672. var otherMesh = globalPool[subIndex];
  37673. if (!_this._canBeMerged(otherMesh)) {
  37674. continue;
  37675. }
  37676. if (otherMesh.material !== current.material) {
  37677. continue;
  37678. }
  37679. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37680. continue;
  37681. }
  37682. currentPool.push(otherMesh);
  37683. globalLength--;
  37684. globalPool.splice(subIndex, 1);
  37685. subIndex--;
  37686. }
  37687. if (currentPool.length < 2) {
  37688. continue;
  37689. }
  37690. // Merge meshes
  37691. BABYLON.Mesh.MergeMeshes(currentPool);
  37692. }
  37693. if (updateSelectionTree != undefined) {
  37694. if (updateSelectionTree) {
  37695. scene.createOrUpdateSelectionOctree();
  37696. }
  37697. }
  37698. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37699. scene.createOrUpdateSelectionOctree();
  37700. }
  37701. return true;
  37702. };
  37703. }
  37704. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37705. get: function () {
  37706. return MergeMeshesOptimization._UpdateSelectionTree;
  37707. },
  37708. set: function (value) {
  37709. MergeMeshesOptimization._UpdateSelectionTree = value;
  37710. },
  37711. enumerable: true,
  37712. configurable: true
  37713. });
  37714. MergeMeshesOptimization._UpdateSelectionTree = false;
  37715. return MergeMeshesOptimization;
  37716. }(SceneOptimization));
  37717. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37718. // Options
  37719. var SceneOptimizerOptions = (function () {
  37720. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37721. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37722. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37723. this.targetFrameRate = targetFrameRate;
  37724. this.trackerDuration = trackerDuration;
  37725. this.optimizations = new Array();
  37726. }
  37727. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37728. var result = new SceneOptimizerOptions(targetFrameRate);
  37729. var priority = 0;
  37730. result.optimizations.push(new MergeMeshesOptimization(priority));
  37731. result.optimizations.push(new ShadowsOptimization(priority));
  37732. result.optimizations.push(new LensFlaresOptimization(priority));
  37733. // Next priority
  37734. priority++;
  37735. result.optimizations.push(new PostProcessesOptimization(priority));
  37736. result.optimizations.push(new ParticlesOptimization(priority));
  37737. // Next priority
  37738. priority++;
  37739. result.optimizations.push(new TextureOptimization(priority, 1024));
  37740. return result;
  37741. };
  37742. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37743. var result = new SceneOptimizerOptions(targetFrameRate);
  37744. var priority = 0;
  37745. result.optimizations.push(new MergeMeshesOptimization(priority));
  37746. result.optimizations.push(new ShadowsOptimization(priority));
  37747. result.optimizations.push(new LensFlaresOptimization(priority));
  37748. // Next priority
  37749. priority++;
  37750. result.optimizations.push(new PostProcessesOptimization(priority));
  37751. result.optimizations.push(new ParticlesOptimization(priority));
  37752. // Next priority
  37753. priority++;
  37754. result.optimizations.push(new TextureOptimization(priority, 512));
  37755. // Next priority
  37756. priority++;
  37757. result.optimizations.push(new RenderTargetsOptimization(priority));
  37758. // Next priority
  37759. priority++;
  37760. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37761. return result;
  37762. };
  37763. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37764. var result = new SceneOptimizerOptions(targetFrameRate);
  37765. var priority = 0;
  37766. result.optimizations.push(new MergeMeshesOptimization(priority));
  37767. result.optimizations.push(new ShadowsOptimization(priority));
  37768. result.optimizations.push(new LensFlaresOptimization(priority));
  37769. // Next priority
  37770. priority++;
  37771. result.optimizations.push(new PostProcessesOptimization(priority));
  37772. result.optimizations.push(new ParticlesOptimization(priority));
  37773. // Next priority
  37774. priority++;
  37775. result.optimizations.push(new TextureOptimization(priority, 256));
  37776. // Next priority
  37777. priority++;
  37778. result.optimizations.push(new RenderTargetsOptimization(priority));
  37779. // Next priority
  37780. priority++;
  37781. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37782. return result;
  37783. };
  37784. return SceneOptimizerOptions;
  37785. }());
  37786. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37787. // Scene optimizer tool
  37788. var SceneOptimizer = (function () {
  37789. function SceneOptimizer() {
  37790. }
  37791. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37792. // TODO: add an epsilon
  37793. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37794. if (onSuccess) {
  37795. onSuccess();
  37796. }
  37797. return;
  37798. }
  37799. // Apply current level of optimizations
  37800. var allDone = true;
  37801. var noOptimizationApplied = true;
  37802. for (var index = 0; index < options.optimizations.length; index++) {
  37803. var optimization = options.optimizations[index];
  37804. if (optimization.priority === currentPriorityLevel) {
  37805. noOptimizationApplied = false;
  37806. allDone = allDone && optimization.apply(scene);
  37807. }
  37808. }
  37809. // If no optimization was applied, this is a failure :(
  37810. if (noOptimizationApplied) {
  37811. if (onFailure) {
  37812. onFailure();
  37813. }
  37814. return;
  37815. }
  37816. // If all optimizations were done, move to next level
  37817. if (allDone) {
  37818. currentPriorityLevel++;
  37819. }
  37820. // Let's the system running for a specific amount of time before checking FPS
  37821. scene.executeWhenReady(function () {
  37822. setTimeout(function () {
  37823. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  37824. }, options.trackerDuration);
  37825. });
  37826. };
  37827. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  37828. if (!options) {
  37829. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  37830. }
  37831. // Let's the system running for a specific amount of time before checking FPS
  37832. scene.executeWhenReady(function () {
  37833. setTimeout(function () {
  37834. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  37835. }, options.trackerDuration);
  37836. });
  37837. };
  37838. return SceneOptimizer;
  37839. }());
  37840. BABYLON.SceneOptimizer = SceneOptimizer;
  37841. })(BABYLON || (BABYLON = {}));
  37842. var BABYLON;
  37843. (function (BABYLON) {
  37844. var Internals;
  37845. (function (Internals) {
  37846. var MeshLODLevel = (function () {
  37847. function MeshLODLevel(distance, mesh) {
  37848. this.distance = distance;
  37849. this.mesh = mesh;
  37850. }
  37851. return MeshLODLevel;
  37852. }());
  37853. Internals.MeshLODLevel = MeshLODLevel;
  37854. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37855. })(BABYLON || (BABYLON = {}));
  37856. var BABYLON;
  37857. (function (BABYLON) {
  37858. var RawTexture = (function (_super) {
  37859. __extends(RawTexture, _super);
  37860. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  37861. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37862. if (invertY === void 0) { invertY = false; }
  37863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37864. _super.call(this, null, scene, !generateMipMaps, invertY);
  37865. this.format = format;
  37866. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  37867. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37868. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37869. }
  37870. RawTexture.prototype.update = function (data) {
  37871. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  37872. };
  37873. // Statics
  37874. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37875. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37876. if (invertY === void 0) { invertY = false; }
  37877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37878. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  37879. };
  37880. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37881. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37882. if (invertY === void 0) { invertY = false; }
  37883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37884. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37885. };
  37886. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37887. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37888. if (invertY === void 0) { invertY = false; }
  37889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37890. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37891. };
  37892. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37893. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37894. if (invertY === void 0) { invertY = false; }
  37895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37896. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  37897. };
  37898. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37899. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37900. if (invertY === void 0) { invertY = false; }
  37901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37902. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  37903. };
  37904. return RawTexture;
  37905. }(BABYLON.Texture));
  37906. BABYLON.RawTexture = RawTexture;
  37907. })(BABYLON || (BABYLON = {}));
  37908. var BABYLON;
  37909. (function (BABYLON) {
  37910. var IndexedVector2 = (function (_super) {
  37911. __extends(IndexedVector2, _super);
  37912. function IndexedVector2(original, index) {
  37913. _super.call(this, original.x, original.y);
  37914. this.index = index;
  37915. }
  37916. return IndexedVector2;
  37917. }(BABYLON.Vector2));
  37918. var PolygonPoints = (function () {
  37919. function PolygonPoints() {
  37920. this.elements = new Array();
  37921. }
  37922. PolygonPoints.prototype.add = function (originalPoints) {
  37923. var _this = this;
  37924. var result = new Array();
  37925. originalPoints.forEach(function (point) {
  37926. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  37927. var newPoint = new IndexedVector2(point, _this.elements.length);
  37928. result.push(newPoint);
  37929. _this.elements.push(newPoint);
  37930. }
  37931. });
  37932. return result;
  37933. };
  37934. PolygonPoints.prototype.computeBounds = function () {
  37935. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  37936. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  37937. this.elements.forEach(function (point) {
  37938. // x
  37939. if (point.x < lmin.x) {
  37940. lmin.x = point.x;
  37941. }
  37942. else if (point.x > lmax.x) {
  37943. lmax.x = point.x;
  37944. }
  37945. // y
  37946. if (point.y < lmin.y) {
  37947. lmin.y = point.y;
  37948. }
  37949. else if (point.y > lmax.y) {
  37950. lmax.y = point.y;
  37951. }
  37952. });
  37953. return {
  37954. min: lmin,
  37955. max: lmax,
  37956. width: lmax.x - lmin.x,
  37957. height: lmax.y - lmin.y
  37958. };
  37959. };
  37960. return PolygonPoints;
  37961. }());
  37962. var Polygon = (function () {
  37963. function Polygon() {
  37964. }
  37965. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  37966. return [
  37967. new BABYLON.Vector2(xmin, ymin),
  37968. new BABYLON.Vector2(xmax, ymin),
  37969. new BABYLON.Vector2(xmax, ymax),
  37970. new BABYLON.Vector2(xmin, ymax)
  37971. ];
  37972. };
  37973. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  37974. if (cx === void 0) { cx = 0; }
  37975. if (cy === void 0) { cy = 0; }
  37976. if (numberOfSides === void 0) { numberOfSides = 32; }
  37977. var result = new Array();
  37978. var angle = 0;
  37979. var increment = (Math.PI * 2) / numberOfSides;
  37980. for (var i = 0; i < numberOfSides; i++) {
  37981. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  37982. angle -= increment;
  37983. }
  37984. return result;
  37985. };
  37986. Polygon.Parse = function (input) {
  37987. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  37988. var i, result = [];
  37989. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  37990. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  37991. }
  37992. return result;
  37993. };
  37994. Polygon.StartingAt = function (x, y) {
  37995. return BABYLON.Path2.StartingAt(x, y);
  37996. };
  37997. return Polygon;
  37998. }());
  37999. BABYLON.Polygon = Polygon;
  38000. var PolygonMeshBuilder = (function () {
  38001. function PolygonMeshBuilder(name, contours, scene) {
  38002. this._points = new PolygonPoints();
  38003. this._outlinepoints = new PolygonPoints();
  38004. this._holes = [];
  38005. if (!("poly2tri" in window)) {
  38006. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  38007. }
  38008. this._name = name;
  38009. this._scene = scene;
  38010. var points;
  38011. if (contours instanceof BABYLON.Path2) {
  38012. points = contours.getPoints();
  38013. }
  38014. else {
  38015. points = contours;
  38016. }
  38017. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  38018. this._outlinepoints.add(points);
  38019. }
  38020. PolygonMeshBuilder.prototype.addHole = function (hole) {
  38021. this._swctx.addHole(this._points.add(hole));
  38022. var holepoints = new PolygonPoints();
  38023. holepoints.add(hole);
  38024. this._holes.push(holepoints);
  38025. return this;
  38026. };
  38027. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38028. var _this = this;
  38029. if (updatable === void 0) { updatable = false; }
  38030. var result = new BABYLON.Mesh(this._name, this._scene);
  38031. var normals = [];
  38032. var positions = [];
  38033. var uvs = [];
  38034. var bounds = this._points.computeBounds();
  38035. this._points.elements.forEach(function (p) {
  38036. normals.push(0, 1.0, 0);
  38037. positions.push(p.x, 0, p.y);
  38038. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38039. });
  38040. var indices = [];
  38041. this._swctx.triangulate();
  38042. this._swctx.getTriangles().forEach(function (triangle) {
  38043. triangle.getPoints().forEach(function (point) {
  38044. indices.push(point.index);
  38045. });
  38046. });
  38047. if (depth > 0) {
  38048. var positionscount = (positions.length / 3); //get the current pointcount
  38049. this._points.elements.forEach(function (p) {
  38050. normals.push(0, -1.0, 0);
  38051. positions.push(p.x, -depth, p.y);
  38052. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38053. });
  38054. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38055. var p2;
  38056. var poscounter = 0;
  38057. this._swctx.getTriangles().forEach(function (triangle) {
  38058. triangle.getPoints().forEach(function (point) {
  38059. switch (poscounter) {
  38060. case 0:
  38061. p1 = point;
  38062. break;
  38063. case 1:
  38064. p2 = point;
  38065. break;
  38066. case 2:
  38067. indices.push(point.index + positionscount);
  38068. indices.push(p2.index + positionscount);
  38069. indices.push(p1.index + positionscount);
  38070. poscounter = -1;
  38071. break;
  38072. }
  38073. poscounter++;
  38074. //indices.push((<IndexedVector2>point).index + positionscount);
  38075. });
  38076. });
  38077. //Add the sides
  38078. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38079. this._holes.forEach(function (hole) {
  38080. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38081. });
  38082. }
  38083. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38084. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38085. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38086. result.setIndices(indices);
  38087. return result;
  38088. };
  38089. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38090. var StartIndex = positions.length / 3;
  38091. var ulength = 0;
  38092. for (var i = 0; i < points.elements.length; i++) {
  38093. var p = points.elements[i];
  38094. var p1;
  38095. if ((i + 1) > points.elements.length - 1) {
  38096. p1 = points.elements[0];
  38097. }
  38098. else {
  38099. p1 = points.elements[i + 1];
  38100. }
  38101. positions.push(p.x, 0, p.y);
  38102. positions.push(p.x, -depth, p.y);
  38103. positions.push(p1.x, 0, p1.y);
  38104. positions.push(p1.x, -depth, p1.y);
  38105. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38106. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38107. var v3 = v2.subtract(v1);
  38108. var v4 = new BABYLON.Vector3(0, 1, 0);
  38109. var vn = BABYLON.Vector3.Cross(v3, v4);
  38110. vn = vn.normalize();
  38111. uvs.push(ulength / bounds.width, 0);
  38112. uvs.push(ulength / bounds.width, 1);
  38113. ulength += v3.length();
  38114. uvs.push((ulength / bounds.width), 0);
  38115. uvs.push((ulength / bounds.width), 1);
  38116. if (!flip) {
  38117. normals.push(-vn.x, -vn.y, -vn.z);
  38118. normals.push(-vn.x, -vn.y, -vn.z);
  38119. normals.push(-vn.x, -vn.y, -vn.z);
  38120. normals.push(-vn.x, -vn.y, -vn.z);
  38121. indices.push(StartIndex);
  38122. indices.push(StartIndex + 1);
  38123. indices.push(StartIndex + 2);
  38124. indices.push(StartIndex + 1);
  38125. indices.push(StartIndex + 3);
  38126. indices.push(StartIndex + 2);
  38127. }
  38128. else {
  38129. normals.push(vn.x, vn.y, vn.z);
  38130. normals.push(vn.x, vn.y, vn.z);
  38131. normals.push(vn.x, vn.y, vn.z);
  38132. normals.push(vn.x, vn.y, vn.z);
  38133. indices.push(StartIndex);
  38134. indices.push(StartIndex + 2);
  38135. indices.push(StartIndex + 1);
  38136. indices.push(StartIndex + 1);
  38137. indices.push(StartIndex + 2);
  38138. indices.push(StartIndex + 3);
  38139. }
  38140. StartIndex += 4;
  38141. }
  38142. ;
  38143. };
  38144. return PolygonMeshBuilder;
  38145. }());
  38146. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38147. })(BABYLON || (BABYLON = {}));
  38148. var BABYLON;
  38149. (function (BABYLON) {
  38150. var Octree = (function () {
  38151. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38152. if (maxDepth === void 0) { maxDepth = 2; }
  38153. this.maxDepth = maxDepth;
  38154. this.dynamicContent = new Array();
  38155. this._maxBlockCapacity = maxBlockCapacity || 64;
  38156. this._selectionContent = new BABYLON.SmartArray(1024);
  38157. this._creationFunc = creationFunc;
  38158. }
  38159. // Methods
  38160. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38161. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38162. };
  38163. Octree.prototype.addMesh = function (entry) {
  38164. for (var index = 0; index < this.blocks.length; index++) {
  38165. var block = this.blocks[index];
  38166. block.addEntry(entry);
  38167. }
  38168. };
  38169. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38170. this._selectionContent.reset();
  38171. for (var index = 0; index < this.blocks.length; index++) {
  38172. var block = this.blocks[index];
  38173. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38174. }
  38175. if (allowDuplicate) {
  38176. this._selectionContent.concat(this.dynamicContent);
  38177. }
  38178. else {
  38179. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38180. }
  38181. return this._selectionContent;
  38182. };
  38183. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38184. this._selectionContent.reset();
  38185. for (var index = 0; index < this.blocks.length; index++) {
  38186. var block = this.blocks[index];
  38187. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38188. }
  38189. if (allowDuplicate) {
  38190. this._selectionContent.concat(this.dynamicContent);
  38191. }
  38192. else {
  38193. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38194. }
  38195. return this._selectionContent;
  38196. };
  38197. Octree.prototype.intersectsRay = function (ray) {
  38198. this._selectionContent.reset();
  38199. for (var index = 0; index < this.blocks.length; index++) {
  38200. var block = this.blocks[index];
  38201. block.intersectsRay(ray, this._selectionContent);
  38202. }
  38203. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38204. return this._selectionContent;
  38205. };
  38206. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38207. target.blocks = new Array();
  38208. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38209. // Segmenting space
  38210. for (var x = 0; x < 2; x++) {
  38211. for (var y = 0; y < 2; y++) {
  38212. for (var z = 0; z < 2; z++) {
  38213. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38214. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38215. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38216. block.addEntries(entries);
  38217. target.blocks.push(block);
  38218. }
  38219. }
  38220. }
  38221. };
  38222. Octree.CreationFuncForMeshes = function (entry, block) {
  38223. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38224. block.entries.push(entry);
  38225. }
  38226. };
  38227. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38228. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38229. block.entries.push(entry);
  38230. }
  38231. };
  38232. return Octree;
  38233. }());
  38234. BABYLON.Octree = Octree;
  38235. })(BABYLON || (BABYLON = {}));
  38236. var BABYLON;
  38237. (function (BABYLON) {
  38238. var OctreeBlock = (function () {
  38239. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38240. this.entries = new Array();
  38241. this._boundingVectors = new Array();
  38242. this._capacity = capacity;
  38243. this._depth = depth;
  38244. this._maxDepth = maxDepth;
  38245. this._creationFunc = creationFunc;
  38246. this._minPoint = minPoint;
  38247. this._maxPoint = maxPoint;
  38248. this._boundingVectors.push(minPoint.clone());
  38249. this._boundingVectors.push(maxPoint.clone());
  38250. this._boundingVectors.push(minPoint.clone());
  38251. this._boundingVectors[2].x = maxPoint.x;
  38252. this._boundingVectors.push(minPoint.clone());
  38253. this._boundingVectors[3].y = maxPoint.y;
  38254. this._boundingVectors.push(minPoint.clone());
  38255. this._boundingVectors[4].z = maxPoint.z;
  38256. this._boundingVectors.push(maxPoint.clone());
  38257. this._boundingVectors[5].z = minPoint.z;
  38258. this._boundingVectors.push(maxPoint.clone());
  38259. this._boundingVectors[6].x = minPoint.x;
  38260. this._boundingVectors.push(maxPoint.clone());
  38261. this._boundingVectors[7].y = minPoint.y;
  38262. }
  38263. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38264. // Property
  38265. get: function () {
  38266. return this._capacity;
  38267. },
  38268. enumerable: true,
  38269. configurable: true
  38270. });
  38271. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38272. get: function () {
  38273. return this._minPoint;
  38274. },
  38275. enumerable: true,
  38276. configurable: true
  38277. });
  38278. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38279. get: function () {
  38280. return this._maxPoint;
  38281. },
  38282. enumerable: true,
  38283. configurable: true
  38284. });
  38285. // Methods
  38286. OctreeBlock.prototype.addEntry = function (entry) {
  38287. if (this.blocks) {
  38288. for (var index = 0; index < this.blocks.length; index++) {
  38289. var block = this.blocks[index];
  38290. block.addEntry(entry);
  38291. }
  38292. return;
  38293. }
  38294. this._creationFunc(entry, this);
  38295. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38296. this.createInnerBlocks();
  38297. }
  38298. };
  38299. OctreeBlock.prototype.addEntries = function (entries) {
  38300. for (var index = 0; index < entries.length; index++) {
  38301. var mesh = entries[index];
  38302. this.addEntry(mesh);
  38303. }
  38304. };
  38305. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38306. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38307. if (this.blocks) {
  38308. for (var index = 0; index < this.blocks.length; index++) {
  38309. var block = this.blocks[index];
  38310. block.select(frustumPlanes, selection, allowDuplicate);
  38311. }
  38312. return;
  38313. }
  38314. if (allowDuplicate) {
  38315. selection.concat(this.entries);
  38316. }
  38317. else {
  38318. selection.concatWithNoDuplicate(this.entries);
  38319. }
  38320. }
  38321. };
  38322. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38323. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38324. if (this.blocks) {
  38325. for (var index = 0; index < this.blocks.length; index++) {
  38326. var block = this.blocks[index];
  38327. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38328. }
  38329. return;
  38330. }
  38331. if (allowDuplicate) {
  38332. selection.concat(this.entries);
  38333. }
  38334. else {
  38335. selection.concatWithNoDuplicate(this.entries);
  38336. }
  38337. }
  38338. };
  38339. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38340. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38341. if (this.blocks) {
  38342. for (var index = 0; index < this.blocks.length; index++) {
  38343. var block = this.blocks[index];
  38344. block.intersectsRay(ray, selection);
  38345. }
  38346. return;
  38347. }
  38348. selection.concatWithNoDuplicate(this.entries);
  38349. }
  38350. };
  38351. OctreeBlock.prototype.createInnerBlocks = function () {
  38352. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38353. };
  38354. return OctreeBlock;
  38355. }());
  38356. BABYLON.OctreeBlock = OctreeBlock;
  38357. })(BABYLON || (BABYLON = {}));
  38358. var BABYLON;
  38359. (function (BABYLON) {
  38360. var BlurPostProcess = (function (_super) {
  38361. __extends(BlurPostProcess, _super);
  38362. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38363. var _this = this;
  38364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38365. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38366. this.direction = direction;
  38367. this.blurWidth = blurWidth;
  38368. this.onApply = function (effect) {
  38369. effect.setFloat2("screenSize", _this.width, _this.height);
  38370. effect.setVector2("direction", _this.direction);
  38371. effect.setFloat("blurWidth", _this.blurWidth);
  38372. };
  38373. }
  38374. return BlurPostProcess;
  38375. }(BABYLON.PostProcess));
  38376. BABYLON.BlurPostProcess = BlurPostProcess;
  38377. })(BABYLON || (BABYLON = {}));
  38378. var BABYLON;
  38379. (function (BABYLON) {
  38380. var RefractionPostProcess = (function (_super) {
  38381. __extends(RefractionPostProcess, _super);
  38382. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38383. var _this = this;
  38384. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38385. this.color = color;
  38386. this.depth = depth;
  38387. this.colorLevel = colorLevel;
  38388. this.onActivate = function (cam) {
  38389. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38390. };
  38391. this.onApply = function (effect) {
  38392. effect.setColor3("baseColor", _this.color);
  38393. effect.setFloat("depth", _this.depth);
  38394. effect.setFloat("colorLevel", _this.colorLevel);
  38395. effect.setTexture("refractionSampler", _this._refRexture);
  38396. };
  38397. }
  38398. // Methods
  38399. RefractionPostProcess.prototype.dispose = function (camera) {
  38400. if (this._refRexture) {
  38401. this._refRexture.dispose();
  38402. }
  38403. _super.prototype.dispose.call(this, camera);
  38404. };
  38405. return RefractionPostProcess;
  38406. }(BABYLON.PostProcess));
  38407. BABYLON.RefractionPostProcess = RefractionPostProcess;
  38408. })(BABYLON || (BABYLON = {}));
  38409. var BABYLON;
  38410. (function (BABYLON) {
  38411. var BlackAndWhitePostProcess = (function (_super) {
  38412. __extends(BlackAndWhitePostProcess, _super);
  38413. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38414. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  38415. }
  38416. return BlackAndWhitePostProcess;
  38417. }(BABYLON.PostProcess));
  38418. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  38419. })(BABYLON || (BABYLON = {}));
  38420. var BABYLON;
  38421. (function (BABYLON) {
  38422. var ConvolutionPostProcess = (function (_super) {
  38423. __extends(ConvolutionPostProcess, _super);
  38424. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  38425. var _this = this;
  38426. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  38427. this.kernel = kernel;
  38428. this.onApply = function (effect) {
  38429. effect.setFloat2("screenSize", _this.width, _this.height);
  38430. effect.setArray("kernel", _this.kernel);
  38431. };
  38432. }
  38433. // Statics
  38434. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  38435. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  38436. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  38437. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  38438. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  38439. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  38440. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  38441. return ConvolutionPostProcess;
  38442. }(BABYLON.PostProcess));
  38443. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  38444. })(BABYLON || (BABYLON = {}));
  38445. var BABYLON;
  38446. (function (BABYLON) {
  38447. var FilterPostProcess = (function (_super) {
  38448. __extends(FilterPostProcess, _super);
  38449. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38450. var _this = this;
  38451. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38452. this.kernelMatrix = kernelMatrix;
  38453. this.onApply = function (effect) {
  38454. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38455. };
  38456. }
  38457. return FilterPostProcess;
  38458. }(BABYLON.PostProcess));
  38459. BABYLON.FilterPostProcess = FilterPostProcess;
  38460. })(BABYLON || (BABYLON = {}));
  38461. var BABYLON;
  38462. (function (BABYLON) {
  38463. var FxaaPostProcess = (function (_super) {
  38464. __extends(FxaaPostProcess, _super);
  38465. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38466. var _this = this;
  38467. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38468. this.onSizeChanged = function () {
  38469. _this.texelWidth = 1.0 / _this.width;
  38470. _this.texelHeight = 1.0 / _this.height;
  38471. };
  38472. this.onApply = function (effect) {
  38473. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38474. };
  38475. }
  38476. return FxaaPostProcess;
  38477. }(BABYLON.PostProcess));
  38478. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38479. })(BABYLON || (BABYLON = {}));
  38480. var BABYLON;
  38481. (function (BABYLON) {
  38482. var StereoscopicInterlacePostProcess = (function (_super) {
  38483. __extends(StereoscopicInterlacePostProcess, _super);
  38484. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38485. var _this = this;
  38486. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38487. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38488. this.onSizeChanged = function () {
  38489. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38490. };
  38491. this.onApply = function (effect) {
  38492. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38493. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38494. };
  38495. }
  38496. return StereoscopicInterlacePostProcess;
  38497. }(BABYLON.PostProcess));
  38498. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38499. })(BABYLON || (BABYLON = {}));
  38500. var BABYLON;
  38501. (function (BABYLON) {
  38502. var LensFlare = (function () {
  38503. function LensFlare(size, position, color, imgUrl, system) {
  38504. this.size = size;
  38505. this.position = position;
  38506. this.dispose = function () {
  38507. if (this.texture) {
  38508. this.texture.dispose();
  38509. }
  38510. // Remove from scene
  38511. var index = this._system.lensFlares.indexOf(this);
  38512. this._system.lensFlares.splice(index, 1);
  38513. };
  38514. this.color = color || new BABYLON.Color3(1, 1, 1);
  38515. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38516. this._system = system;
  38517. system.lensFlares.push(this);
  38518. }
  38519. return LensFlare;
  38520. }());
  38521. BABYLON.LensFlare = LensFlare;
  38522. })(BABYLON || (BABYLON = {}));
  38523. var BABYLON;
  38524. (function (BABYLON) {
  38525. var LensFlareSystem = (function () {
  38526. function LensFlareSystem(name, emitter, scene) {
  38527. this.name = name;
  38528. this.lensFlares = new Array();
  38529. this.borderLimit = 300;
  38530. this.layerMask = 0x0FFFFFFF;
  38531. this._vertexDeclaration = [2];
  38532. this._vertexStrideSize = 2 * 4;
  38533. this._isEnabled = true;
  38534. this._scene = scene;
  38535. this._emitter = emitter;
  38536. scene.lensFlareSystems.push(this);
  38537. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38538. // VBO
  38539. var vertices = [];
  38540. vertices.push(1, 1);
  38541. vertices.push(-1, 1);
  38542. vertices.push(-1, -1);
  38543. vertices.push(1, -1);
  38544. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38545. // Indices
  38546. var indices = [];
  38547. indices.push(0);
  38548. indices.push(1);
  38549. indices.push(2);
  38550. indices.push(0);
  38551. indices.push(2);
  38552. indices.push(3);
  38553. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38554. // Effects
  38555. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38556. }
  38557. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38558. get: function () {
  38559. return this._isEnabled;
  38560. },
  38561. set: function (value) {
  38562. this._isEnabled = value;
  38563. },
  38564. enumerable: true,
  38565. configurable: true
  38566. });
  38567. LensFlareSystem.prototype.getScene = function () {
  38568. return this._scene;
  38569. };
  38570. LensFlareSystem.prototype.getEmitter = function () {
  38571. return this._emitter;
  38572. };
  38573. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38574. this._emitter = newEmitter;
  38575. };
  38576. LensFlareSystem.prototype.getEmitterPosition = function () {
  38577. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38578. };
  38579. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38580. var position = this.getEmitterPosition();
  38581. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38582. this._positionX = position.x;
  38583. this._positionY = position.y;
  38584. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38585. if (position.z > 0) {
  38586. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38587. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38588. return true;
  38589. }
  38590. }
  38591. return false;
  38592. };
  38593. LensFlareSystem.prototype._isVisible = function () {
  38594. if (!this._isEnabled) {
  38595. return false;
  38596. }
  38597. var emitterPosition = this.getEmitterPosition();
  38598. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38599. var distance = direction.length();
  38600. direction.normalize();
  38601. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38602. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38603. return !pickInfo.hit || pickInfo.distance > distance;
  38604. };
  38605. LensFlareSystem.prototype.render = function () {
  38606. if (!this._effect.isReady())
  38607. return false;
  38608. var engine = this._scene.getEngine();
  38609. var viewport = this._scene.activeCamera.viewport;
  38610. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38611. // Position
  38612. if (!this.computeEffectivePosition(globalViewport)) {
  38613. return false;
  38614. }
  38615. // Visibility
  38616. if (!this._isVisible()) {
  38617. return false;
  38618. }
  38619. // Intensity
  38620. var awayX;
  38621. var awayY;
  38622. if (this._positionX < this.borderLimit + globalViewport.x) {
  38623. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38624. }
  38625. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38626. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38627. }
  38628. else {
  38629. awayX = 0;
  38630. }
  38631. if (this._positionY < this.borderLimit + globalViewport.y) {
  38632. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38633. }
  38634. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38635. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38636. }
  38637. else {
  38638. awayY = 0;
  38639. }
  38640. var away = (awayX > awayY) ? awayX : awayY;
  38641. if (away > this.borderLimit) {
  38642. away = this.borderLimit;
  38643. }
  38644. var intensity = 1.0 - (away / this.borderLimit);
  38645. if (intensity < 0) {
  38646. return false;
  38647. }
  38648. if (intensity > 1.0) {
  38649. intensity = 1.0;
  38650. }
  38651. // Position
  38652. var centerX = globalViewport.x + globalViewport.width / 2;
  38653. var centerY = globalViewport.y + globalViewport.height / 2;
  38654. var distX = centerX - this._positionX;
  38655. var distY = centerY - this._positionY;
  38656. // Effects
  38657. engine.enableEffect(this._effect);
  38658. engine.setState(false);
  38659. engine.setDepthBuffer(false);
  38660. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38661. // VBOs
  38662. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38663. // Flares
  38664. for (var index = 0; index < this.lensFlares.length; index++) {
  38665. var flare = this.lensFlares[index];
  38666. var x = centerX - (distX * flare.position);
  38667. var y = centerY - (distY * flare.position);
  38668. var cw = flare.size;
  38669. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38670. var cx = 2 * (x / globalViewport.width) - 1.0;
  38671. var cy = 1.0 - 2 * (y / globalViewport.height);
  38672. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38673. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38674. // Texture
  38675. this._effect.setTexture("textureSampler", flare.texture);
  38676. // Color
  38677. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38678. // Draw order
  38679. engine.draw(true, 0, 6);
  38680. }
  38681. engine.setDepthBuffer(true);
  38682. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38683. return true;
  38684. };
  38685. LensFlareSystem.prototype.dispose = function () {
  38686. if (this._vertexBuffer) {
  38687. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38688. this._vertexBuffer = null;
  38689. }
  38690. if (this._indexBuffer) {
  38691. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38692. this._indexBuffer = null;
  38693. }
  38694. while (this.lensFlares.length) {
  38695. this.lensFlares[0].dispose();
  38696. }
  38697. // Remove from scene
  38698. var index = this._scene.lensFlareSystems.indexOf(this);
  38699. this._scene.lensFlareSystems.splice(index, 1);
  38700. };
  38701. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38702. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38703. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  38704. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  38705. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38706. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38707. var parsedFlare = parsedLensFlareSystem.flares[index];
  38708. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38709. }
  38710. return lensFlareSystem;
  38711. };
  38712. LensFlareSystem.prototype.serialize = function () {
  38713. var serializationObject = {};
  38714. serializationObject.name = this.name;
  38715. serializationObject.emitterId = this.getEmitter().id;
  38716. serializationObject.borderLimit = this.borderLimit;
  38717. serializationObject.flares = [];
  38718. for (var index = 0; index < this.lensFlares.length; index++) {
  38719. var flare = this.lensFlares[index];
  38720. serializationObject.flares.push({
  38721. size: flare.size,
  38722. position: flare.position,
  38723. color: flare.color.asArray(),
  38724. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38725. });
  38726. }
  38727. return serializationObject;
  38728. };
  38729. return LensFlareSystem;
  38730. }());
  38731. BABYLON.LensFlareSystem = LensFlareSystem;
  38732. })(BABYLON || (BABYLON = {}));
  38733. var BABYLON;
  38734. (function (BABYLON) {
  38735. // We're mainly based on the logic defined into the FreeCamera code
  38736. var DeviceOrientationCamera = (function (_super) {
  38737. __extends(DeviceOrientationCamera, _super);
  38738. //-- end properties for backward compatibility for inputs
  38739. function DeviceOrientationCamera(name, position, scene) {
  38740. _super.call(this, name, position, scene);
  38741. this.inputs.addDeviceOrientation();
  38742. }
  38743. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38744. //-- Begin properties for backward compatibility for inputs
  38745. get: function () {
  38746. var gamepad = this.inputs.attached["deviceOrientation"];
  38747. if (gamepad)
  38748. return gamepad.angularSensibility;
  38749. },
  38750. set: function (value) {
  38751. var gamepad = this.inputs.attached["deviceOrientation"];
  38752. if (gamepad)
  38753. gamepad.angularSensibility = value;
  38754. },
  38755. enumerable: true,
  38756. configurable: true
  38757. });
  38758. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38759. get: function () {
  38760. var gamepad = this.inputs.attached["deviceOrientation"];
  38761. if (gamepad)
  38762. return gamepad.moveSensibility;
  38763. },
  38764. set: function (value) {
  38765. var gamepad = this.inputs.attached["deviceOrientation"];
  38766. if (gamepad)
  38767. gamepad.moveSensibility = value;
  38768. },
  38769. enumerable: true,
  38770. configurable: true
  38771. });
  38772. DeviceOrientationCamera.prototype.getTypeName = function () {
  38773. return "DeviceOrientationCamera";
  38774. };
  38775. return DeviceOrientationCamera;
  38776. }(BABYLON.FreeCamera));
  38777. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38778. })(BABYLON || (BABYLON = {}));
  38779. var BABYLON;
  38780. (function (BABYLON) {
  38781. // We're mainly based on the logic defined into the FreeCamera code
  38782. var UniversalCamera = (function (_super) {
  38783. __extends(UniversalCamera, _super);
  38784. //-- end properties for backward compatibility for inputs
  38785. function UniversalCamera(name, position, scene) {
  38786. _super.call(this, name, position, scene);
  38787. this.inputs.addGamepad();
  38788. }
  38789. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38790. //-- Begin properties for backward compatibility for inputs
  38791. get: function () {
  38792. var gamepad = this.inputs.attached["gamepad"];
  38793. if (gamepad)
  38794. return gamepad.gamepadAngularSensibility;
  38795. },
  38796. set: function (value) {
  38797. var gamepad = this.inputs.attached["gamepad"];
  38798. if (gamepad)
  38799. gamepad.gamepadAngularSensibility = value;
  38800. },
  38801. enumerable: true,
  38802. configurable: true
  38803. });
  38804. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38805. get: function () {
  38806. var gamepad = this.inputs.attached["gamepad"];
  38807. if (gamepad)
  38808. return gamepad.gamepadMoveSensibility;
  38809. },
  38810. set: function (value) {
  38811. var gamepad = this.inputs.attached["gamepad"];
  38812. if (gamepad)
  38813. gamepad.gamepadMoveSensibility = value;
  38814. },
  38815. enumerable: true,
  38816. configurable: true
  38817. });
  38818. UniversalCamera.prototype.getTypeName = function () {
  38819. return "UniversalCamera";
  38820. };
  38821. return UniversalCamera;
  38822. }(BABYLON.TouchCamera));
  38823. BABYLON.UniversalCamera = UniversalCamera;
  38824. })(BABYLON || (BABYLON = {}));
  38825. var BABYLON;
  38826. (function (BABYLON) {
  38827. var Gamepads = (function () {
  38828. function Gamepads(ongamedpadconnected) {
  38829. var _this = this;
  38830. this.babylonGamepads = [];
  38831. this.oneGamepadConnected = false;
  38832. this.isMonitoring = false;
  38833. this.gamepadEventSupported = 'GamepadEvent' in window;
  38834. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38835. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38836. this._callbackGamepadConnected = ongamedpadconnected;
  38837. if (this.gamepadSupportAvailable) {
  38838. // Checking if the gamepad connected event is supported (like in Firefox)
  38839. if (this.gamepadEventSupported) {
  38840. this._onGamepadConnectedEvent = function (evt) {
  38841. _this._onGamepadConnected(evt);
  38842. };
  38843. this._onGamepadDisonnectedEvent = function (evt) {
  38844. _this._onGamepadDisconnected(evt);
  38845. };
  38846. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38847. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38848. }
  38849. else {
  38850. this._startMonitoringGamepads();
  38851. }
  38852. }
  38853. }
  38854. Gamepads.prototype.dispose = function () {
  38855. if (Gamepads.gamepadDOMInfo) {
  38856. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38857. }
  38858. if (this._onGamepadConnectedEvent) {
  38859. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38860. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38861. this._onGamepadConnectedEvent = null;
  38862. this._onGamepadDisonnectedEvent = null;
  38863. }
  38864. };
  38865. Gamepads.prototype._onGamepadConnected = function (evt) {
  38866. var newGamepad = this._addNewGamepad(evt.gamepad);
  38867. if (this._callbackGamepadConnected)
  38868. this._callbackGamepadConnected(newGamepad);
  38869. this._startMonitoringGamepads();
  38870. };
  38871. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38872. if (!this.oneGamepadConnected) {
  38873. this.oneGamepadConnected = true;
  38874. if (Gamepads.gamepadDOMInfo) {
  38875. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38876. Gamepads.gamepadDOMInfo = null;
  38877. }
  38878. }
  38879. var newGamepad;
  38880. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38881. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38882. }
  38883. else {
  38884. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38885. }
  38886. this.babylonGamepads.push(newGamepad);
  38887. return newGamepad;
  38888. };
  38889. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38890. // Remove the gamepad from the list of gamepads to monitor.
  38891. for (var i in this.babylonGamepads) {
  38892. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38893. this.babylonGamepads.splice(+i, 1);
  38894. break;
  38895. }
  38896. }
  38897. // If no gamepads are left, stop the polling loop.
  38898. if (this.babylonGamepads.length == 0) {
  38899. this._stopMonitoringGamepads();
  38900. }
  38901. };
  38902. Gamepads.prototype._startMonitoringGamepads = function () {
  38903. if (!this.isMonitoring) {
  38904. this.isMonitoring = true;
  38905. this._checkGamepadsStatus();
  38906. }
  38907. };
  38908. Gamepads.prototype._stopMonitoringGamepads = function () {
  38909. this.isMonitoring = false;
  38910. };
  38911. Gamepads.prototype._checkGamepadsStatus = function () {
  38912. var _this = this;
  38913. // updating gamepad objects
  38914. this._updateGamepadObjects();
  38915. for (var i in this.babylonGamepads) {
  38916. this.babylonGamepads[i].update();
  38917. }
  38918. if (this.isMonitoring) {
  38919. if (window.requestAnimationFrame) {
  38920. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38921. }
  38922. else if (window.mozRequestAnimationFrame) {
  38923. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38924. }
  38925. else if (window.webkitRequestAnimationFrame) {
  38926. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38927. }
  38928. }
  38929. };
  38930. // This function is called only on Chrome, which does not yet support
  38931. // connection/disconnection events, but requires you to monitor
  38932. // an array for changes.
  38933. Gamepads.prototype._updateGamepadObjects = function () {
  38934. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38935. for (var i = 0; i < gamepads.length; i++) {
  38936. if (gamepads[i]) {
  38937. if (!(gamepads[i].index in this.babylonGamepads)) {
  38938. var newGamepad = this._addNewGamepad(gamepads[i]);
  38939. if (this._callbackGamepadConnected) {
  38940. this._callbackGamepadConnected(newGamepad);
  38941. }
  38942. }
  38943. else {
  38944. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38945. }
  38946. }
  38947. }
  38948. };
  38949. return Gamepads;
  38950. }());
  38951. BABYLON.Gamepads = Gamepads;
  38952. var StickValues = (function () {
  38953. function StickValues(x, y) {
  38954. this.x = x;
  38955. this.y = y;
  38956. }
  38957. return StickValues;
  38958. }());
  38959. BABYLON.StickValues = StickValues;
  38960. var Gamepad = (function () {
  38961. function Gamepad(id, index, browserGamepad) {
  38962. this.id = id;
  38963. this.index = index;
  38964. this.browserGamepad = browserGamepad;
  38965. if (this.browserGamepad.axes.length >= 2) {
  38966. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38967. }
  38968. if (this.browserGamepad.axes.length >= 4) {
  38969. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38970. }
  38971. }
  38972. Gamepad.prototype.onleftstickchanged = function (callback) {
  38973. this._onleftstickchanged = callback;
  38974. };
  38975. Gamepad.prototype.onrightstickchanged = function (callback) {
  38976. this._onrightstickchanged = callback;
  38977. };
  38978. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38979. get: function () {
  38980. return this._leftStick;
  38981. },
  38982. set: function (newValues) {
  38983. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38984. this._onleftstickchanged(newValues);
  38985. }
  38986. this._leftStick = newValues;
  38987. },
  38988. enumerable: true,
  38989. configurable: true
  38990. });
  38991. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38992. get: function () {
  38993. return this._rightStick;
  38994. },
  38995. set: function (newValues) {
  38996. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38997. this._onrightstickchanged(newValues);
  38998. }
  38999. this._rightStick = newValues;
  39000. },
  39001. enumerable: true,
  39002. configurable: true
  39003. });
  39004. Gamepad.prototype.update = function () {
  39005. if (this._leftStick) {
  39006. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39007. }
  39008. if (this._rightStick) {
  39009. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39010. }
  39011. };
  39012. return Gamepad;
  39013. }());
  39014. BABYLON.Gamepad = Gamepad;
  39015. var GenericPad = (function (_super) {
  39016. __extends(GenericPad, _super);
  39017. function GenericPad(id, index, gamepad) {
  39018. _super.call(this, id, index, gamepad);
  39019. this.id = id;
  39020. this.index = index;
  39021. this.gamepad = gamepad;
  39022. this._buttons = new Array(gamepad.buttons.length);
  39023. }
  39024. GenericPad.prototype.onbuttondown = function (callback) {
  39025. this._onbuttondown = callback;
  39026. };
  39027. GenericPad.prototype.onbuttonup = function (callback) {
  39028. this._onbuttonup = callback;
  39029. };
  39030. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39031. if (newValue !== currentValue) {
  39032. if (this._onbuttondown && newValue === 1) {
  39033. this._onbuttondown(buttonIndex);
  39034. }
  39035. if (this._onbuttonup && newValue === 0) {
  39036. this._onbuttonup(buttonIndex);
  39037. }
  39038. }
  39039. return newValue;
  39040. };
  39041. GenericPad.prototype.update = function () {
  39042. _super.prototype.update.call(this);
  39043. for (var index = 0; index < this._buttons.length; index++) {
  39044. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39045. }
  39046. };
  39047. return GenericPad;
  39048. }(Gamepad));
  39049. BABYLON.GenericPad = GenericPad;
  39050. (function (Xbox360Button) {
  39051. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39052. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39053. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39054. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39055. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39056. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39057. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39058. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39059. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39060. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39061. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39062. var Xbox360Button = BABYLON.Xbox360Button;
  39063. (function (Xbox360Dpad) {
  39064. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39065. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39066. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39067. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39068. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39069. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39070. var Xbox360Pad = (function (_super) {
  39071. __extends(Xbox360Pad, _super);
  39072. function Xbox360Pad() {
  39073. _super.apply(this, arguments);
  39074. this._leftTrigger = 0;
  39075. this._rightTrigger = 0;
  39076. this._buttonA = 0;
  39077. this._buttonB = 0;
  39078. this._buttonX = 0;
  39079. this._buttonY = 0;
  39080. this._buttonBack = 0;
  39081. this._buttonStart = 0;
  39082. this._buttonLB = 0;
  39083. this._buttonRB = 0;
  39084. this._buttonLeftStick = 0;
  39085. this._buttonRightStick = 0;
  39086. this._dPadUp = 0;
  39087. this._dPadDown = 0;
  39088. this._dPadLeft = 0;
  39089. this._dPadRight = 0;
  39090. }
  39091. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39092. this._onlefttriggerchanged = callback;
  39093. };
  39094. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39095. this._onrighttriggerchanged = callback;
  39096. };
  39097. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39098. get: function () {
  39099. return this._leftTrigger;
  39100. },
  39101. set: function (newValue) {
  39102. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39103. this._onlefttriggerchanged(newValue);
  39104. }
  39105. this._leftTrigger = newValue;
  39106. },
  39107. enumerable: true,
  39108. configurable: true
  39109. });
  39110. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39111. get: function () {
  39112. return this._rightTrigger;
  39113. },
  39114. set: function (newValue) {
  39115. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39116. this._onrighttriggerchanged(newValue);
  39117. }
  39118. this._rightTrigger = newValue;
  39119. },
  39120. enumerable: true,
  39121. configurable: true
  39122. });
  39123. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39124. this._onbuttondown = callback;
  39125. };
  39126. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39127. this._onbuttonup = callback;
  39128. };
  39129. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39130. this._ondpaddown = callback;
  39131. };
  39132. Xbox360Pad.prototype.ondpadup = function (callback) {
  39133. this._ondpadup = callback;
  39134. };
  39135. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39136. if (newValue !== currentValue) {
  39137. if (this._onbuttondown && newValue === 1) {
  39138. this._onbuttondown(buttonType);
  39139. }
  39140. if (this._onbuttonup && newValue === 0) {
  39141. this._onbuttonup(buttonType);
  39142. }
  39143. }
  39144. return newValue;
  39145. };
  39146. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39147. if (newValue !== currentValue) {
  39148. if (this._ondpaddown && newValue === 1) {
  39149. this._ondpaddown(buttonType);
  39150. }
  39151. if (this._ondpadup && newValue === 0) {
  39152. this._ondpadup(buttonType);
  39153. }
  39154. }
  39155. return newValue;
  39156. };
  39157. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39158. get: function () {
  39159. return this._buttonA;
  39160. },
  39161. set: function (value) {
  39162. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39163. },
  39164. enumerable: true,
  39165. configurable: true
  39166. });
  39167. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39168. get: function () {
  39169. return this._buttonB;
  39170. },
  39171. set: function (value) {
  39172. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39173. },
  39174. enumerable: true,
  39175. configurable: true
  39176. });
  39177. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39178. get: function () {
  39179. return this._buttonX;
  39180. },
  39181. set: function (value) {
  39182. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39183. },
  39184. enumerable: true,
  39185. configurable: true
  39186. });
  39187. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39188. get: function () {
  39189. return this._buttonY;
  39190. },
  39191. set: function (value) {
  39192. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39193. },
  39194. enumerable: true,
  39195. configurable: true
  39196. });
  39197. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39198. get: function () {
  39199. return this._buttonStart;
  39200. },
  39201. set: function (value) {
  39202. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39203. },
  39204. enumerable: true,
  39205. configurable: true
  39206. });
  39207. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39208. get: function () {
  39209. return this._buttonBack;
  39210. },
  39211. set: function (value) {
  39212. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39213. },
  39214. enumerable: true,
  39215. configurable: true
  39216. });
  39217. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39218. get: function () {
  39219. return this._buttonLB;
  39220. },
  39221. set: function (value) {
  39222. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39223. },
  39224. enumerable: true,
  39225. configurable: true
  39226. });
  39227. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39228. get: function () {
  39229. return this._buttonRB;
  39230. },
  39231. set: function (value) {
  39232. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39233. },
  39234. enumerable: true,
  39235. configurable: true
  39236. });
  39237. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39238. get: function () {
  39239. return this._buttonLeftStick;
  39240. },
  39241. set: function (value) {
  39242. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39248. get: function () {
  39249. return this._buttonRightStick;
  39250. },
  39251. set: function (value) {
  39252. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39253. },
  39254. enumerable: true,
  39255. configurable: true
  39256. });
  39257. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39258. get: function () {
  39259. return this._dPadUp;
  39260. },
  39261. set: function (value) {
  39262. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39268. get: function () {
  39269. return this._dPadDown;
  39270. },
  39271. set: function (value) {
  39272. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39273. },
  39274. enumerable: true,
  39275. configurable: true
  39276. });
  39277. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39278. get: function () {
  39279. return this._dPadLeft;
  39280. },
  39281. set: function (value) {
  39282. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39283. },
  39284. enumerable: true,
  39285. configurable: true
  39286. });
  39287. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39288. get: function () {
  39289. return this._dPadRight;
  39290. },
  39291. set: function (value) {
  39292. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39293. },
  39294. enumerable: true,
  39295. configurable: true
  39296. });
  39297. Xbox360Pad.prototype.update = function () {
  39298. _super.prototype.update.call(this);
  39299. this.buttonA = this.browserGamepad.buttons[0].value;
  39300. this.buttonB = this.browserGamepad.buttons[1].value;
  39301. this.buttonX = this.browserGamepad.buttons[2].value;
  39302. this.buttonY = this.browserGamepad.buttons[3].value;
  39303. this.buttonLB = this.browserGamepad.buttons[4].value;
  39304. this.buttonRB = this.browserGamepad.buttons[5].value;
  39305. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39306. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39307. this.buttonBack = this.browserGamepad.buttons[8].value;
  39308. this.buttonStart = this.browserGamepad.buttons[9].value;
  39309. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39310. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39311. this.dPadUp = this.browserGamepad.buttons[12].value;
  39312. this.dPadDown = this.browserGamepad.buttons[13].value;
  39313. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39314. this.dPadRight = this.browserGamepad.buttons[15].value;
  39315. };
  39316. return Xbox360Pad;
  39317. }(Gamepad));
  39318. BABYLON.Xbox360Pad = Xbox360Pad;
  39319. })(BABYLON || (BABYLON = {}));
  39320. var BABYLON;
  39321. (function (BABYLON) {
  39322. // We're mainly based on the logic defined into the FreeCamera code
  39323. var GamepadCamera = (function (_super) {
  39324. __extends(GamepadCamera, _super);
  39325. //-- end properties for backward compatibility for inputs
  39326. function GamepadCamera(name, position, scene) {
  39327. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39328. _super.call(this, name, position, scene);
  39329. }
  39330. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39331. //-- Begin properties for backward compatibility for inputs
  39332. get: function () {
  39333. var gamepad = this.inputs.attached["gamepad"];
  39334. if (gamepad)
  39335. return gamepad.gamepadAngularSensibility;
  39336. },
  39337. set: function (value) {
  39338. var gamepad = this.inputs.attached["gamepad"];
  39339. if (gamepad)
  39340. gamepad.gamepadAngularSensibility = value;
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39346. get: function () {
  39347. var gamepad = this.inputs.attached["gamepad"];
  39348. if (gamepad)
  39349. return gamepad.gamepadMoveSensibility;
  39350. },
  39351. set: function (value) {
  39352. var gamepad = this.inputs.attached["gamepad"];
  39353. if (gamepad)
  39354. gamepad.gamepadMoveSensibility = value;
  39355. },
  39356. enumerable: true,
  39357. configurable: true
  39358. });
  39359. GamepadCamera.prototype.getTypeName = function () {
  39360. return "GamepadCamera";
  39361. };
  39362. return GamepadCamera;
  39363. }(BABYLON.UniversalCamera));
  39364. BABYLON.GamepadCamera = GamepadCamera;
  39365. })(BABYLON || (BABYLON = {}));
  39366. var BABYLON;
  39367. (function (BABYLON) {
  39368. var Analyser = (function () {
  39369. function Analyser(scene) {
  39370. this.SMOOTHING = 0.75;
  39371. this.FFT_SIZE = 512;
  39372. this.BARGRAPHAMPLITUDE = 256;
  39373. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39374. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39375. this._scene = scene;
  39376. this._audioEngine = BABYLON.Engine.audioEngine;
  39377. if (this._audioEngine.canUseWebAudio) {
  39378. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39379. this._webAudioAnalyser.minDecibels = -140;
  39380. this._webAudioAnalyser.maxDecibels = 0;
  39381. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39382. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39383. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39384. }
  39385. }
  39386. Analyser.prototype.getFrequencyBinCount = function () {
  39387. if (this._audioEngine.canUseWebAudio) {
  39388. return this._webAudioAnalyser.frequencyBinCount;
  39389. }
  39390. else {
  39391. return 0;
  39392. }
  39393. };
  39394. Analyser.prototype.getByteFrequencyData = function () {
  39395. if (this._audioEngine.canUseWebAudio) {
  39396. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39397. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39398. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39399. }
  39400. return this._byteFreqs;
  39401. };
  39402. Analyser.prototype.getByteTimeDomainData = function () {
  39403. if (this._audioEngine.canUseWebAudio) {
  39404. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39405. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39406. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39407. }
  39408. return this._byteTime;
  39409. };
  39410. Analyser.prototype.getFloatFrequencyData = function () {
  39411. if (this._audioEngine.canUseWebAudio) {
  39412. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39413. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39414. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39415. }
  39416. return this._floatFreqs;
  39417. };
  39418. Analyser.prototype.drawDebugCanvas = function () {
  39419. var _this = this;
  39420. if (this._audioEngine.canUseWebAudio) {
  39421. if (!this._debugCanvas) {
  39422. this._debugCanvas = document.createElement("canvas");
  39423. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39424. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39425. this._debugCanvas.style.position = "absolute";
  39426. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39427. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39428. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39429. document.body.appendChild(this._debugCanvas);
  39430. this._registerFunc = function () {
  39431. _this.drawDebugCanvas();
  39432. };
  39433. this._scene.registerBeforeRender(this._registerFunc);
  39434. }
  39435. if (this._registerFunc) {
  39436. var workingArray = this.getByteFrequencyData();
  39437. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39438. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39439. // Draw the frequency domain chart.
  39440. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39441. var value = workingArray[i];
  39442. var percent = value / this.BARGRAPHAMPLITUDE;
  39443. var height = this.DEBUGCANVASSIZE.height * percent;
  39444. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39445. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39446. var hue = i / this.getFrequencyBinCount() * 360;
  39447. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39448. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39449. }
  39450. }
  39451. }
  39452. };
  39453. Analyser.prototype.stopDebugCanvas = function () {
  39454. if (this._debugCanvas) {
  39455. this._scene.unregisterBeforeRender(this._registerFunc);
  39456. this._registerFunc = null;
  39457. document.body.removeChild(this._debugCanvas);
  39458. this._debugCanvas = null;
  39459. this._debugCanvasContext = null;
  39460. }
  39461. };
  39462. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39463. if (this._audioEngine.canUseWebAudio) {
  39464. inputAudioNode.connect(this._webAudioAnalyser);
  39465. this._webAudioAnalyser.connect(outputAudioNode);
  39466. }
  39467. };
  39468. Analyser.prototype.dispose = function () {
  39469. if (this._audioEngine.canUseWebAudio) {
  39470. this._webAudioAnalyser.disconnect();
  39471. }
  39472. };
  39473. return Analyser;
  39474. }());
  39475. BABYLON.Analyser = Analyser;
  39476. })(BABYLON || (BABYLON = {}));
  39477. var BABYLON;
  39478. (function (BABYLON) {
  39479. var DepthRenderer = (function () {
  39480. function DepthRenderer(scene, type) {
  39481. var _this = this;
  39482. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39483. this._viewMatrix = BABYLON.Matrix.Zero();
  39484. this._projectionMatrix = BABYLON.Matrix.Zero();
  39485. this._transformMatrix = BABYLON.Matrix.Zero();
  39486. this._worldViewProjection = BABYLON.Matrix.Zero();
  39487. this._scene = scene;
  39488. var engine = scene.getEngine();
  39489. // Render target
  39490. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39491. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39492. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39493. this._depthMap.refreshRate = 1;
  39494. this._depthMap.renderParticles = false;
  39495. this._depthMap.renderList = null;
  39496. // set default depth value to 1.0 (far away)
  39497. this._depthMap.onClear = function (engine) {
  39498. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39499. };
  39500. // Custom render function
  39501. var renderSubMesh = function (subMesh) {
  39502. var mesh = subMesh.getRenderingMesh();
  39503. var scene = _this._scene;
  39504. var engine = scene.getEngine();
  39505. // Culling
  39506. engine.setState(subMesh.getMaterial().backFaceCulling);
  39507. // Managing instances
  39508. var batch = mesh._getInstancesRenderList(subMesh._id);
  39509. if (batch.mustReturn) {
  39510. return;
  39511. }
  39512. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39513. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39514. engine.enableEffect(_this._effect);
  39515. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39516. var material = subMesh.getMaterial();
  39517. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39518. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39519. // Alpha test
  39520. if (material && material.needAlphaTesting()) {
  39521. var alphaTexture = material.getAlphaTestTexture();
  39522. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39523. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39524. }
  39525. // Bones
  39526. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39527. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39528. }
  39529. // Draw
  39530. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39531. }
  39532. };
  39533. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39534. var index;
  39535. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39536. renderSubMesh(opaqueSubMeshes.data[index]);
  39537. }
  39538. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39539. renderSubMesh(alphaTestSubMeshes.data[index]);
  39540. }
  39541. };
  39542. }
  39543. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39544. var material = subMesh.getMaterial();
  39545. if (material.disableDepthWrite) {
  39546. return false;
  39547. }
  39548. var defines = [];
  39549. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39550. var mesh = subMesh.getMesh();
  39551. var scene = mesh.getScene();
  39552. // Alpha test
  39553. if (material && material.needAlphaTesting()) {
  39554. defines.push("#define ALPHATEST");
  39555. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39556. attribs.push(BABYLON.VertexBuffer.UVKind);
  39557. defines.push("#define UV1");
  39558. }
  39559. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39560. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39561. defines.push("#define UV2");
  39562. }
  39563. }
  39564. // Bones
  39565. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39566. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39567. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39568. if (mesh.numBoneInfluencers > 4) {
  39569. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39570. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39571. }
  39572. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39573. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39574. }
  39575. else {
  39576. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39577. }
  39578. // Instances
  39579. if (useInstances) {
  39580. defines.push("#define INSTANCES");
  39581. attribs.push("world0");
  39582. attribs.push("world1");
  39583. attribs.push("world2");
  39584. attribs.push("world3");
  39585. }
  39586. // Get correct effect
  39587. var join = defines.join("\n");
  39588. if (this._cachedDefines !== join) {
  39589. this._cachedDefines = join;
  39590. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39591. }
  39592. return this._effect.isReady();
  39593. };
  39594. DepthRenderer.prototype.getDepthMap = function () {
  39595. return this._depthMap;
  39596. };
  39597. // Methods
  39598. DepthRenderer.prototype.dispose = function () {
  39599. this._depthMap.dispose();
  39600. };
  39601. return DepthRenderer;
  39602. }());
  39603. BABYLON.DepthRenderer = DepthRenderer;
  39604. })(BABYLON || (BABYLON = {}));
  39605. var BABYLON;
  39606. (function (BABYLON) {
  39607. var SSAORenderingPipeline = (function (_super) {
  39608. __extends(SSAORenderingPipeline, _super);
  39609. /**
  39610. * @constructor
  39611. * @param {string} name - The rendering pipeline name
  39612. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39613. * @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 }
  39614. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39615. */
  39616. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39617. var _this = this;
  39618. _super.call(this, scene.getEngine(), name);
  39619. // Members
  39620. /**
  39621. * The PassPostProcess id in the pipeline that contains the original scene color
  39622. * @type {string}
  39623. */
  39624. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39625. /**
  39626. * The SSAO PostProcess id in the pipeline
  39627. * @type {string}
  39628. */
  39629. this.SSAORenderEffect = "SSAORenderEffect";
  39630. /**
  39631. * The horizontal blur PostProcess id in the pipeline
  39632. * @type {string}
  39633. */
  39634. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39635. /**
  39636. * The vertical blur PostProcess id in the pipeline
  39637. * @type {string}
  39638. */
  39639. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39640. /**
  39641. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39642. * @type {string}
  39643. */
  39644. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39645. /**
  39646. * The output strength of the SSAO post-process. Default value is 1.0.
  39647. * @type {number}
  39648. */
  39649. this.totalStrength = 1.0;
  39650. /**
  39651. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39652. * @type {number}
  39653. */
  39654. this.radius = 0.0001;
  39655. /**
  39656. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39657. * Must not be equal to fallOff and superior to fallOff.
  39658. * Default value is 0.975
  39659. * @type {number}
  39660. */
  39661. this.area = 0.0075;
  39662. /**
  39663. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39664. * Must not be equal to area and inferior to area.
  39665. * Default value is 0.0
  39666. * @type {number}
  39667. */
  39668. this.fallOff = 0.000001;
  39669. /**
  39670. * The base color of the SSAO post-process
  39671. * The final result is "base + ssao" between [0, 1]
  39672. * @type {number}
  39673. */
  39674. this.base = 0.5;
  39675. this._firstUpdate = true;
  39676. this._scene = scene;
  39677. // Set up assets
  39678. this._createRandomTexture();
  39679. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39680. var ssaoRatio = ratio.ssaoRatio || ratio;
  39681. var combineRatio = ratio.combineRatio || ratio;
  39682. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39683. this._createSSAOPostProcess(ssaoRatio);
  39684. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39685. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39686. this._createSSAOCombinePostProcess(combineRatio);
  39687. // Set up pipeline
  39688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39690. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39691. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39693. // Finish
  39694. scene.postProcessRenderPipelineManager.addPipeline(this);
  39695. if (cameras)
  39696. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39697. }
  39698. // Public Methods
  39699. /**
  39700. * Returns the horizontal blur PostProcess
  39701. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39702. */
  39703. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39704. return this._blurHPostProcess;
  39705. };
  39706. /**
  39707. * Returns the vertical blur PostProcess
  39708. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39709. */
  39710. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39711. return this._blurVPostProcess;
  39712. };
  39713. /**
  39714. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39715. */
  39716. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39717. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39718. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39719. this._originalColorPostProcess = undefined;
  39720. this._ssaoPostProcess = undefined;
  39721. this._blurHPostProcess = undefined;
  39722. this._blurVPostProcess = undefined;
  39723. this._ssaoCombinePostProcess = undefined;
  39724. this._randomTexture.dispose();
  39725. if (disableDepthRender)
  39726. this._scene.disableDepthRenderer();
  39727. };
  39728. // Private Methods
  39729. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39730. var _this = this;
  39731. var numSamples = 16;
  39732. var sampleSphere = [
  39733. 0.5381, 0.1856, -0.4319,
  39734. 0.1379, 0.2486, 0.4430,
  39735. 0.3371, 0.5679, -0.0057,
  39736. -0.6999, -0.0451, -0.0019,
  39737. 0.0689, -0.1598, -0.8547,
  39738. 0.0560, 0.0069, -0.1843,
  39739. -0.0146, 0.1402, 0.0762,
  39740. 0.0100, -0.1924, -0.0344,
  39741. -0.3577, -0.5301, -0.4358,
  39742. -0.3169, 0.1063, 0.0158,
  39743. 0.0103, -0.5869, 0.0046,
  39744. -0.0897, -0.4940, 0.3287,
  39745. 0.7119, -0.0154, -0.0918,
  39746. -0.0533, 0.0596, -0.5411,
  39747. 0.0352, -0.0631, 0.5460,
  39748. -0.4776, 0.2847, -0.0271
  39749. ];
  39750. var samplesFactor = 1.0 / numSamples;
  39751. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39752. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39753. "area", "fallOff", "base"
  39754. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39755. this._ssaoPostProcess.onApply = function (effect) {
  39756. if (_this._firstUpdate) {
  39757. effect.setArray3("sampleSphere", sampleSphere);
  39758. effect.setFloat("samplesFactor", samplesFactor);
  39759. effect.setFloat("randTextureTiles", 4.0);
  39760. _this._firstUpdate = false;
  39761. }
  39762. effect.setFloat("totalStrength", _this.totalStrength);
  39763. effect.setFloat("radius", _this.radius);
  39764. effect.setFloat("area", _this.area);
  39765. effect.setFloat("fallOff", _this.fallOff);
  39766. effect.setFloat("base", _this.base);
  39767. effect.setTexture("textureSampler", _this._depthTexture);
  39768. effect.setTexture("randomSampler", _this._randomTexture);
  39769. };
  39770. };
  39771. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39772. var _this = this;
  39773. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39774. this._ssaoCombinePostProcess.onApply = function (effect) {
  39775. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39776. };
  39777. };
  39778. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39779. var size = 512;
  39780. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39781. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39782. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39783. var context = this._randomTexture.getContext();
  39784. var rand = function (min, max) {
  39785. return Math.random() * (max - min) + min;
  39786. };
  39787. var randVector = BABYLON.Vector3.Zero();
  39788. for (var x = 0; x < size; x++) {
  39789. for (var y = 0; y < size; y++) {
  39790. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39791. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39792. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39793. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39794. context.fillRect(x, y, 1, 1);
  39795. }
  39796. }
  39797. this._randomTexture.update(false);
  39798. };
  39799. return SSAORenderingPipeline;
  39800. }(BABYLON.PostProcessRenderPipeline));
  39801. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39802. })(BABYLON || (BABYLON = {}));
  39803. var BABYLON;
  39804. (function (BABYLON) {
  39805. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39806. var VolumetricLightScatteringPostProcess = (function (_super) {
  39807. __extends(VolumetricLightScatteringPostProcess, _super);
  39808. /**
  39809. * @constructor
  39810. * @param {string} name - The post-process name
  39811. * @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)
  39812. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39813. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  39814. * @param {number} samples - The post-process quality, default 100
  39815. * @param {number} samplingMode - The post-process filtering mode
  39816. * @param {BABYLON.Engine} engine - The babylon engine
  39817. * @param {boolean} reusable - If the post-process is reusable
  39818. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  39819. */
  39820. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  39821. var _this = this;
  39822. if (samples === void 0) { samples = 100; }
  39823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39824. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  39825. this._screenCoordinates = BABYLON.Vector2.Zero();
  39826. /**
  39827. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39828. * @type {Vector3}
  39829. */
  39830. this.customMeshPosition = BABYLON.Vector3.Zero();
  39831. /**
  39832. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  39833. * @type {boolean}
  39834. */
  39835. this.useCustomMeshPosition = false;
  39836. /**
  39837. * If the post-process should inverse the light scattering direction
  39838. * @type {boolean}
  39839. */
  39840. this.invert = true;
  39841. /**
  39842. * Array containing the excluded meshes not rendered in the internal pass
  39843. */
  39844. this.excludedMeshes = new Array();
  39845. /**
  39846. * Controls the overall intensity of the post-process
  39847. * @type {number}
  39848. */
  39849. this.exposure = 0.3;
  39850. /**
  39851. * Dissipates each sample's contribution in range [0, 1]
  39852. * @type {number}
  39853. */
  39854. this.decay = 0.96815;
  39855. /**
  39856. * Controls the overall intensity of each sample
  39857. * @type {number}
  39858. */
  39859. this.weight = 0.58767;
  39860. /**
  39861. * Controls the density of each sample
  39862. * @type {number}
  39863. */
  39864. this.density = 0.926;
  39865. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  39866. var engine = scene.getEngine();
  39867. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  39868. // Configure mesh
  39869. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  39870. // Configure
  39871. this._createPass(scene, ratio.passRatio || ratio);
  39872. this.onActivate = function (camera) {
  39873. if (!_this.isSupported) {
  39874. _this.dispose(camera);
  39875. }
  39876. _this.onActivate = null;
  39877. };
  39878. this.onApply = function (effect) {
  39879. _this._updateMeshScreenCoordinates(scene);
  39880. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  39881. effect.setFloat("exposure", _this.exposure);
  39882. effect.setFloat("decay", _this.decay);
  39883. effect.setFloat("weight", _this.weight);
  39884. effect.setFloat("density", _this.density);
  39885. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  39886. };
  39887. }
  39888. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  39889. get: function () {
  39890. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39891. return false;
  39892. },
  39893. set: function (useDiffuseColor) {
  39894. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39895. },
  39896. enumerable: true,
  39897. configurable: true
  39898. });
  39899. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  39900. var mesh = subMesh.getMesh();
  39901. // Render this.mesh as default
  39902. if (mesh === this.mesh) {
  39903. return mesh.material.isReady(mesh);
  39904. }
  39905. var defines = [];
  39906. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39907. var material = subMesh.getMaterial();
  39908. var needUV = false;
  39909. // Alpha test
  39910. if (material) {
  39911. if (material.needAlphaTesting()) {
  39912. defines.push("#define ALPHATEST");
  39913. }
  39914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39915. attribs.push(BABYLON.VertexBuffer.UVKind);
  39916. defines.push("#define UV1");
  39917. }
  39918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39919. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39920. defines.push("#define UV2");
  39921. }
  39922. }
  39923. // Bones
  39924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39927. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39928. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39929. }
  39930. else {
  39931. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39932. }
  39933. // Instances
  39934. if (useInstances) {
  39935. defines.push("#define INSTANCES");
  39936. attribs.push("world0");
  39937. attribs.push("world1");
  39938. attribs.push("world2");
  39939. attribs.push("world3");
  39940. }
  39941. // Get correct effect
  39942. var join = defines.join("\n");
  39943. if (this._cachedDefines !== join) {
  39944. this._cachedDefines = join;
  39945. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  39946. }
  39947. return this._volumetricLightScatteringPass.isReady();
  39948. };
  39949. /**
  39950. * Sets the new light position for light scattering effect
  39951. * @param {BABYLON.Vector3} The new custom light position
  39952. */
  39953. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  39954. this.customMeshPosition = position;
  39955. };
  39956. /**
  39957. * Returns the light position for light scattering effect
  39958. * @return {BABYLON.Vector3} The custom light position
  39959. */
  39960. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  39961. return this.customMeshPosition;
  39962. };
  39963. /**
  39964. * Disposes the internal assets and detaches the post-process from the camera
  39965. */
  39966. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  39967. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  39968. if (rttIndex !== -1) {
  39969. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  39970. }
  39971. this._volumetricLightScatteringRTT.dispose();
  39972. _super.prototype.dispose.call(this, camera);
  39973. };
  39974. /**
  39975. * Returns the render target texture used by the post-process
  39976. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  39977. */
  39978. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  39979. return this._volumetricLightScatteringRTT;
  39980. };
  39981. // Private methods
  39982. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  39983. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  39984. return true;
  39985. }
  39986. return false;
  39987. };
  39988. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  39989. var _this = this;
  39990. var engine = scene.getEngine();
  39991. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39992. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39993. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39994. this._volumetricLightScatteringRTT.renderList = null;
  39995. this._volumetricLightScatteringRTT.renderParticles = false;
  39996. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  39997. // Custom render function for submeshes
  39998. var renderSubMesh = function (subMesh) {
  39999. var mesh = subMesh.getRenderingMesh();
  40000. if (_this._meshExcluded(mesh)) {
  40001. return;
  40002. }
  40003. var scene = mesh.getScene();
  40004. var engine = scene.getEngine();
  40005. // Culling
  40006. engine.setState(subMesh.getMaterial().backFaceCulling);
  40007. // Managing instances
  40008. var batch = mesh._getInstancesRenderList(subMesh._id);
  40009. if (batch.mustReturn) {
  40010. return;
  40011. }
  40012. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40013. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40014. var effect = _this._volumetricLightScatteringPass;
  40015. if (mesh === _this.mesh) {
  40016. effect = subMesh.getMaterial().getEffect();
  40017. }
  40018. engine.enableEffect(effect);
  40019. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  40020. if (mesh === _this.mesh) {
  40021. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  40022. }
  40023. else {
  40024. var material = subMesh.getMaterial();
  40025. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  40026. // Alpha test
  40027. if (material && material.needAlphaTesting()) {
  40028. var alphaTexture = material.getAlphaTestTexture();
  40029. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40030. if (alphaTexture) {
  40031. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40032. }
  40033. }
  40034. // Bones
  40035. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40036. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40037. }
  40038. }
  40039. // Draw
  40040. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40041. }
  40042. };
  40043. // Render target texture callbacks
  40044. var savedSceneClearColor;
  40045. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40046. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40047. savedSceneClearColor = scene.clearColor;
  40048. scene.clearColor = sceneClearColor;
  40049. };
  40050. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40051. scene.clearColor = savedSceneClearColor;
  40052. };
  40053. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40054. var engine = scene.getEngine();
  40055. var index;
  40056. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40057. renderSubMesh(opaqueSubMeshes.data[index]);
  40058. }
  40059. engine.setAlphaTesting(true);
  40060. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40061. renderSubMesh(alphaTestSubMeshes.data[index]);
  40062. }
  40063. engine.setAlphaTesting(false);
  40064. if (transparentSubMeshes.length) {
  40065. // Sort sub meshes
  40066. for (index = 0; index < transparentSubMeshes.length; index++) {
  40067. var submesh = transparentSubMeshes.data[index];
  40068. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40069. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40070. }
  40071. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40072. sortedArray.sort(function (a, b) {
  40073. // Alpha index first
  40074. if (a._alphaIndex > b._alphaIndex) {
  40075. return 1;
  40076. }
  40077. if (a._alphaIndex < b._alphaIndex) {
  40078. return -1;
  40079. }
  40080. // Then distance to camera
  40081. if (a._distanceToCamera < b._distanceToCamera) {
  40082. return 1;
  40083. }
  40084. if (a._distanceToCamera > b._distanceToCamera) {
  40085. return -1;
  40086. }
  40087. return 0;
  40088. });
  40089. // Render sub meshes
  40090. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40091. for (index = 0; index < sortedArray.length; index++) {
  40092. renderSubMesh(sortedArray[index]);
  40093. }
  40094. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40095. }
  40096. };
  40097. };
  40098. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40099. var transform = scene.getTransformMatrix();
  40100. var meshPosition;
  40101. if (this.useCustomMeshPosition) {
  40102. meshPosition = this.customMeshPosition;
  40103. }
  40104. else if (this.attachedNode) {
  40105. meshPosition = this.attachedNode.position;
  40106. }
  40107. else {
  40108. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40109. }
  40110. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40111. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40112. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40113. if (this.invert)
  40114. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40115. };
  40116. // Static methods
  40117. /**
  40118. * Creates a default mesh for the Volumeric Light Scattering post-process
  40119. * @param {string} The mesh name
  40120. * @param {BABYLON.Scene} The scene where to create the mesh
  40121. * @return {BABYLON.Mesh} the default mesh
  40122. */
  40123. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40124. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40125. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40126. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40127. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40128. mesh.material = material;
  40129. return mesh;
  40130. };
  40131. __decorate([
  40132. BABYLON.serializeAsVector3()
  40133. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40134. __decorate([
  40135. BABYLON.serialize()
  40136. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40137. __decorate([
  40138. BABYLON.serialize()
  40139. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40140. __decorate([
  40141. BABYLON.serializeAsMeshReference()
  40142. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40143. __decorate([
  40144. BABYLON.serialize()
  40145. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40146. __decorate([
  40147. BABYLON.serialize()
  40148. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40149. __decorate([
  40150. BABYLON.serialize()
  40151. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40152. __decorate([
  40153. BABYLON.serialize()
  40154. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40155. __decorate([
  40156. BABYLON.serialize()
  40157. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40158. return VolumetricLightScatteringPostProcess;
  40159. }(BABYLON.PostProcess));
  40160. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40161. })(BABYLON || (BABYLON = {}));
  40162. // BABYLON.JS Chromatic Aberration GLSL Shader
  40163. // Author: Olivier Guyot
  40164. // Separates very slightly R, G and B colors on the edges of the screen
  40165. // Inspired by Francois Tarlier & Martins Upitis
  40166. var BABYLON;
  40167. (function (BABYLON) {
  40168. var LensRenderingPipeline = (function (_super) {
  40169. __extends(LensRenderingPipeline, _super);
  40170. /**
  40171. * @constructor
  40172. *
  40173. * Effect parameters are as follow:
  40174. * {
  40175. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40176. * edge_blur: number; // from 0 to x (1 for realism)
  40177. * distortion: number; // from 0 to x (1 for realism)
  40178. * grain_amount: number; // from 0 to 1
  40179. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40180. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40181. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40182. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40183. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40184. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40185. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40186. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40187. * }
  40188. * Note: if an effect parameter is unset, effect is disabled
  40189. *
  40190. * @param {string} name - The rendering pipeline name
  40191. * @param {object} parameters - An object containing all parameters (see above)
  40192. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40193. * @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)
  40194. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40195. */
  40196. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40197. var _this = this;
  40198. if (ratio === void 0) { ratio = 1.0; }
  40199. _super.call(this, scene.getEngine(), name);
  40200. // Lens effects can be of the following:
  40201. // - chromatic aberration (slight shift of RGB colors)
  40202. // - blur on the edge of the lens
  40203. // - lens distortion
  40204. // - depth-of-field blur & highlights enhancing
  40205. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40206. // - grain effect (noise or custom texture)
  40207. // Two additional texture samplers are needed:
  40208. // - depth map (for depth-of-field)
  40209. // - grain texture
  40210. /**
  40211. * The chromatic aberration PostProcess id in the pipeline
  40212. * @type {string}
  40213. */
  40214. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40215. /**
  40216. * The highlights enhancing PostProcess id in the pipeline
  40217. * @type {string}
  40218. */
  40219. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40220. /**
  40221. * The depth-of-field PostProcess id in the pipeline
  40222. * @type {string}
  40223. */
  40224. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40225. this._scene = scene;
  40226. // Fetch texture samplers
  40227. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40228. if (parameters.grain_texture) {
  40229. this._grainTexture = parameters.grain_texture;
  40230. }
  40231. else {
  40232. this._createGrainTexture();
  40233. }
  40234. // save parameters
  40235. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40236. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40237. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40238. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40239. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40240. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40241. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40242. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40243. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40244. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40245. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40246. // Create effects
  40247. this._createChromaticAberrationPostProcess(ratio);
  40248. this._createHighlightsPostProcess(ratio);
  40249. this._createDepthOfFieldPostProcess(ratio / 4);
  40250. // Set up pipeline
  40251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40252. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40254. if (this._highlightsGain === -1) {
  40255. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40256. }
  40257. // Finish
  40258. scene.postProcessRenderPipelineManager.addPipeline(this);
  40259. if (cameras) {
  40260. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40261. }
  40262. }
  40263. // public methods (self explanatory)
  40264. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40265. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40266. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40267. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40268. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40269. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40270. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40271. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40272. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40273. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40274. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40275. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40276. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40277. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40278. };
  40279. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40280. this._highlightsPostProcess.updateEffect();
  40281. };
  40282. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40283. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40284. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40285. this._highlightsGain = amount;
  40286. };
  40287. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40288. if (this._highlightsGain === -1) {
  40289. this._highlightsGain = 1.0;
  40290. }
  40291. this._highlightsThreshold = amount;
  40292. };
  40293. LensRenderingPipeline.prototype.disableHighlights = function () {
  40294. this._highlightsGain = -1;
  40295. };
  40296. /**
  40297. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40298. */
  40299. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40300. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40301. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40302. this._chromaticAberrationPostProcess = undefined;
  40303. this._highlightsPostProcess = undefined;
  40304. this._depthOfFieldPostProcess = undefined;
  40305. this._grainTexture.dispose();
  40306. if (disableDepthRender)
  40307. this._scene.disableDepthRenderer();
  40308. };
  40309. // colors shifting and distortion
  40310. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40311. var _this = this;
  40312. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40313. [], // samplers
  40314. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40315. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40316. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40317. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40318. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40319. };
  40320. };
  40321. // highlights enhancing
  40322. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40323. var _this = this;
  40324. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40325. [], // samplers
  40326. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40327. this._highlightsPostProcess.onApply = function (effect) {
  40328. effect.setFloat('gain', _this._highlightsGain);
  40329. effect.setFloat('threshold', _this._highlightsThreshold);
  40330. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40331. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40332. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40333. };
  40334. };
  40335. // colors shifting and distortion
  40336. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40337. var _this = this;
  40338. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40339. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40340. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40341. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40342. this._depthOfFieldPostProcess.onApply = function (effect) {
  40343. effect.setTexture("depthSampler", _this._depthTexture);
  40344. effect.setTexture("grainSampler", _this._grainTexture);
  40345. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40346. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40347. effect.setFloat('grain_amount', _this._grainAmount);
  40348. effect.setBool('blur_noise', _this._blurNoise);
  40349. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40350. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40351. effect.setFloat('distortion', _this._distortion);
  40352. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40353. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40354. effect.setFloat('aperture', _this._dofAperture);
  40355. effect.setFloat('darken', _this._dofDarken);
  40356. effect.setFloat('edge_blur', _this._edgeBlur);
  40357. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40358. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40359. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40360. };
  40361. };
  40362. // creates a black and white random noise texture, 512x512
  40363. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40364. var size = 512;
  40365. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40366. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40367. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40368. var context = this._grainTexture.getContext();
  40369. var rand = function (min, max) {
  40370. return Math.random() * (max - min) + min;
  40371. };
  40372. var value;
  40373. for (var x = 0; x < size; x++) {
  40374. for (var y = 0; y < size; y++) {
  40375. value = Math.floor(rand(0.42, 0.58) * 255);
  40376. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40377. context.fillRect(x, y, 1, 1);
  40378. }
  40379. }
  40380. this._grainTexture.update(false);
  40381. };
  40382. return LensRenderingPipeline;
  40383. }(BABYLON.PostProcessRenderPipeline));
  40384. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40385. })(BABYLON || (BABYLON = {}));
  40386. //
  40387. // This post-process allows the modification of rendered colors by using
  40388. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40389. //
  40390. // The object needs to be provided an url to a texture containing the color
  40391. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40392. // Use an image editing software to tweak the LUT to match your needs.
  40393. //
  40394. // For an example of a color LUT, see here:
  40395. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  40396. // For explanations on color grading, see here:
  40397. // http://udn.epicgames.com/Three/ColorGrading.html
  40398. //
  40399. var BABYLON;
  40400. (function (BABYLON) {
  40401. var ColorCorrectionPostProcess = (function (_super) {
  40402. __extends(ColorCorrectionPostProcess, _super);
  40403. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  40404. var _this = this;
  40405. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  40406. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  40407. this._colorTableTexture.anisotropicFilteringLevel = 1;
  40408. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40409. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40410. this.onApply = function (effect) {
  40411. effect.setTexture("colorTable", _this._colorTableTexture);
  40412. };
  40413. }
  40414. return ColorCorrectionPostProcess;
  40415. }(BABYLON.PostProcess));
  40416. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  40417. })(BABYLON || (BABYLON = {}));
  40418. var BABYLON;
  40419. (function (BABYLON) {
  40420. var AnaglyphFreeCamera = (function (_super) {
  40421. __extends(AnaglyphFreeCamera, _super);
  40422. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  40423. _super.call(this, name, position, scene);
  40424. this.interaxialDistance = interaxialDistance;
  40425. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40426. }
  40427. AnaglyphFreeCamera.prototype.getTypeName = function () {
  40428. return "AnaglyphFreeCamera";
  40429. };
  40430. return AnaglyphFreeCamera;
  40431. }(BABYLON.FreeCamera));
  40432. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  40433. var AnaglyphArcRotateCamera = (function (_super) {
  40434. __extends(AnaglyphArcRotateCamera, _super);
  40435. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  40436. _super.call(this, name, alpha, beta, radius, target, scene);
  40437. this.interaxialDistance = interaxialDistance;
  40438. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40439. }
  40440. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  40441. return "AnaglyphArcRotateCamera";
  40442. };
  40443. return AnaglyphArcRotateCamera;
  40444. }(BABYLON.ArcRotateCamera));
  40445. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  40446. var AnaglyphGamepadCamera = (function (_super) {
  40447. __extends(AnaglyphGamepadCamera, _super);
  40448. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  40449. _super.call(this, name, position, scene);
  40450. this.interaxialDistance = interaxialDistance;
  40451. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40452. }
  40453. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40454. return "AnaglyphGamepadCamera";
  40455. };
  40456. return AnaglyphGamepadCamera;
  40457. }(BABYLON.GamepadCamera));
  40458. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40459. var AnaglyphUniversalCamera = (function (_super) {
  40460. __extends(AnaglyphUniversalCamera, _super);
  40461. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40462. _super.call(this, name, position, scene);
  40463. this.interaxialDistance = interaxialDistance;
  40464. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40465. }
  40466. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40467. return "AnaglyphUniversalCamera";
  40468. };
  40469. return AnaglyphUniversalCamera;
  40470. }(BABYLON.UniversalCamera));
  40471. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40472. var StereoscopicFreeCamera = (function (_super) {
  40473. __extends(StereoscopicFreeCamera, _super);
  40474. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40475. _super.call(this, name, position, scene);
  40476. this.interaxialDistance = interaxialDistance;
  40477. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40478. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40479. }
  40480. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40481. return "StereoscopicFreeCamera";
  40482. };
  40483. return StereoscopicFreeCamera;
  40484. }(BABYLON.FreeCamera));
  40485. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40486. var StereoscopicArcRotateCamera = (function (_super) {
  40487. __extends(StereoscopicArcRotateCamera, _super);
  40488. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40489. _super.call(this, name, alpha, beta, radius, target, scene);
  40490. this.interaxialDistance = interaxialDistance;
  40491. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40492. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40493. }
  40494. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40495. return "StereoscopicArcRotateCamera";
  40496. };
  40497. return StereoscopicArcRotateCamera;
  40498. }(BABYLON.ArcRotateCamera));
  40499. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40500. var StereoscopicGamepadCamera = (function (_super) {
  40501. __extends(StereoscopicGamepadCamera, _super);
  40502. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40503. _super.call(this, name, position, scene);
  40504. this.interaxialDistance = interaxialDistance;
  40505. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40506. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40507. }
  40508. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40509. return "StereoscopicGamepadCamera";
  40510. };
  40511. return StereoscopicGamepadCamera;
  40512. }(BABYLON.GamepadCamera));
  40513. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40514. var StereoscopicUniversalCamera = (function (_super) {
  40515. __extends(StereoscopicUniversalCamera, _super);
  40516. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40517. _super.call(this, name, position, scene);
  40518. this.interaxialDistance = interaxialDistance;
  40519. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40520. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40521. }
  40522. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40523. return "StereoscopicUniversalCamera";
  40524. };
  40525. return StereoscopicUniversalCamera;
  40526. }(BABYLON.UniversalCamera));
  40527. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40528. })(BABYLON || (BABYLON = {}));
  40529. var BABYLON;
  40530. (function (BABYLON) {
  40531. var HDRRenderingPipeline = (function (_super) {
  40532. __extends(HDRRenderingPipeline, _super);
  40533. /**
  40534. * @constructor
  40535. * @param {string} name - The rendering pipeline name
  40536. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40537. * @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)
  40538. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40539. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40540. */
  40541. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40542. var _this = this;
  40543. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40544. _super.call(this, scene.getEngine(), name);
  40545. /**
  40546. * Public members
  40547. */
  40548. // Gaussian Blur
  40549. /**
  40550. * Gaussian blur coefficient
  40551. * @type {number}
  40552. */
  40553. this.gaussCoeff = 0.3;
  40554. /**
  40555. * Gaussian blur mean
  40556. * @type {number}
  40557. */
  40558. this.gaussMean = 1.0;
  40559. /**
  40560. * Gaussian blur standard deviation
  40561. * @type {number}
  40562. */
  40563. this.gaussStandDev = 0.8;
  40564. /**
  40565. * Gaussian blur multiplier. Multiplies the blur effect
  40566. * @type {number}
  40567. */
  40568. this.gaussMultiplier = 4.0;
  40569. // HDR
  40570. /**
  40571. * Exposure, controls the overall intensity of the pipeline
  40572. * @type {number}
  40573. */
  40574. this.exposure = 1.0;
  40575. /**
  40576. * Minimum luminance that the post-process can output. Luminance is >= 0
  40577. * @type {number}
  40578. */
  40579. this.minimumLuminance = 1.0;
  40580. /**
  40581. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40582. * @type {number}
  40583. */
  40584. this.maximumLuminance = 1e20;
  40585. /**
  40586. * Increase rate for luminance: eye adaptation speed to dark
  40587. * @type {number}
  40588. */
  40589. this.luminanceIncreaserate = 0.5;
  40590. /**
  40591. * Decrease rate for luminance: eye adaptation speed to bright
  40592. * @type {number}
  40593. */
  40594. this.luminanceDecreaseRate = 0.5;
  40595. // Bright pass
  40596. /**
  40597. * Minimum luminance needed to compute HDR
  40598. * @type {number}
  40599. */
  40600. this.brightThreshold = 0.8;
  40601. this._needUpdate = true;
  40602. this._scene = scene;
  40603. // Bright pass
  40604. this._createBrightPassPostProcess(scene, ratio);
  40605. // Down sample X4
  40606. this._createDownSampleX4PostProcess(scene, ratio);
  40607. // Create gaussian blur post-processes
  40608. this._createGaussianBlurPostProcess(scene, ratio);
  40609. // Texture adder
  40610. this._createTextureAdderPostProcess(scene, ratio);
  40611. // Luminance generator
  40612. this._createLuminanceGeneratorPostProcess(scene);
  40613. // HDR
  40614. this._createHDRPostProcess(scene, ratio);
  40615. // Pass postprocess
  40616. if (originalPostProcess === null) {
  40617. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40618. }
  40619. else {
  40620. this._originalPostProcess = originalPostProcess;
  40621. }
  40622. // Configure pipeline
  40623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40627. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40628. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40629. var addDownSamplerPostProcess = function (id) {
  40630. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40631. };
  40632. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40633. addDownSamplerPostProcess(i);
  40634. }
  40635. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40636. // Finish
  40637. scene.postProcessRenderPipelineManager.addPipeline(this);
  40638. if (cameras !== null) {
  40639. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40640. }
  40641. this.update();
  40642. }
  40643. /**
  40644. * Tells the pipeline to update its post-processes
  40645. */
  40646. HDRRenderingPipeline.prototype.update = function () {
  40647. this._needUpdate = true;
  40648. };
  40649. /**
  40650. * Returns the current calculated luminance
  40651. */
  40652. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40653. return this._hdrCurrentLuminance;
  40654. };
  40655. /**
  40656. * Returns the currently drawn luminance
  40657. */
  40658. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40659. return this._hdrOutputLuminance;
  40660. };
  40661. /**
  40662. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40663. */
  40664. HDRRenderingPipeline.prototype.dispose = function () {
  40665. this._originalPostProcess = undefined;
  40666. this._brightPassPostProcess = undefined;
  40667. this._downSampleX4PostProcess = undefined;
  40668. this._guassianBlurHPostProcess = undefined;
  40669. this._guassianBlurVPostProcess = undefined;
  40670. this._textureAdderPostProcess = undefined;
  40671. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40672. this._downSamplePostProcesses[i] = undefined;
  40673. }
  40674. this._hdrPostProcess = undefined;
  40675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40676. };
  40677. /**
  40678. * Creates the HDR post-process and computes the luminance adaptation
  40679. */
  40680. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40681. var _this = this;
  40682. var hdrLastLuminance = 0.0;
  40683. this._hdrOutputLuminance = -1.0;
  40684. this._hdrCurrentLuminance = 1.0;
  40685. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40686. this._hdrPostProcess.onApply = function (effect) {
  40687. if (_this._hdrOutputLuminance < 0.0) {
  40688. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40689. }
  40690. else {
  40691. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40692. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40693. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40694. }
  40695. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40696. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40697. }
  40698. else {
  40699. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40700. }
  40701. }
  40702. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40703. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40704. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40705. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40706. effect.setFloat("exposure", _this.exposure);
  40707. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40708. _this._needUpdate = false;
  40709. };
  40710. };
  40711. /**
  40712. * Texture Adder post-process
  40713. */
  40714. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40715. var _this = this;
  40716. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40717. this._textureAdderPostProcess.onApply = function (effect) {
  40718. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40719. };
  40720. };
  40721. /**
  40722. * Down sample X4 post-process
  40723. */
  40724. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40725. var _this = this;
  40726. var downSampleX4Offsets = new Array(32);
  40727. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40728. this._downSampleX4PostProcess.onApply = function (effect) {
  40729. if (_this._needUpdate) {
  40730. var id = 0;
  40731. for (var i = -2; i < 2; i++) {
  40732. for (var j = -2; j < 2; j++) {
  40733. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40734. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40735. id += 2;
  40736. }
  40737. }
  40738. }
  40739. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40740. };
  40741. };
  40742. /**
  40743. * Bright pass post-process
  40744. */
  40745. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40746. var _this = this;
  40747. var brightOffsets = new Array(8);
  40748. var brightPassCallback = function (effect) {
  40749. if (_this._needUpdate) {
  40750. var sU = (1.0 / _this._brightPassPostProcess.width);
  40751. var sV = (1.0 / _this._brightPassPostProcess.height);
  40752. brightOffsets[0] = -0.5 * sU;
  40753. brightOffsets[1] = 0.5 * sV;
  40754. brightOffsets[2] = 0.5 * sU;
  40755. brightOffsets[3] = 0.5 * sV;
  40756. brightOffsets[4] = -0.5 * sU;
  40757. brightOffsets[5] = -0.5 * sV;
  40758. brightOffsets[6] = 0.5 * sU;
  40759. brightOffsets[7] = -0.5 * sV;
  40760. }
  40761. effect.setArray2("dsOffsets", brightOffsets);
  40762. effect.setFloat("brightThreshold", _this.brightThreshold);
  40763. };
  40764. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40765. this._brightPassPostProcess.onApply = brightPassCallback;
  40766. };
  40767. /**
  40768. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40769. */
  40770. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40771. var _this = this;
  40772. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40773. var luminanceOffsets = new Array(8);
  40774. var downSampleOffsets = new Array(18);
  40775. var halfDestPixelSize;
  40776. this._downSamplePostProcesses = new Array(lumSteps);
  40777. // Utils for luminance
  40778. var luminanceUpdateSourceOffsets = function (width, height) {
  40779. var sU = (1.0 / width);
  40780. var sV = (1.0 / height);
  40781. luminanceOffsets[0] = -0.5 * sU;
  40782. luminanceOffsets[1] = 0.5 * sV;
  40783. luminanceOffsets[2] = 0.5 * sU;
  40784. luminanceOffsets[3] = 0.5 * sV;
  40785. luminanceOffsets[4] = -0.5 * sU;
  40786. luminanceOffsets[5] = -0.5 * sV;
  40787. luminanceOffsets[6] = 0.5 * sU;
  40788. luminanceOffsets[7] = -0.5 * sV;
  40789. };
  40790. var luminanceUpdateDestOffsets = function (width, height) {
  40791. var id = 0;
  40792. for (var x = -1; x < 2; x++) {
  40793. for (var y = -1; y < 2; y++) {
  40794. downSampleOffsets[id] = (x) / width;
  40795. downSampleOffsets[id + 1] = (y) / height;
  40796. id += 2;
  40797. }
  40798. }
  40799. };
  40800. // Luminance callback
  40801. var luminanceCallback = function (effect) {
  40802. if (_this._needUpdate) {
  40803. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40804. }
  40805. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40806. effect.setArray2("lumOffsets", luminanceOffsets);
  40807. };
  40808. // Down sample callbacks
  40809. var downSampleCallback = function (indice) {
  40810. var i = indice;
  40811. return function (effect) {
  40812. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40813. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40814. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  40815. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  40816. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  40817. effect.setArray2("dsOffsets", downSampleOffsets);
  40818. };
  40819. };
  40820. var downSampleAfterRenderCallback = function (effect) {
  40821. // Unpack result
  40822. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  40823. 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);
  40824. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  40825. };
  40826. // Create luminance post-process
  40827. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  40828. 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);
  40829. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  40830. // Create down sample post-processes
  40831. for (var i = lumSteps - 2; i >= 0; i--) {
  40832. var length = Math.pow(3, i);
  40833. ratio = { width: length, height: length };
  40834. var defines = "#define DOWN_SAMPLE\n";
  40835. if (i === 0) {
  40836. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  40837. }
  40838. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  40839. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  40840. if (i === 0) {
  40841. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  40842. }
  40843. }
  40844. };
  40845. /**
  40846. * Gaussian blur post-processes. Horizontal and Vertical
  40847. */
  40848. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  40849. var _this = this;
  40850. var blurOffsetsW = new Array(9);
  40851. var blurOffsetsH = new Array(9);
  40852. var blurWeights = new Array(9);
  40853. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  40854. // Utils for gaussian blur
  40855. var calculateBlurOffsets = function (height) {
  40856. var lastOutputDimensions = {
  40857. width: scene.getEngine().getRenderWidth(),
  40858. height: scene.getEngine().getRenderHeight()
  40859. };
  40860. for (var i = 0; i < 9; i++) {
  40861. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  40862. if (height) {
  40863. blurOffsetsH[i] = value;
  40864. }
  40865. else {
  40866. blurOffsetsW[i] = value;
  40867. }
  40868. }
  40869. };
  40870. var calculateWeights = function () {
  40871. var x = 0.0;
  40872. for (var i = 0; i < 9; i++) {
  40873. x = (i - 4.0) / 4.0;
  40874. 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));
  40875. }
  40876. };
  40877. // Callback
  40878. var gaussianBlurCallback = function (height) {
  40879. return function (effect) {
  40880. if (_this._needUpdate) {
  40881. calculateWeights();
  40882. calculateBlurOffsets(height);
  40883. }
  40884. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  40885. effect.setArray("blurWeights", blurWeights);
  40886. effect.setFloat("multiplier", _this.gaussMultiplier);
  40887. };
  40888. };
  40889. // Create horizontal gaussian blur post-processes
  40890. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  40891. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  40892. // Create vertical gaussian blur post-process
  40893. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  40894. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  40895. };
  40896. // Luminance generator
  40897. HDRRenderingPipeline.LUM_STEPS = 6;
  40898. return HDRRenderingPipeline;
  40899. }(BABYLON.PostProcessRenderPipeline));
  40900. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  40901. })(BABYLON || (BABYLON = {}));
  40902. var BABYLON;
  40903. (function (BABYLON) {
  40904. var FaceAdjacencies = (function () {
  40905. function FaceAdjacencies() {
  40906. this.edges = new Array();
  40907. this.edgesConnectedCount = 0;
  40908. }
  40909. return FaceAdjacencies;
  40910. }());
  40911. var EdgesRenderer = (function () {
  40912. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  40913. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  40914. if (epsilon === void 0) { epsilon = 0.95; }
  40915. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  40916. this.edgesWidthScalerForOrthographic = 1000.0;
  40917. this.edgesWidthScalerForPerspective = 50.0;
  40918. this._linesPositions = new Array();
  40919. this._linesNormals = new Array();
  40920. this._linesIndices = new Array();
  40921. this._buffers = new Array();
  40922. this._checkVerticesInsteadOfIndices = false;
  40923. this._source = source;
  40924. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  40925. this._epsilon = epsilon;
  40926. this._prepareRessources();
  40927. this._generateEdgesLines();
  40928. }
  40929. EdgesRenderer.prototype._prepareRessources = function () {
  40930. if (this._lineShader) {
  40931. return;
  40932. }
  40933. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  40934. attributes: ["position", "normal"],
  40935. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  40936. });
  40937. this._lineShader.disableDepthWrite = true;
  40938. this._lineShader.backFaceCulling = false;
  40939. };
  40940. EdgesRenderer.prototype.dispose = function () {
  40941. this._vb0.dispose();
  40942. this._vb1.dispose();
  40943. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  40944. this._lineShader.dispose();
  40945. };
  40946. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  40947. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  40948. return 0;
  40949. }
  40950. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  40951. return 1;
  40952. }
  40953. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  40954. return 2;
  40955. }
  40956. return -1;
  40957. };
  40958. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  40959. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  40960. return 0;
  40961. }
  40962. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  40963. return 1;
  40964. }
  40965. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  40966. return 2;
  40967. }
  40968. return -1;
  40969. };
  40970. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  40971. var needToCreateLine;
  40972. if (edge === undefined) {
  40973. needToCreateLine = true;
  40974. }
  40975. else {
  40976. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  40977. needToCreateLine = dotProduct < this._epsilon;
  40978. }
  40979. if (needToCreateLine) {
  40980. var offset = this._linesPositions.length / 3;
  40981. var normal = p0.subtract(p1);
  40982. normal.normalize();
  40983. // Positions
  40984. this._linesPositions.push(p0.x);
  40985. this._linesPositions.push(p0.y);
  40986. this._linesPositions.push(p0.z);
  40987. this._linesPositions.push(p0.x);
  40988. this._linesPositions.push(p0.y);
  40989. this._linesPositions.push(p0.z);
  40990. this._linesPositions.push(p1.x);
  40991. this._linesPositions.push(p1.y);
  40992. this._linesPositions.push(p1.z);
  40993. this._linesPositions.push(p1.x);
  40994. this._linesPositions.push(p1.y);
  40995. this._linesPositions.push(p1.z);
  40996. // Normals
  40997. this._linesNormals.push(p1.x);
  40998. this._linesNormals.push(p1.y);
  40999. this._linesNormals.push(p1.z);
  41000. this._linesNormals.push(-1);
  41001. this._linesNormals.push(p1.x);
  41002. this._linesNormals.push(p1.y);
  41003. this._linesNormals.push(p1.z);
  41004. this._linesNormals.push(1);
  41005. this._linesNormals.push(p0.x);
  41006. this._linesNormals.push(p0.y);
  41007. this._linesNormals.push(p0.z);
  41008. this._linesNormals.push(-1);
  41009. this._linesNormals.push(p0.x);
  41010. this._linesNormals.push(p0.y);
  41011. this._linesNormals.push(p0.z);
  41012. this._linesNormals.push(1);
  41013. // Indices
  41014. this._linesIndices.push(offset);
  41015. this._linesIndices.push(offset + 1);
  41016. this._linesIndices.push(offset + 2);
  41017. this._linesIndices.push(offset);
  41018. this._linesIndices.push(offset + 2);
  41019. this._linesIndices.push(offset + 3);
  41020. }
  41021. };
  41022. EdgesRenderer.prototype._generateEdgesLines = function () {
  41023. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41024. var indices = this._source.getIndices();
  41025. // First let's find adjacencies
  41026. var adjacencies = new Array();
  41027. var faceNormals = new Array();
  41028. var index;
  41029. var faceAdjacencies;
  41030. // Prepare faces
  41031. for (index = 0; index < indices.length; index += 3) {
  41032. faceAdjacencies = new FaceAdjacencies();
  41033. var p0Index = indices[index];
  41034. var p1Index = indices[index + 1];
  41035. var p2Index = indices[index + 2];
  41036. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41037. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41038. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41039. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41040. faceNormal.normalize();
  41041. faceNormals.push(faceNormal);
  41042. adjacencies.push(faceAdjacencies);
  41043. }
  41044. // Scan
  41045. for (index = 0; index < adjacencies.length; index++) {
  41046. faceAdjacencies = adjacencies[index];
  41047. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41048. var otherFaceAdjacencies = adjacencies[otherIndex];
  41049. if (faceAdjacencies.edgesConnectedCount === 3) {
  41050. break;
  41051. }
  41052. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41053. continue;
  41054. }
  41055. var otherP0 = indices[otherIndex * 3];
  41056. var otherP1 = indices[otherIndex * 3 + 1];
  41057. var otherP2 = indices[otherIndex * 3 + 2];
  41058. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41059. var otherEdgeIndex;
  41060. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41061. continue;
  41062. }
  41063. switch (edgeIndex) {
  41064. case 0:
  41065. if (this._checkVerticesInsteadOfIndices) {
  41066. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41067. }
  41068. else {
  41069. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41070. }
  41071. break;
  41072. case 1:
  41073. if (this._checkVerticesInsteadOfIndices) {
  41074. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41075. }
  41076. else {
  41077. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41078. }
  41079. break;
  41080. case 2:
  41081. if (this._checkVerticesInsteadOfIndices) {
  41082. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41083. }
  41084. else {
  41085. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41086. }
  41087. break;
  41088. }
  41089. if (otherEdgeIndex === -1) {
  41090. continue;
  41091. }
  41092. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41093. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41094. faceAdjacencies.edgesConnectedCount++;
  41095. otherFaceAdjacencies.edgesConnectedCount++;
  41096. if (faceAdjacencies.edgesConnectedCount === 3) {
  41097. break;
  41098. }
  41099. }
  41100. }
  41101. }
  41102. // Create lines
  41103. for (index = 0; index < adjacencies.length; index++) {
  41104. // 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
  41105. var current = adjacencies[index];
  41106. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41107. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41108. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41109. }
  41110. // Merge into a single mesh
  41111. var engine = this._source.getScene().getEngine();
  41112. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41113. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41114. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41115. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41116. this._ib = engine.createIndexBuffer(this._linesIndices);
  41117. this._indicesCount = this._linesIndices.length;
  41118. };
  41119. EdgesRenderer.prototype.render = function () {
  41120. if (!this._lineShader.isReady()) {
  41121. return;
  41122. }
  41123. var scene = this._source.getScene();
  41124. var engine = scene.getEngine();
  41125. this._lineShader._preBind();
  41126. // VBOs
  41127. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41128. scene.resetCachedMaterial();
  41129. this._lineShader.setColor4("color", this._source.edgesColor);
  41130. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41131. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41132. }
  41133. else {
  41134. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41135. }
  41136. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41137. this._lineShader.bind(this._source.getWorldMatrix());
  41138. // Draw order
  41139. engine.draw(true, 0, this._indicesCount);
  41140. this._lineShader.unbind();
  41141. engine.setDepthWrite(true);
  41142. };
  41143. return EdgesRenderer;
  41144. }());
  41145. BABYLON.EdgesRenderer = EdgesRenderer;
  41146. })(BABYLON || (BABYLON = {}));
  41147. var BABYLON;
  41148. (function (BABYLON) {
  41149. (function (TonemappingOperator) {
  41150. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41151. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41152. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41153. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41154. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41155. var TonemappingOperator = BABYLON.TonemappingOperator;
  41156. ;
  41157. var TonemapPostProcess = (function (_super) {
  41158. __extends(TonemapPostProcess, _super);
  41159. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41160. var _this = this;
  41161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41162. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41163. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41164. this._operator = _operator;
  41165. this.exposureAdjustment = exposureAdjustment;
  41166. var defines = "#define ";
  41167. if (this._operator === TonemappingOperator.Hable)
  41168. defines += "HABLE_TONEMAPPING";
  41169. else if (this._operator === TonemappingOperator.Reinhard)
  41170. defines += "REINHARD_TONEMAPPING";
  41171. else if (this._operator === TonemappingOperator.HejiDawson)
  41172. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41173. else if (this._operator === TonemappingOperator.Photographic)
  41174. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41175. //sadly a second call to create the effect.
  41176. this.updateEffect(defines);
  41177. this.onApply = function (effect) {
  41178. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41179. };
  41180. }
  41181. return TonemapPostProcess;
  41182. }(BABYLON.PostProcess));
  41183. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41184. })(BABYLON || (BABYLON = {}));
  41185. var BABYLON;
  41186. (function (BABYLON) {
  41187. var ReflectionProbe = (function () {
  41188. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41189. var _this = this;
  41190. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41191. this.name = name;
  41192. this._viewMatrix = BABYLON.Matrix.Identity();
  41193. this._target = BABYLON.Vector3.Zero();
  41194. this._add = BABYLON.Vector3.Zero();
  41195. this.position = BABYLON.Vector3.Zero();
  41196. this._scene = scene;
  41197. this._scene.reflectionProbes.push(this);
  41198. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41199. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41200. switch (faceIndex) {
  41201. case 0:
  41202. _this._add.copyFromFloats(1, 0, 0);
  41203. break;
  41204. case 1:
  41205. _this._add.copyFromFloats(-1, 0, 0);
  41206. break;
  41207. case 2:
  41208. _this._add.copyFromFloats(0, -1, 0);
  41209. break;
  41210. case 3:
  41211. _this._add.copyFromFloats(0, 1, 0);
  41212. break;
  41213. case 4:
  41214. _this._add.copyFromFloats(0, 0, 1);
  41215. break;
  41216. case 5:
  41217. _this._add.copyFromFloats(0, 0, -1);
  41218. break;
  41219. }
  41220. if (_this._attachedMesh) {
  41221. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41222. }
  41223. _this.position.addToRef(_this._add, _this._target);
  41224. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41225. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41226. };
  41227. this._renderTargetTexture.onAfterUnbind = function () {
  41228. scene.updateTransformMatrix(true);
  41229. };
  41230. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41231. }
  41232. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41233. get: function () {
  41234. return this._renderTargetTexture.refreshRate;
  41235. },
  41236. set: function (value) {
  41237. this._renderTargetTexture.refreshRate = value;
  41238. },
  41239. enumerable: true,
  41240. configurable: true
  41241. });
  41242. ReflectionProbe.prototype.getScene = function () {
  41243. return this._scene;
  41244. };
  41245. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41246. get: function () {
  41247. return this._renderTargetTexture;
  41248. },
  41249. enumerable: true,
  41250. configurable: true
  41251. });
  41252. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41253. get: function () {
  41254. return this._renderTargetTexture.renderList;
  41255. },
  41256. enumerable: true,
  41257. configurable: true
  41258. });
  41259. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41260. this._attachedMesh = mesh;
  41261. };
  41262. ReflectionProbe.prototype.dispose = function () {
  41263. var index = this._scene.reflectionProbes.indexOf(this);
  41264. if (index !== -1) {
  41265. // Remove from the scene if found
  41266. this._scene.reflectionProbes.splice(index, 1);
  41267. }
  41268. if (this._renderTargetTexture) {
  41269. this._renderTargetTexture.dispose();
  41270. this._renderTargetTexture = null;
  41271. }
  41272. };
  41273. return ReflectionProbe;
  41274. }());
  41275. BABYLON.ReflectionProbe = ReflectionProbe;
  41276. })(BABYLON || (BABYLON = {}));
  41277. var BABYLON;
  41278. (function (BABYLON) {
  41279. var SolidParticle = (function () {
  41280. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41281. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41282. this.position = BABYLON.Vector3.Zero(); // position
  41283. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41284. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41285. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41286. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41287. this.alive = true; // alive
  41288. this.idx = particleIndex;
  41289. this._pos = positionIndex;
  41290. this._model = model;
  41291. this.shapeId = shapeId;
  41292. this.idxInShape = idxInShape;
  41293. }
  41294. Object.defineProperty(SolidParticle.prototype, "scale", {
  41295. //legacy support, changed scale to scaling
  41296. get: function () {
  41297. return this.scaling;
  41298. },
  41299. set: function (scale) {
  41300. this.scaling = scale;
  41301. },
  41302. enumerable: true,
  41303. configurable: true
  41304. });
  41305. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41306. //legacy support, changed quaternion to rotationQuaternion
  41307. get: function () {
  41308. return this.rotationQuaternion;
  41309. },
  41310. set: function (q) {
  41311. this.rotationQuaternion = q;
  41312. },
  41313. enumerable: true,
  41314. configurable: true
  41315. });
  41316. return SolidParticle;
  41317. }());
  41318. BABYLON.SolidParticle = SolidParticle;
  41319. var ModelShape = (function () {
  41320. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41321. this.shapeID = id;
  41322. this._shape = shape;
  41323. this._shapeUV = shapeUV;
  41324. this._positionFunction = posFunction;
  41325. this._vertexFunction = vtxFunction;
  41326. }
  41327. return ModelShape;
  41328. }());
  41329. BABYLON.ModelShape = ModelShape;
  41330. })(BABYLON || (BABYLON = {}));
  41331. var BABYLON;
  41332. (function (BABYLON) {
  41333. /**
  41334. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41335. */
  41336. var SolidParticleSystem = (function () {
  41337. /**
  41338. * Creates a SPS (Solid Particle System) object.
  41339. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41340. * `scene` (Scene) is the scene in which the SPS is added.
  41341. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41342. * `isPickable` (default false) : if the solid particles must be pickable.
  41343. */
  41344. function SolidParticleSystem(name, scene, options) {
  41345. // public members
  41346. /**
  41347. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41348. * Example : var p = SPS.particles[i];
  41349. */
  41350. this.particles = new Array();
  41351. /**
  41352. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41353. */
  41354. this.nbParticles = 0;
  41355. /**
  41356. * If the particles must ever face the camera (default false). Useful for planar particles.
  41357. */
  41358. this.billboard = false;
  41359. /**
  41360. * This a counter ofr your own usage. It's not set by any SPS functions.
  41361. */
  41362. this.counter = 0;
  41363. /**
  41364. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41365. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41366. */
  41367. this.vars = {};
  41368. this._positions = new Array();
  41369. this._indices = new Array();
  41370. this._normals = new Array();
  41371. this._colors = new Array();
  41372. this._uvs = new Array();
  41373. this._index = 0; // indices index
  41374. this._updatable = true;
  41375. this._pickable = false;
  41376. this._isVisibilityBoxLocked = false;
  41377. this._alwaysVisible = false;
  41378. this._shapeCounter = 0;
  41379. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41380. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41381. this._computeParticleColor = true;
  41382. this._computeParticleTexture = true;
  41383. this._computeParticleRotation = true;
  41384. this._computeParticleVertex = false;
  41385. this._computeBoundingBox = false;
  41386. this._cam_axisZ = BABYLON.Vector3.Zero();
  41387. this._cam_axisY = BABYLON.Vector3.Zero();
  41388. this._cam_axisX = BABYLON.Vector3.Zero();
  41389. this._axisX = BABYLON.Axis.X;
  41390. this._axisY = BABYLON.Axis.Y;
  41391. this._axisZ = BABYLON.Axis.Z;
  41392. this._fakeCamPos = BABYLON.Vector3.Zero();
  41393. this._rotMatrix = new BABYLON.Matrix();
  41394. this._invertMatrix = new BABYLON.Matrix();
  41395. this._rotated = BABYLON.Vector3.Zero();
  41396. this._quaternion = new BABYLON.Quaternion();
  41397. this._vertex = BABYLON.Vector3.Zero();
  41398. this._normal = BABYLON.Vector3.Zero();
  41399. this._yaw = 0.0;
  41400. this._pitch = 0.0;
  41401. this._roll = 0.0;
  41402. this._halfroll = 0.0;
  41403. this._halfpitch = 0.0;
  41404. this._halfyaw = 0.0;
  41405. this._sinRoll = 0.0;
  41406. this._cosRoll = 0.0;
  41407. this._sinPitch = 0.0;
  41408. this._cosPitch = 0.0;
  41409. this._sinYaw = 0.0;
  41410. this._cosYaw = 0.0;
  41411. this._w = 0.0;
  41412. this._minimum = BABYLON.Tmp.Vector3[0];
  41413. this._maximum = BABYLON.Tmp.Vector3[1];
  41414. this.name = name;
  41415. this._scene = scene;
  41416. this._camera = scene.activeCamera;
  41417. this._pickable = options ? options.isPickable : false;
  41418. if (options && options.updatable) {
  41419. this._updatable = options.updatable;
  41420. }
  41421. else {
  41422. this._updatable = true;
  41423. }
  41424. if (this._pickable) {
  41425. this.pickedParticles = [];
  41426. }
  41427. }
  41428. /**
  41429. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41430. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41431. */
  41432. SolidParticleSystem.prototype.buildMesh = function () {
  41433. if (this.nbParticles === 0) {
  41434. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41435. this.addShape(triangle, 1);
  41436. triangle.dispose();
  41437. }
  41438. this._positions32 = new Float32Array(this._positions);
  41439. this._uvs32 = new Float32Array(this._uvs);
  41440. this._colors32 = new Float32Array(this._colors);
  41441. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41442. this._normals32 = new Float32Array(this._normals);
  41443. this._fixedNormal32 = new Float32Array(this._normals);
  41444. var vertexData = new BABYLON.VertexData();
  41445. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41446. vertexData.indices = this._indices;
  41447. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41448. if (this._uvs32) {
  41449. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41450. ;
  41451. }
  41452. if (this._colors32) {
  41453. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41454. }
  41455. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41456. vertexData.applyToMesh(mesh, this._updatable);
  41457. this.mesh = mesh;
  41458. this.mesh.isPickable = this._pickable;
  41459. // free memory
  41460. this._positions = null;
  41461. this._normals = null;
  41462. this._uvs = null;
  41463. this._colors = null;
  41464. if (!this._updatable) {
  41465. this.particles.length = 0;
  41466. }
  41467. return mesh;
  41468. };
  41469. /**
  41470. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41471. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41472. * Thus the particles generated from `digest()` have their property `position` set yet.
  41473. * `mesh` (`Mesh`) is the mesh to be digested
  41474. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41475. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41476. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41477. */
  41478. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41479. var size = (options && options.facetNb) || 1;
  41480. var number = (options && options.number);
  41481. var delta = (options && options.delta) || 0;
  41482. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41483. var meshInd = mesh.getIndices();
  41484. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41485. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41486. var f = 0; // facet counter
  41487. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41488. // compute size from number
  41489. if (number) {
  41490. number = (number > totalFacets) ? totalFacets : number;
  41491. size = Math.round(totalFacets / number);
  41492. delta = 0;
  41493. }
  41494. else {
  41495. size = (size > totalFacets) ? totalFacets : size;
  41496. }
  41497. var facetPos = []; // submesh positions
  41498. var facetInd = []; // submesh indices
  41499. var facetUV = []; // submesh UV
  41500. var facetCol = []; // submesh colors
  41501. var barycenter = BABYLON.Tmp.Vector3[0];
  41502. var rand;
  41503. var sizeO = size;
  41504. while (f < totalFacets) {
  41505. size = sizeO + Math.floor((1 + delta) * Math.random());
  41506. if (f > totalFacets - size) {
  41507. size = totalFacets - f;
  41508. }
  41509. // reset temp arrays
  41510. facetPos.length = 0;
  41511. facetInd.length = 0;
  41512. facetUV.length = 0;
  41513. facetCol.length = 0;
  41514. // iterate over "size" facets
  41515. var fi = 0;
  41516. for (var j = f * 3; j < (f + size) * 3; j++) {
  41517. facetInd.push(fi);
  41518. var i = meshInd[j];
  41519. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41520. if (meshUV) {
  41521. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41522. }
  41523. if (meshCol) {
  41524. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41525. }
  41526. fi++;
  41527. }
  41528. // create a model shape for each single particle
  41529. var idx = this.nbParticles;
  41530. var shape = this._posToShape(facetPos);
  41531. var shapeUV = this._uvsToShapeUV(facetUV);
  41532. // compute the barycenter of the shape
  41533. var v;
  41534. for (v = 0; v < shape.length; v++) {
  41535. barycenter.addInPlace(shape[v]);
  41536. }
  41537. barycenter.scaleInPlace(1 / shape.length);
  41538. // shift the shape from its barycenter to the origin
  41539. for (v = 0; v < shape.length; v++) {
  41540. shape[v].subtractInPlace(barycenter);
  41541. }
  41542. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41543. // add the particle in the SPS
  41544. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41545. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41546. // initialize the particle position
  41547. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41548. this._index += shape.length;
  41549. idx++;
  41550. this.nbParticles++;
  41551. this._shapeCounter++;
  41552. f += size;
  41553. }
  41554. return this;
  41555. };
  41556. //reset copy
  41557. SolidParticleSystem.prototype._resetCopy = function () {
  41558. this._copy.position.x = 0;
  41559. this._copy.position.y = 0;
  41560. this._copy.position.z = 0;
  41561. this._copy.rotation.x = 0;
  41562. this._copy.rotation.y = 0;
  41563. this._copy.rotation.z = 0;
  41564. this._copy.rotationQuaternion = null;
  41565. this._copy.scaling.x = 1;
  41566. this._copy.scaling.y = 1;
  41567. this._copy.scaling.z = 1;
  41568. this._copy.uvs.x = 0;
  41569. this._copy.uvs.y = 0;
  41570. this._copy.uvs.z = 1;
  41571. this._copy.uvs.w = 1;
  41572. this._copy.color = null;
  41573. };
  41574. // _meshBuilder : inserts the shape model in the global SPS mesh
  41575. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41576. var i;
  41577. var u = 0;
  41578. var c = 0;
  41579. this._resetCopy();
  41580. if (options && options.positionFunction) {
  41581. options.positionFunction(this._copy, idx, idxInShape);
  41582. }
  41583. if (this._copy.rotationQuaternion) {
  41584. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41585. }
  41586. else {
  41587. this._yaw = this._copy.rotation.y;
  41588. this._pitch = this._copy.rotation.x;
  41589. this._roll = this._copy.rotation.z;
  41590. this._quaternionRotationYPR();
  41591. }
  41592. this._quaternionToRotationMatrix();
  41593. for (i = 0; i < shape.length; i++) {
  41594. this._vertex.x = shape[i].x;
  41595. this._vertex.y = shape[i].y;
  41596. this._vertex.z = shape[i].z;
  41597. if (options && options.vertexFunction) {
  41598. options.vertexFunction(this._copy, this._vertex, i);
  41599. }
  41600. this._vertex.x *= this._copy.scaling.x;
  41601. this._vertex.y *= this._copy.scaling.y;
  41602. this._vertex.z *= this._copy.scaling.z;
  41603. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41604. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41605. if (meshUV) {
  41606. 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);
  41607. u += 2;
  41608. }
  41609. if (this._copy.color) {
  41610. this._color = this._copy.color;
  41611. }
  41612. else if (meshCol && meshCol[c]) {
  41613. this._color.r = meshCol[c];
  41614. this._color.g = meshCol[c + 1];
  41615. this._color.b = meshCol[c + 2];
  41616. this._color.a = meshCol[c + 3];
  41617. }
  41618. else {
  41619. this._color.r = 1;
  41620. this._color.g = 1;
  41621. this._color.b = 1;
  41622. this._color.a = 1;
  41623. }
  41624. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41625. c += 4;
  41626. }
  41627. for (i = 0; i < meshInd.length; i++) {
  41628. indices.push(p + meshInd[i]);
  41629. }
  41630. if (this._pickable) {
  41631. var nbfaces = meshInd.length / 3;
  41632. for (i = 0; i < nbfaces; i++) {
  41633. this.pickedParticles.push({ idx: idx, faceId: i });
  41634. }
  41635. }
  41636. };
  41637. // returns a shape array from positions array
  41638. SolidParticleSystem.prototype._posToShape = function (positions) {
  41639. var shape = [];
  41640. for (var i = 0; i < positions.length; i += 3) {
  41641. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41642. }
  41643. return shape;
  41644. };
  41645. // returns a shapeUV array from a Vector4 uvs
  41646. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41647. var shapeUV = [];
  41648. if (uvs) {
  41649. for (var i = 0; i < uvs.length; i++)
  41650. shapeUV.push(uvs[i]);
  41651. }
  41652. return shapeUV;
  41653. };
  41654. // adds a new particle object in the particles array
  41655. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41656. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41657. };
  41658. /**
  41659. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41660. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41661. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41662. * `nb` (positive integer) the number of particles to be created from this model
  41663. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41664. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41665. */
  41666. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41667. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41668. var meshInd = mesh.getIndices();
  41669. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41670. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41671. var shape = this._posToShape(meshPos);
  41672. var shapeUV = this._uvsToShapeUV(meshUV);
  41673. var posfunc = options ? options.positionFunction : null;
  41674. var vtxfunc = options ? options.vertexFunction : null;
  41675. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41676. // particles
  41677. var idx = this.nbParticles;
  41678. for (var i = 0; i < nb; i++) {
  41679. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41680. if (this._updatable) {
  41681. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41682. }
  41683. this._index += shape.length;
  41684. idx++;
  41685. }
  41686. this.nbParticles += nb;
  41687. this._shapeCounter++;
  41688. return this._shapeCounter - 1;
  41689. };
  41690. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41691. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41692. this._resetCopy();
  41693. if (particle._model._positionFunction) {
  41694. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41695. }
  41696. if (this._copy.rotationQuaternion) {
  41697. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41698. }
  41699. else {
  41700. this._yaw = this._copy.rotation.y;
  41701. this._pitch = this._copy.rotation.x;
  41702. this._roll = this._copy.rotation.z;
  41703. this._quaternionRotationYPR();
  41704. }
  41705. this._quaternionToRotationMatrix();
  41706. this._shape = particle._model._shape;
  41707. for (var pt = 0; pt < this._shape.length; pt++) {
  41708. this._vertex.x = this._shape[pt].x;
  41709. this._vertex.y = this._shape[pt].y;
  41710. this._vertex.z = this._shape[pt].z;
  41711. if (particle._model._vertexFunction) {
  41712. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41713. }
  41714. this._vertex.x *= this._copy.scaling.x;
  41715. this._vertex.y *= this._copy.scaling.y;
  41716. this._vertex.z *= this._copy.scaling.z;
  41717. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41718. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41719. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41720. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41721. }
  41722. particle.position.x = 0;
  41723. particle.position.y = 0;
  41724. particle.position.z = 0;
  41725. particle.rotation.x = 0;
  41726. particle.rotation.y = 0;
  41727. particle.rotation.z = 0;
  41728. particle.rotationQuaternion = null;
  41729. particle.scaling.x = 1;
  41730. particle.scaling.y = 1;
  41731. particle.scaling.z = 1;
  41732. };
  41733. /**
  41734. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41735. */
  41736. SolidParticleSystem.prototype.rebuildMesh = function () {
  41737. for (var p = 0; p < this.particles.length; p++) {
  41738. this._rebuildParticle(this.particles[p]);
  41739. }
  41740. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41741. };
  41742. /**
  41743. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41744. * This method calls `updateParticle()` for each particle of the SPS.
  41745. * For an animated SPS, it is usually called within the render loop.
  41746. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41747. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41748. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41749. */
  41750. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41751. if (start === void 0) { start = 0; }
  41752. if (end === void 0) { end = this.nbParticles - 1; }
  41753. if (update === void 0) { update = true; }
  41754. if (!this._updatable) {
  41755. return;
  41756. }
  41757. // custom beforeUpdate
  41758. this.beforeUpdateParticles(start, end, update);
  41759. this._cam_axisX.x = 1;
  41760. this._cam_axisX.y = 0;
  41761. this._cam_axisX.z = 0;
  41762. this._cam_axisY.x = 0;
  41763. this._cam_axisY.y = 1;
  41764. this._cam_axisY.z = 0;
  41765. this._cam_axisZ.x = 0;
  41766. this._cam_axisZ.y = 0;
  41767. this._cam_axisZ.z = 1;
  41768. // if the particles will always face the camera
  41769. if (this.billboard) {
  41770. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41771. this._yaw = this.mesh.rotation.y;
  41772. this._pitch = this.mesh.rotation.x;
  41773. this._roll = this.mesh.rotation.z;
  41774. this._quaternionRotationYPR();
  41775. this._quaternionToRotationMatrix();
  41776. this._rotMatrix.invertToRef(this._invertMatrix);
  41777. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41778. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41779. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41780. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41781. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41782. this._cam_axisY.normalize();
  41783. this._cam_axisX.normalize();
  41784. this._cam_axisZ.normalize();
  41785. }
  41786. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41787. var idx = 0;
  41788. var index = 0;
  41789. var colidx = 0;
  41790. var colorIndex = 0;
  41791. var uvidx = 0;
  41792. var uvIndex = 0;
  41793. if (this._computeBoundingBox) {
  41794. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41795. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41796. }
  41797. // particle loop
  41798. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41799. for (var p = start; p <= end; p++) {
  41800. this._particle = this.particles[p];
  41801. this._shape = this._particle._model._shape;
  41802. this._shapeUV = this._particle._model._shapeUV;
  41803. // call to custom user function to update the particle properties
  41804. this.updateParticle(this._particle);
  41805. // particle rotation matrix
  41806. if (this.billboard) {
  41807. this._particle.rotation.x = 0.0;
  41808. this._particle.rotation.y = 0.0;
  41809. }
  41810. if (this._computeParticleRotation) {
  41811. if (this._particle.rotationQuaternion) {
  41812. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41813. }
  41814. else {
  41815. this._yaw = this._particle.rotation.y;
  41816. this._pitch = this._particle.rotation.x;
  41817. this._roll = this._particle.rotation.z;
  41818. this._quaternionRotationYPR();
  41819. }
  41820. this._quaternionToRotationMatrix();
  41821. }
  41822. for (var pt = 0; pt < this._shape.length; pt++) {
  41823. idx = index + pt * 3;
  41824. colidx = colorIndex + pt * 4;
  41825. uvidx = uvIndex + pt * 2;
  41826. this._vertex.x = this._shape[pt].x;
  41827. this._vertex.y = this._shape[pt].y;
  41828. this._vertex.z = this._shape[pt].z;
  41829. if (this._computeParticleVertex) {
  41830. this.updateParticleVertex(this._particle, this._vertex, pt);
  41831. }
  41832. // positions
  41833. this._vertex.x *= this._particle.scaling.x;
  41834. this._vertex.y *= this._particle.scaling.y;
  41835. this._vertex.z *= this._particle.scaling.z;
  41836. 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];
  41837. 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;
  41838. 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;
  41839. 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;
  41840. 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;
  41841. 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;
  41842. 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;
  41843. if (this._computeBoundingBox) {
  41844. if (this._positions32[idx] < this._minimum.x) {
  41845. this._minimum.x = this._positions32[idx];
  41846. }
  41847. if (this._positions32[idx] > this._maximum.x) {
  41848. this._maximum.x = this._positions32[idx];
  41849. }
  41850. if (this._positions32[idx + 1] < this._minimum.y) {
  41851. this._minimum.y = this._positions32[idx + 1];
  41852. }
  41853. if (this._positions32[idx + 1] > this._maximum.y) {
  41854. this._maximum.y = this._positions32[idx + 1];
  41855. }
  41856. if (this._positions32[idx + 2] < this._minimum.z) {
  41857. this._minimum.z = this._positions32[idx + 2];
  41858. }
  41859. if (this._positions32[idx + 2] > this._maximum.z) {
  41860. this._maximum.z = this._positions32[idx + 2];
  41861. }
  41862. }
  41863. // normals : if the particles can't be morphed then just rotate the normals
  41864. if (!this._computeParticleVertex && !this.billboard) {
  41865. this._normal.x = this._fixedNormal32[idx];
  41866. this._normal.y = this._fixedNormal32[idx + 1];
  41867. this._normal.z = this._fixedNormal32[idx + 2];
  41868. 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];
  41869. 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;
  41870. 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;
  41871. 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;
  41872. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41873. 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;
  41874. 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;
  41875. }
  41876. if (this._computeParticleColor) {
  41877. this._colors32[colidx] = this._particle.color.r;
  41878. this._colors32[colidx + 1] = this._particle.color.g;
  41879. this._colors32[colidx + 2] = this._particle.color.b;
  41880. this._colors32[colidx + 3] = this._particle.color.a;
  41881. }
  41882. if (this._computeParticleTexture) {
  41883. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41884. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41885. }
  41886. }
  41887. index = idx + 3;
  41888. colorIndex = colidx + 4;
  41889. uvIndex = uvidx + 2;
  41890. }
  41891. if (update) {
  41892. if (this._computeParticleColor) {
  41893. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41894. }
  41895. if (this._computeParticleTexture) {
  41896. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41897. }
  41898. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41899. if (!this.mesh.areNormalsFrozen) {
  41900. if (this._computeParticleVertex || this.billboard) {
  41901. // recompute the normals only if the particles can be morphed, update then the normal reference array
  41902. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  41903. for (var i = 0; i < this._normals32.length; i++) {
  41904. this._fixedNormal32[i] = this._normals32[i];
  41905. }
  41906. }
  41907. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41908. }
  41909. }
  41910. if (this._computeBoundingBox) {
  41911. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41912. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41913. }
  41914. this.afterUpdateParticles(start, end, update);
  41915. };
  41916. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41917. this._halfroll = this._roll * 0.5;
  41918. this._halfpitch = this._pitch * 0.5;
  41919. this._halfyaw = this._yaw * 0.5;
  41920. this._sinRoll = Math.sin(this._halfroll);
  41921. this._cosRoll = Math.cos(this._halfroll);
  41922. this._sinPitch = Math.sin(this._halfpitch);
  41923. this._cosPitch = Math.cos(this._halfpitch);
  41924. this._sinYaw = Math.sin(this._halfyaw);
  41925. this._cosYaw = Math.cos(this._halfyaw);
  41926. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41927. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41928. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41929. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41930. };
  41931. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41932. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41933. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41934. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41935. this._rotMatrix.m[3] = 0;
  41936. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41937. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41938. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41939. this._rotMatrix.m[7] = 0;
  41940. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41941. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41942. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41943. this._rotMatrix.m[11] = 0;
  41944. this._rotMatrix.m[12] = 0;
  41945. this._rotMatrix.m[13] = 0;
  41946. this._rotMatrix.m[14] = 0;
  41947. this._rotMatrix.m[15] = 1.0;
  41948. };
  41949. /**
  41950. * Disposes the SPS
  41951. */
  41952. SolidParticleSystem.prototype.dispose = function () {
  41953. this.mesh.dispose();
  41954. this.vars = null;
  41955. // drop references to internal big arrays for the GC
  41956. this._positions = null;
  41957. this._indices = null;
  41958. this._normals = null;
  41959. this._uvs = null;
  41960. this._colors = null;
  41961. this._positions32 = null;
  41962. this._normals32 = null;
  41963. this._fixedNormal32 = null;
  41964. this._uvs32 = null;
  41965. this._colors32 = null;
  41966. this.pickedParticles = null;
  41967. };
  41968. /**
  41969. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41970. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41971. */
  41972. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41973. if (!this._isVisibilityBoxLocked) {
  41974. this.mesh.refreshBoundingInfo();
  41975. }
  41976. };
  41977. /**
  41978. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41979. * @param size the size (float) of the visibility box
  41980. * note : this doesn't lock the SPS mesh bounding box.
  41981. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41982. */
  41983. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41984. var vis = size / 2;
  41985. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41986. };
  41987. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41988. // getter and setter
  41989. get: function () {
  41990. return this._alwaysVisible;
  41991. },
  41992. /**
  41993. * Sets the SPS as always visible or not
  41994. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  41995. */
  41996. set: function (val) {
  41997. this._alwaysVisible = val;
  41998. this.mesh.alwaysSelectAsActiveMesh = val;
  41999. },
  42000. enumerable: true,
  42001. configurable: true
  42002. });
  42003. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42004. get: function () {
  42005. return this._isVisibilityBoxLocked;
  42006. },
  42007. /**
  42008. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42009. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42010. */
  42011. set: function (val) {
  42012. this._isVisibilityBoxLocked = val;
  42013. this.mesh.getBoundingInfo().isLocked = val;
  42014. },
  42015. enumerable: true,
  42016. configurable: true
  42017. });
  42018. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42019. // getters
  42020. get: function () {
  42021. return this._computeParticleRotation;
  42022. },
  42023. // Optimizer setters
  42024. /**
  42025. * Tells to `setParticles()` to compute the particle rotations or not.
  42026. * Default value : true. The SPS is faster when it's set to false.
  42027. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42028. */
  42029. set: function (val) {
  42030. this._computeParticleRotation = val;
  42031. },
  42032. enumerable: true,
  42033. configurable: true
  42034. });
  42035. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42036. get: function () {
  42037. return this._computeParticleColor;
  42038. },
  42039. /**
  42040. * Tells to `setParticles()` to compute the particle colors or not.
  42041. * Default value : true. The SPS is faster when it's set to false.
  42042. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42043. */
  42044. set: function (val) {
  42045. this._computeParticleColor = val;
  42046. },
  42047. enumerable: true,
  42048. configurable: true
  42049. });
  42050. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42051. get: function () {
  42052. return this._computeParticleTexture;
  42053. },
  42054. /**
  42055. * Tells to `setParticles()` to compute the particle textures or not.
  42056. * Default value : true. The SPS is faster when it's set to false.
  42057. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42058. */
  42059. set: function (val) {
  42060. this._computeParticleTexture = val;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42066. get: function () {
  42067. return this._computeParticleVertex;
  42068. },
  42069. /**
  42070. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42071. * Default value : false. The SPS is faster when it's set to false.
  42072. * Note : the particle custom vertex positions aren't stored values.
  42073. */
  42074. set: function (val) {
  42075. this._computeParticleVertex = val;
  42076. },
  42077. enumerable: true,
  42078. configurable: true
  42079. });
  42080. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42081. get: function () {
  42082. return this._computeBoundingBox;
  42083. },
  42084. /**
  42085. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42086. */
  42087. set: function (val) {
  42088. this._computeBoundingBox = val;
  42089. },
  42090. enumerable: true,
  42091. configurable: true
  42092. });
  42093. // =======================================================================
  42094. // Particle behavior logic
  42095. // these following methods may be overwritten by the user to fit his needs
  42096. /**
  42097. * This function does nothing. It may be overwritten to set all the particle first values.
  42098. * The SPS doesn't call this function, you may have to call it by your own.
  42099. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42100. */
  42101. SolidParticleSystem.prototype.initParticles = function () {
  42102. };
  42103. /**
  42104. * This function does nothing. It may be overwritten to recycle a particle.
  42105. * The SPS doesn't call this function, you may have to call it by your own.
  42106. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42107. */
  42108. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42109. return particle;
  42110. };
  42111. /**
  42112. * Updates a particle : this function should be overwritten by the user.
  42113. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42114. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42115. * ex : just set a particle position or velocity and recycle conditions
  42116. */
  42117. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42118. return particle;
  42119. };
  42120. /**
  42121. * Updates a vertex of a particle : it can be overwritten by the user.
  42122. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42123. * @param particle the current particle
  42124. * @param vertex the current index of the current particle
  42125. * @param pt the index of the current vertex in the particle shape
  42126. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42127. * ex : just set a vertex particle position
  42128. */
  42129. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42130. return vertex;
  42131. };
  42132. /**
  42133. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42134. * This does nothing and may be overwritten by the user.
  42135. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42136. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42137. * @param update the boolean update value actually passed to setParticles()
  42138. */
  42139. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42140. };
  42141. /**
  42142. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42143. * This will be passed three parameters.
  42144. * This does nothing and may be overwritten by the user.
  42145. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42146. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42147. * @param update the boolean update value actually passed to setParticles()
  42148. */
  42149. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42150. };
  42151. return SolidParticleSystem;
  42152. }());
  42153. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42154. })(BABYLON || (BABYLON = {}));
  42155. var BABYLON;
  42156. (function (BABYLON) {
  42157. var Internals;
  42158. (function (Internals) {
  42159. var FileFaceOrientation = (function () {
  42160. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42161. this.name = name;
  42162. this.worldAxisForNormal = worldAxisForNormal;
  42163. this.worldAxisForFileX = worldAxisForFileX;
  42164. this.worldAxisForFileY = worldAxisForFileY;
  42165. }
  42166. return FileFaceOrientation;
  42167. }());
  42168. ;
  42169. /**
  42170. * Helper class dealing with the extraction of spherical polynomial dataArray
  42171. * from a cube map.
  42172. */
  42173. var CubeMapToSphericalPolynomialTools = (function () {
  42174. function CubeMapToSphericalPolynomialTools() {
  42175. }
  42176. /**
  42177. * Converts a cubemap to the according Spherical Polynomial data.
  42178. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42179. *
  42180. * @param cubeInfo The Cube map to extract the information from.
  42181. * @return The Spherical Polynomial data.
  42182. */
  42183. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42184. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42185. var totalSolidAngle = 0.0;
  42186. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42187. var du = 2.0 / cubeInfo.size;
  42188. var dv = du;
  42189. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42190. var minUV = du * 0.5 - 1.0;
  42191. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42192. var fileFace = this.FileFaces[faceIndex];
  42193. var dataArray = cubeInfo[fileFace.name];
  42194. var v = minUV;
  42195. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42196. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42197. // Because SP is still linear, so summation is fine in that basis.
  42198. for (var y = 0; y < cubeInfo.size; y++) {
  42199. var u = minUV;
  42200. for (var x = 0; x < cubeInfo.size; x++) {
  42201. // World direction (not normalised)
  42202. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42203. worldDirection.normalize();
  42204. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42205. if (1) {
  42206. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42207. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42208. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42209. var color = new BABYLON.Color3(r, g, b);
  42210. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42211. }
  42212. else {
  42213. if (faceIndex == 0) {
  42214. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42215. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42216. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42217. }
  42218. else if (faceIndex == 1) {
  42219. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42220. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42221. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42222. }
  42223. else if (faceIndex == 2) {
  42224. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42225. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42226. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42227. }
  42228. else if (faceIndex == 3) {
  42229. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42230. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42231. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42232. }
  42233. else if (faceIndex == 4) {
  42234. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42235. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42236. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42237. }
  42238. else if (faceIndex == 5) {
  42239. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42240. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42241. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42242. }
  42243. 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]);
  42244. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42245. }
  42246. totalSolidAngle += deltaSolidAngle;
  42247. u += du;
  42248. }
  42249. v += dv;
  42250. }
  42251. }
  42252. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42253. var correction = correctSolidAngle / totalSolidAngle;
  42254. sphericalHarmonics.scale(correction);
  42255. // Additionally scale by pi -- audit needed
  42256. sphericalHarmonics.scale(1.0 / Math.PI);
  42257. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42258. };
  42259. CubeMapToSphericalPolynomialTools.FileFaces = [
  42260. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42261. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42262. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42263. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42264. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42265. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42266. ];
  42267. return CubeMapToSphericalPolynomialTools;
  42268. }());
  42269. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42270. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42271. })(BABYLON || (BABYLON = {}));
  42272. var BABYLON;
  42273. (function (BABYLON) {
  42274. var Internals;
  42275. (function (Internals) {
  42276. /**
  42277. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42278. */
  42279. var PanoramaToCubeMapTools = (function () {
  42280. function PanoramaToCubeMapTools() {
  42281. }
  42282. /**
  42283. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42284. *
  42285. * @param float32Array The source data.
  42286. * @param inputWidth The width of the input panorama.
  42287. * @param inputhHeight The height of the input panorama.
  42288. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42289. * @return The cubemap data
  42290. */
  42291. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42292. if (!float32Array) {
  42293. throw "ConvertPanoramaToCubemap: input cannot be null";
  42294. }
  42295. if (float32Array.length != inputWidth * inputHeight * 3) {
  42296. throw "ConvertPanoramaToCubemap: input size is wrong";
  42297. }
  42298. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42299. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42300. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42301. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42302. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42303. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42304. return {
  42305. front: textureFront,
  42306. back: textureBack,
  42307. left: textureLeft,
  42308. right: textureRight,
  42309. up: textureUp,
  42310. down: textureDown,
  42311. size: size
  42312. };
  42313. };
  42314. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42315. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42316. var textureArray = new Float32Array(buffer);
  42317. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42318. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42319. var dy = 1 / texSize;
  42320. var fy = 0;
  42321. for (var y = 0; y < texSize; y++) {
  42322. var xv1 = faceData[0];
  42323. var xv2 = faceData[2];
  42324. for (var x = 0; x < texSize; x++) {
  42325. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42326. v.normalize();
  42327. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42328. // 3 channels per pixels
  42329. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42330. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42331. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42332. xv1 = xv1.add(rotDX1);
  42333. xv2 = xv2.add(rotDX2);
  42334. }
  42335. fy += dy;
  42336. }
  42337. return textureArray;
  42338. };
  42339. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42340. var theta = Math.atan2(vDir.z, vDir.x);
  42341. var phi = Math.acos(vDir.y);
  42342. while (theta < -Math.PI)
  42343. theta += 2 * Math.PI;
  42344. while (theta > Math.PI)
  42345. theta -= 2 * Math.PI;
  42346. var dx = theta / Math.PI;
  42347. var dy = phi / Math.PI;
  42348. // recenter.
  42349. dx = dx * 0.5 + 0.5;
  42350. var px = Math.round(dx * inputWidth);
  42351. if (px < 0)
  42352. px = 0;
  42353. else if (px >= inputWidth)
  42354. px = inputWidth - 1;
  42355. var py = Math.round(dy * inputHeight);
  42356. if (py < 0)
  42357. py = 0;
  42358. else if (py >= inputHeight)
  42359. py = inputHeight - 1;
  42360. var inputY = (inputHeight - py - 1);
  42361. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42362. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42363. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42364. return {
  42365. r: r,
  42366. g: g,
  42367. b: b
  42368. };
  42369. };
  42370. PanoramaToCubeMapTools.FACE_FRONT = [
  42371. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42372. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42373. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42374. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42375. ];
  42376. PanoramaToCubeMapTools.FACE_BACK = [
  42377. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42378. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42379. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42380. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42381. ];
  42382. PanoramaToCubeMapTools.FACE_RIGHT = [
  42383. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42384. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42385. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42386. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42387. ];
  42388. PanoramaToCubeMapTools.FACE_LEFT = [
  42389. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42390. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42391. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42392. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42393. ];
  42394. PanoramaToCubeMapTools.FACE_DOWN = [
  42395. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42396. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42397. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42398. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42399. ];
  42400. PanoramaToCubeMapTools.FACE_UP = [
  42401. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42402. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42403. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42404. new BABYLON.Vector3(1.0, -1.0, -1.0)
  42405. ];
  42406. return PanoramaToCubeMapTools;
  42407. }());
  42408. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  42409. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42410. })(BABYLON || (BABYLON = {}));
  42411. var BABYLON;
  42412. (function (BABYLON) {
  42413. var Internals;
  42414. (function (Internals) {
  42415. ;
  42416. /**
  42417. * This groups tools to convert HDR texture to native colors array.
  42418. */
  42419. var HDRTools = (function () {
  42420. function HDRTools() {
  42421. }
  42422. HDRTools.Ldexp = function (mantissa, exponent) {
  42423. if (exponent > 1023) {
  42424. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  42425. }
  42426. if (exponent < -1074) {
  42427. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  42428. }
  42429. return mantissa * Math.pow(2, exponent);
  42430. };
  42431. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  42432. if (exponent > 0) {
  42433. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  42434. float32array[index + 0] = red * exponent;
  42435. float32array[index + 1] = green * exponent;
  42436. float32array[index + 2] = blue * exponent;
  42437. }
  42438. else {
  42439. float32array[index + 0] = 0;
  42440. float32array[index + 1] = 0;
  42441. float32array[index + 2] = 0;
  42442. }
  42443. };
  42444. HDRTools.readStringLine = function (uint8array, startIndex) {
  42445. var line = "";
  42446. var character = "";
  42447. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  42448. character = String.fromCharCode(uint8array[i]);
  42449. if (character == "\n") {
  42450. break;
  42451. }
  42452. line += character;
  42453. }
  42454. return line;
  42455. };
  42456. /**
  42457. * Reads header information from an RGBE texture stored in a native array.
  42458. * More information on this format are available here:
  42459. * https://en.wikipedia.org/wiki/RGBE_image_format
  42460. *
  42461. * @param uint8array The binary file stored in native array.
  42462. * @return The header information.
  42463. */
  42464. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42465. var height = 0;
  42466. var width = 0;
  42467. var line = this.readStringLine(uint8array, 0);
  42468. if (line[0] != '#' || line[1] != '?') {
  42469. throw "Bad HDR Format.";
  42470. }
  42471. var endOfHeader = false;
  42472. var findFormat = false;
  42473. var lineIndex = 0;
  42474. do {
  42475. lineIndex += (line.length + 1);
  42476. line = this.readStringLine(uint8array, lineIndex);
  42477. if (line == "FORMAT=32-bit_rle_rgbe") {
  42478. findFormat = true;
  42479. }
  42480. else if (line.length == 0) {
  42481. endOfHeader = true;
  42482. }
  42483. } while (!endOfHeader);
  42484. if (!findFormat) {
  42485. throw "HDR Bad header format, unsupported FORMAT";
  42486. }
  42487. lineIndex += (line.length + 1);
  42488. line = this.readStringLine(uint8array, lineIndex);
  42489. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42490. var match = sizeRegexp.exec(line);
  42491. // TODO. Support +Y and -X if needed.
  42492. if (match.length < 3) {
  42493. throw "HDR Bad header format, no size";
  42494. }
  42495. width = parseInt(match[2]);
  42496. height = parseInt(match[1]);
  42497. if (width < 8 || width > 0x7fff) {
  42498. throw "HDR Bad header format, unsupported size";
  42499. }
  42500. lineIndex += (line.length + 1);
  42501. return {
  42502. height: height,
  42503. width: width,
  42504. dataPosition: lineIndex
  42505. };
  42506. };
  42507. /**
  42508. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42509. * This RGBE texture needs to store the information as a panorama.
  42510. *
  42511. * More information on this format are available here:
  42512. * https://en.wikipedia.org/wiki/RGBE_image_format
  42513. *
  42514. * @param buffer The binary file stored in an array buffer.
  42515. * @param size The expected size of the extracted cubemap.
  42516. * @return The Cube Map information.
  42517. */
  42518. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42519. var uint8array = new Uint8Array(buffer);
  42520. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42521. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42522. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42523. return cubeMapData;
  42524. };
  42525. /**
  42526. * Returns the pixels data extracted from an RGBE texture.
  42527. * This pixels will be stored left to right up to down in the R G B order in one array.
  42528. *
  42529. * More information on this format are available here:
  42530. * https://en.wikipedia.org/wiki/RGBE_image_format
  42531. *
  42532. * @param uint8array The binary file stored in an array buffer.
  42533. * @param hdrInfo The header information of the file.
  42534. * @return The pixels data in RGB right to left up to down order.
  42535. */
  42536. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42537. // Keep for multi format supports.
  42538. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42539. };
  42540. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42541. var num_scanlines = hdrInfo.height;
  42542. var scanline_width = hdrInfo.width;
  42543. var a, b, c, d, count;
  42544. var dataIndex = hdrInfo.dataPosition;
  42545. var index = 0, endIndex = 0, i = 0;
  42546. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42547. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42548. // 3 channels of 4 bytes per pixel in float.
  42549. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42550. var resultArray = new Float32Array(resultBuffer);
  42551. // read in each successive scanline
  42552. while (num_scanlines > 0) {
  42553. a = uint8array[dataIndex++];
  42554. b = uint8array[dataIndex++];
  42555. c = uint8array[dataIndex++];
  42556. d = uint8array[dataIndex++];
  42557. if (a != 2 || b != 2 || (c & 0x80)) {
  42558. // this file is not run length encoded
  42559. throw "HDR Bad header format, not RLE";
  42560. }
  42561. if (((c << 8) | d) != scanline_width) {
  42562. throw "HDR Bad header format, wrong scan line width";
  42563. }
  42564. index = 0;
  42565. // read each of the four channels for the scanline into the buffer
  42566. for (i = 0; i < 4; i++) {
  42567. endIndex = (i + 1) * scanline_width;
  42568. while (index < endIndex) {
  42569. a = uint8array[dataIndex++];
  42570. b = uint8array[dataIndex++];
  42571. if (a > 128) {
  42572. // a run of the same value
  42573. count = a - 128;
  42574. if ((count == 0) || (count > endIndex - index)) {
  42575. throw "HDR Bad Format, bad scanline data (run)";
  42576. }
  42577. while (count-- > 0) {
  42578. scanLineArray[index++] = b;
  42579. }
  42580. }
  42581. else {
  42582. // a non-run
  42583. count = a;
  42584. if ((count == 0) || (count > endIndex - index)) {
  42585. throw "HDR Bad Format, bad scanline data (non-run)";
  42586. }
  42587. scanLineArray[index++] = b;
  42588. if (--count > 0) {
  42589. for (var j = 0; j < count; j++) {
  42590. scanLineArray[index++] = uint8array[dataIndex++];
  42591. }
  42592. }
  42593. }
  42594. }
  42595. }
  42596. // now convert data from buffer into floats
  42597. for (i = 0; i < scanline_width; i++) {
  42598. a = scanLineArray[i];
  42599. b = scanLineArray[i + scanline_width];
  42600. c = scanLineArray[i + 2 * scanline_width];
  42601. d = scanLineArray[i + 3 * scanline_width];
  42602. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42603. }
  42604. num_scanlines--;
  42605. }
  42606. return resultArray;
  42607. };
  42608. return HDRTools;
  42609. }());
  42610. Internals.HDRTools = HDRTools;
  42611. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42612. })(BABYLON || (BABYLON = {}));
  42613. //_______________________________________________________________
  42614. // Extracted from CubeMapGen:
  42615. // https://code.google.com/archive/p/cubemapgen/
  42616. //
  42617. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42618. //_______________________________________________________________
  42619. var BABYLON;
  42620. (function (BABYLON) {
  42621. var Internals;
  42622. (function (Internals) {
  42623. /**
  42624. * The bounding box information used during the conversion process.
  42625. */
  42626. var CMGBoundinBox = (function () {
  42627. function CMGBoundinBox() {
  42628. this.min = new BABYLON.Vector3(0, 0, 0);
  42629. this.max = new BABYLON.Vector3(0, 0, 0);
  42630. this.clear();
  42631. }
  42632. CMGBoundinBox.prototype.clear = function () {
  42633. this.min.x = CMGBoundinBox.MAX;
  42634. this.min.y = CMGBoundinBox.MAX;
  42635. this.min.z = CMGBoundinBox.MAX;
  42636. this.max.x = CMGBoundinBox.MIN;
  42637. this.max.y = CMGBoundinBox.MIN;
  42638. this.max.z = CMGBoundinBox.MIN;
  42639. };
  42640. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42641. this.min.x = Math.min(this.min.x, x);
  42642. this.min.y = Math.min(this.min.y, y);
  42643. this.min.z = Math.min(this.min.z, z);
  42644. this.max.x = Math.max(this.max.x, x);
  42645. this.max.y = Math.max(this.max.y, y);
  42646. this.max.z = Math.max(this.max.z, z);
  42647. };
  42648. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42649. this.min.x = Math.max(this.min.x, x);
  42650. this.min.y = Math.max(this.min.y, y);
  42651. this.min.z = Math.max(this.min.z, z);
  42652. };
  42653. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42654. this.max.x = Math.min(this.max.x, x);
  42655. this.max.y = Math.min(this.max.y, y);
  42656. this.max.z = Math.min(this.max.z, z);
  42657. };
  42658. CMGBoundinBox.prototype.empty = function () {
  42659. if ((this.min.x > this.max.y) ||
  42660. (this.min.y > this.max.y) ||
  42661. (this.min.z > this.max.y)) {
  42662. return true;
  42663. }
  42664. else {
  42665. return false;
  42666. }
  42667. };
  42668. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42669. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42670. return CMGBoundinBox;
  42671. }());
  42672. /**
  42673. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42674. * required by the glossinees of a material.
  42675. *
  42676. * This only supports the cosine drop power as well as Warp fixup generation method.
  42677. *
  42678. * This is using the process from CubeMapGen described here:
  42679. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42680. */
  42681. var PMREMGenerator = (function () {
  42682. /**
  42683. * Constructor of the generator.
  42684. *
  42685. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42686. * @param inputSize The size of the cubemap faces
  42687. * @param outputSize The size of the output cubemap faces
  42688. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42689. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42690. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42691. * @param specularPower The max specular level of the desired cubemap
  42692. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42693. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42694. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42695. */
  42696. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42697. this.input = input;
  42698. this.inputSize = inputSize;
  42699. this.outputSize = outputSize;
  42700. this.maxNumMipLevels = maxNumMipLevels;
  42701. this.numChannels = numChannels;
  42702. this.isFloat = isFloat;
  42703. this.specularPower = specularPower;
  42704. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42705. this.excludeBase = excludeBase;
  42706. this.fixup = fixup;
  42707. this._outputSurface = [];
  42708. this._numMipLevels = 0;
  42709. }
  42710. /**
  42711. * Launches the filter process and return the result.
  42712. *
  42713. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42714. */
  42715. PMREMGenerator.prototype.filterCubeMap = function () {
  42716. // Init cubemap processor
  42717. this.init();
  42718. // Filters the cubemap
  42719. this.filterCubeMapMipChain();
  42720. // Returns the filtered mips.
  42721. return this._outputSurface;
  42722. };
  42723. PMREMGenerator.prototype.init = function () {
  42724. var i;
  42725. var j;
  42726. var mipLevelSize;
  42727. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42728. if (this.maxNumMipLevels == 0) {
  42729. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42730. }
  42731. //first miplevel size
  42732. mipLevelSize = this.outputSize;
  42733. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42734. for (j = 0; j < this.maxNumMipLevels; j++) {
  42735. this._outputSurface.length++;
  42736. this._outputSurface[j] = [];
  42737. //Iterate over faces for output images
  42738. for (i = 0; i < 6; i++) {
  42739. this._outputSurface[j].length++;
  42740. // Initializes a new array for the output.
  42741. if (this.isFloat) {
  42742. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42743. }
  42744. else {
  42745. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42746. }
  42747. }
  42748. //next mip level is half size
  42749. mipLevelSize >>= 1;
  42750. this._numMipLevels++;
  42751. //terminate if mip chain becomes too small
  42752. if (mipLevelSize == 0) {
  42753. this.maxNumMipLevels = j;
  42754. return;
  42755. }
  42756. }
  42757. };
  42758. //--------------------------------------------------------------------------------------
  42759. //Cube map filtering and mip chain generation.
  42760. // the cube map filtereing is specified using a number of parameters:
  42761. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42762. // indicates the region of the hemisphere to filter over for each tap.
  42763. //
  42764. // Note that the top mip level is also a filtered version of the original input images
  42765. // as well in order to create mip chains for diffuse environment illumination.
  42766. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42767. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42768. //
  42769. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42770. // is a_InitialMipAngle
  42771. //
  42772. // The angle for the subsequent levels of the mip chain are specified by their parents
  42773. // filtering angle and a per-level scale and bias
  42774. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42775. //
  42776. //--------------------------------------------------------------------------------------
  42777. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42778. // First, take count of the lighting model to modify SpecularPower
  42779. // 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;
  42780. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42781. //Cone angle start (for generating subsequent mip levels)
  42782. var currentSpecularPower = this.specularPower;
  42783. //Build filter lookup tables based on the source miplevel size
  42784. this.precomputeFilterLookupTables(this.inputSize);
  42785. // Note that we need to filter the first level before generating mipmap
  42786. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42787. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42788. // TODO : Write a function to copy and scale the base mipmap in output
  42789. // I am just lazy here and just put a high specular power value, and do some if.
  42790. if (this.excludeBase && (levelIndex == 0)) {
  42791. // 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).
  42792. currentSpecularPower = 100000.0;
  42793. }
  42794. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42795. var srcCubeImage = this.input;
  42796. var dstCubeImage = this._outputSurface[levelIndex];
  42797. var dstSize = this.outputSize >> levelIndex;
  42798. // Compute required angle.
  42799. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42800. // filter cube surfaces
  42801. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42802. // fix seams
  42803. if (this.fixup) {
  42804. this.fixupCubeEdges(dstCubeImage, dstSize);
  42805. }
  42806. // Decrease the specular power to generate the mipmap chain
  42807. // TODO : Use another method for Exclude (see first comment at start of the function
  42808. if (this.excludeBase && (levelIndex == 0)) {
  42809. currentSpecularPower = this.specularPower;
  42810. }
  42811. currentSpecularPower *= this.cosinePowerDropPerMip;
  42812. }
  42813. };
  42814. //--------------------------------------------------------------------------------------
  42815. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  42816. // It allow to optimize the texel to access base on the specular power.
  42817. //--------------------------------------------------------------------------------------
  42818. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  42819. // We want to find the alpha such that:
  42820. // cos(alpha)^cosinePower = epsilon
  42821. // That's: acos(epsilon^(1/cosinePower))
  42822. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  42823. var angle = 180.0;
  42824. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  42825. angle *= 180.0 / Math.PI; // Convert to degree
  42826. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  42827. return angle;
  42828. };
  42829. //--------------------------------------------------------------------------------------
  42830. //Builds the following lookup tables prior to filtering:
  42831. // -normalizer cube map
  42832. // -tap weight lookup table
  42833. //
  42834. //--------------------------------------------------------------------------------------
  42835. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  42836. var srcTexelAngle;
  42837. var iCubeFace;
  42838. //clear pre-existing normalizer cube map
  42839. this._normCubeMap = [];
  42840. //Normalized vectors per cubeface and per-texel solid angle
  42841. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  42842. };
  42843. //--------------------------------------------------------------------------------------
  42844. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  42845. //
  42846. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  42847. //
  42848. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  42849. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  42850. // below
  42851. //--------------------------------------------------------------------------------------
  42852. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  42853. var iCubeFace;
  42854. var u;
  42855. var v;
  42856. //iterate over cube faces
  42857. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42858. //First three channels for norm cube, and last channel for solid angle
  42859. this._normCubeMap.push(new Float32Array(size * size * 4));
  42860. //fast texture walk, build normalizer cube map
  42861. var facesData = this.input[iCubeFace];
  42862. for (v = 0; v < size; v++) {
  42863. for (u = 0; u < size; u++) {
  42864. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  42865. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  42866. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  42867. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  42868. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  42869. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  42870. }
  42871. }
  42872. }
  42873. };
  42874. //--------------------------------------------------------------------------------------
  42875. // Convert cubemap face texel coordinates and face idx to 3D vector
  42876. // note the U and V coords are integer coords and range from 0 to size-1
  42877. // this routine can be used to generate a normalizer cube map
  42878. //--------------------------------------------------------------------------------------
  42879. // SL BEGIN
  42880. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  42881. var nvcU;
  42882. var nvcV;
  42883. var tempVec;
  42884. // Change from original AMD code
  42885. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42886. // + 0.5f is for texel center addressing
  42887. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  42888. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  42889. // warp fixup
  42890. if (fixup && size > 1) {
  42891. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  42892. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  42893. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  42894. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  42895. }
  42896. // Get current vector
  42897. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  42898. // U contribution
  42899. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42900. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  42901. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  42902. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  42903. // V contribution and Sum
  42904. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42905. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  42906. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  42907. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  42908. //add face axis
  42909. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  42910. PMREMGenerator._vectorTemp.x += faceAxis[0];
  42911. PMREMGenerator._vectorTemp.y += faceAxis[1];
  42912. PMREMGenerator._vectorTemp.z += faceAxis[2];
  42913. //normalize vector
  42914. PMREMGenerator._vectorTemp.normalize();
  42915. return PMREMGenerator._vectorTemp;
  42916. };
  42917. //--------------------------------------------------------------------------------------
  42918. // Convert 3D vector to cubemap face texel coordinates and face idx
  42919. // note the U and V coords are integer coords and range from 0 to size-1
  42920. // this routine can be used to generate a normalizer cube map
  42921. //
  42922. // returns face IDX and texel coords
  42923. //--------------------------------------------------------------------------------------
  42924. // SL BEGIN
  42925. /*
  42926. Mapping Texture Coordinates to Cube Map Faces
  42927. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  42928. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  42929. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  42930. map arrangement in Pixar's RenderMan package.
  42931. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  42932. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  42933. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  42934. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  42935. the major axis direction). The target column in the table below explains how the major axis direction
  42936. maps to the 2D image of a particular cube map target.
  42937. major axis
  42938. direction target sc tc ma
  42939. ---------- --------------------------------- --- --- ---
  42940. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  42941. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  42942. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  42943. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  42944. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  42945. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  42946. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  42947. an updated (s,t) is calculated as follows
  42948. s = ( sc/|ma| + 1 ) / 2
  42949. t = ( tc/|ma| + 1 ) / 2
  42950. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  42951. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  42952. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  42953. */
  42954. // Note this method return U and V in range from 0 to size-1
  42955. // SL END
  42956. // Store the information in vector3 for convenience (faceindex, u, v)
  42957. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  42958. var maxCoord;
  42959. var faceIdx;
  42960. //absolute value 3
  42961. var absX = Math.abs(x);
  42962. var absY = Math.abs(y);
  42963. var absZ = Math.abs(z);
  42964. if (absX >= absY && absX >= absZ) {
  42965. maxCoord = absX;
  42966. if (x >= 0) {
  42967. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  42968. }
  42969. else {
  42970. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  42971. }
  42972. }
  42973. else if (absY >= absX && absY >= absZ) {
  42974. maxCoord = absY;
  42975. if (y >= 0) {
  42976. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  42977. }
  42978. else {
  42979. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  42980. }
  42981. }
  42982. else {
  42983. maxCoord = absZ;
  42984. if (z >= 0) {
  42985. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  42986. }
  42987. else {
  42988. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  42989. }
  42990. }
  42991. //divide through by max coord so face vector lies on cube face
  42992. var scale = 1 / maxCoord;
  42993. x *= scale;
  42994. y *= scale;
  42995. z *= scale;
  42996. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42997. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  42998. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42999. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  43000. // Modify original AMD code to return value from 0 to Size - 1
  43001. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  43002. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  43003. PMREMGenerator._vectorTemp.x = faceIdx;
  43004. PMREMGenerator._vectorTemp.y = u;
  43005. PMREMGenerator._vectorTemp.z = v;
  43006. return PMREMGenerator._vectorTemp;
  43007. };
  43008. //--------------------------------------------------------------------------------------
  43009. //Original code from Ignacio CastaÒo
  43010. // This formula is from Manne ÷hrstrˆm's thesis.
  43011. // Take two coordiantes in the range [-1, 1] that define a portion of a
  43012. // cube face and return the area of the projection of that portion on the
  43013. // surface of the sphere.
  43014. //--------------------------------------------------------------------------------------
  43015. PMREMGenerator.prototype.areaElement = function (x, y) {
  43016. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  43017. };
  43018. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  43019. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43020. // (+ 0.5f is for texel center addressing)
  43021. u = (2.0 * (u + 0.5) / size) - 1.0;
  43022. v = (2.0 * (v + 0.5) / size) - 1.0;
  43023. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  43024. var invResolution = 1.0 / size;
  43025. // U and V are the -1..1 texture coordinate on the current face.
  43026. // Get projected area for this texel
  43027. var x0 = u - invResolution;
  43028. var y0 = v - invResolution;
  43029. var x1 = u + invResolution;
  43030. var y1 = v + invResolution;
  43031. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43032. return solidAngle;
  43033. };
  43034. //--------------------------------------------------------------------------------------
  43035. //The key to the speed of these filtering routines is to quickly define a per-face
  43036. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43037. // Later these pixels are selectively processed based on their dot products to see if
  43038. // they reside within the filtering cone.
  43039. //
  43040. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43041. // of the number of texels needed to be covered in width and height order to filter the
  43042. // region. the bounding box for the center taps face is defined first, and if the
  43043. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43044. // defined next
  43045. //--------------------------------------------------------------------------------------
  43046. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43047. // note that pixels within these regions may be rejected
  43048. // based on the anlge
  43049. var iCubeFace;
  43050. var u;
  43051. var v;
  43052. // bounding box per face to specify region to process
  43053. var filterExtents = [];
  43054. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43055. filterExtents.push(new CMGBoundinBox());
  43056. }
  43057. // min angle a src texel can cover (in degrees)
  43058. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43059. // angle about center tap to define filter cone
  43060. // filter angle is 1/2 the cone angle
  43061. var filterAngle = filterConeAngle / 2.0;
  43062. //ensure filter angle is larger than a texel
  43063. if (filterAngle < srcTexelAngle) {
  43064. filterAngle = srcTexelAngle;
  43065. }
  43066. //ensure filter cone is always smaller than the hemisphere
  43067. if (filterAngle > 90.0) {
  43068. filterAngle = 90.0;
  43069. }
  43070. // the maximum number of texels in 1D the filter cone angle will cover
  43071. // used to determine bounding box size for filter extents
  43072. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43073. // ensure conservative region always covers at least one texel
  43074. if (filterSize < 1) {
  43075. filterSize = 1;
  43076. }
  43077. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43078. // reside within the cone angle
  43079. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43080. // process required faces
  43081. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43082. //iterate over dst cube map face texel
  43083. for (v = 0; v < dstSize; v++) {
  43084. for (u = 0; u < dstSize; u++) {
  43085. //get center tap direction
  43086. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43087. //clear old per-face filter extents
  43088. this.clearFilterExtents(filterExtents);
  43089. //define per-face filter extents
  43090. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43091. //perform filtering of src faces using filter extents
  43092. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43093. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43094. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43095. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43096. }
  43097. }
  43098. }
  43099. };
  43100. //--------------------------------------------------------------------------------------
  43101. //Clear filter extents for the 6 cube map faces
  43102. //--------------------------------------------------------------------------------------
  43103. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43104. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43105. filterExtents[iCubeFaces].clear();
  43106. }
  43107. };
  43108. //--------------------------------------------------------------------------------------
  43109. //Define per-face bounding box filter extents
  43110. //
  43111. // These define conservative texel regions in each of the faces the filter can possibly
  43112. // process. When the pixels in the regions are actually processed, the dot product
  43113. // between the tap vector and the center tap vector is used to determine the weight of
  43114. // the tap and whether or not the tap is within the cone.
  43115. //
  43116. //--------------------------------------------------------------------------------------
  43117. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43118. //neighboring face and bleed over amount, and width of BBOX for
  43119. // left, right, top, and bottom edges of this face
  43120. var bleedOverAmount = [0, 0, 0, 0];
  43121. var bleedOverBBoxMin = [0, 0, 0, 0];
  43122. var bleedOverBBoxMax = [0, 0, 0, 0];
  43123. var neighborFace;
  43124. var neighborEdge;
  43125. var oppositeFaceIdx;
  43126. //get face idx, and u, v info from center tap dir
  43127. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43128. var faceIdx = result.x;
  43129. var u = result.y;
  43130. var v = result.z;
  43131. //define bbox size within face
  43132. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43133. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43134. filterExtents[faceIdx].clampMin(0, 0, 0);
  43135. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43136. //u and v extent in face corresponding to center tap
  43137. var minU = filterExtents[faceIdx].min.x;
  43138. var minV = filterExtents[faceIdx].min.y;
  43139. var maxU = filterExtents[faceIdx].max.x;
  43140. var maxV = filterExtents[faceIdx].max.y;
  43141. //bleed over amounts for face across u=0 edge (left)
  43142. bleedOverAmount[0] = (bboxSize - u);
  43143. bleedOverBBoxMin[0] = minV;
  43144. bleedOverBBoxMax[0] = maxV;
  43145. //bleed over amounts for face across u=1 edge (right)
  43146. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43147. bleedOverBBoxMin[1] = minV;
  43148. bleedOverBBoxMax[1] = maxV;
  43149. //bleed over to face across v=0 edge (up)
  43150. bleedOverAmount[2] = (bboxSize - v);
  43151. bleedOverBBoxMin[2] = minU;
  43152. bleedOverBBoxMax[2] = maxU;
  43153. //bleed over to face across v=1 edge (down)
  43154. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43155. bleedOverBBoxMin[3] = minU;
  43156. bleedOverBBoxMax[3] = maxU;
  43157. //compute bleed over regions in neighboring faces
  43158. for (var i = 0; i < 4; i++) {
  43159. if (bleedOverAmount[i] > 0) {
  43160. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43161. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43162. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43163. // be flipped: the cases are
  43164. // if a left edge mates with a left or bottom edge on the neighbor
  43165. // if a top edge mates with a top or right edge on the neighbor
  43166. // if a right edge mates with a right or top edge on the neighbor
  43167. // if a bottom edge mates with a bottom or left edge on the neighbor
  43168. //Seeing as the edges are enumerated as follows
  43169. // left =0
  43170. // right =1
  43171. // top =2
  43172. // bottom =3
  43173. //
  43174. // so if the edge enums are the same, or the sum of the enums == 3,
  43175. // the bbox needs to be flipped
  43176. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43177. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43178. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43179. }
  43180. //The way the bounding box is extended onto the neighboring face
  43181. // depends on which edge of neighboring face abuts with this one
  43182. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43183. case PMREMGenerator.CP_EDGE_LEFT:
  43184. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43185. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43186. break;
  43187. case PMREMGenerator.CP_EDGE_RIGHT:
  43188. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43189. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43190. break;
  43191. case PMREMGenerator.CP_EDGE_TOP:
  43192. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43193. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43194. break;
  43195. case PMREMGenerator.CP_EDGE_BOTTOM:
  43196. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43197. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43198. break;
  43199. }
  43200. //clamp filter extents in non-center tap faces to remain within surface
  43201. filterExtents[neighborFace].clampMin(0, 0, 0);
  43202. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43203. }
  43204. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43205. // from the center tap face, then process the opposite face entirely for now.
  43206. //Note that the cases in which this happens, what usually happens is that
  43207. // more than one edge bleeds onto the opposite face, and the bounding box
  43208. // encompasses the entire cube map face.
  43209. if (bleedOverAmount[i] > srcSize) {
  43210. //determine opposite face
  43211. switch (faceIdx) {
  43212. case PMREMGenerator.CP_FACE_X_POS:
  43213. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43214. break;
  43215. case PMREMGenerator.CP_FACE_X_NEG:
  43216. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43217. break;
  43218. case PMREMGenerator.CP_FACE_Y_POS:
  43219. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43220. break;
  43221. case PMREMGenerator.CP_FACE_Y_NEG:
  43222. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43223. break;
  43224. case PMREMGenerator.CP_FACE_Z_POS:
  43225. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43226. break;
  43227. case PMREMGenerator.CP_FACE_Z_NEG:
  43228. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43229. break;
  43230. default:
  43231. break;
  43232. }
  43233. //just encompass entire face for now
  43234. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43235. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43236. }
  43237. }
  43238. };
  43239. //--------------------------------------------------------------------------------------
  43240. //ProcessFilterExtents
  43241. // Process bounding box in each cube face
  43242. //
  43243. //--------------------------------------------------------------------------------------
  43244. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43245. //accumulators are 64-bit floats in order to have the precision needed
  43246. // over a summation of a large number of pixels
  43247. var dstAccum = [0, 0, 0, 0];
  43248. var weightAccum = 0;
  43249. var k = 0;
  43250. var nSrcChannels = this.numChannels;
  43251. // norm cube map and srcCubeMap have same face width
  43252. var faceWidth = srcSize;
  43253. //amount to add to pointer to move to next scanline in images
  43254. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43255. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43256. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43257. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43258. // iterate over cubefaces
  43259. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43260. //if bbox is non empty
  43261. if (!filterExtents[iFaceIdx].empty()) {
  43262. var uStart = filterExtents[iFaceIdx].min.x;
  43263. var vStart = filterExtents[iFaceIdx].min.y;
  43264. var uEnd = filterExtents[iFaceIdx].max.x;
  43265. var vEnd = filterExtents[iFaceIdx].max.y;
  43266. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43267. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43268. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43269. for (var v = vStart; v <= vEnd; v++) {
  43270. var normCubeRowWalk = 0;
  43271. var srcCubeRowWalk = 0;
  43272. for (var u = uStart; u <= uEnd; u++) {
  43273. //pointer to direction in cube map associated with texel
  43274. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43275. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43276. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43277. //check dot product to see if texel is within cone
  43278. var tapDotProd = texelVectX * centerTapDir.x +
  43279. texelVectY * centerTapDir.y +
  43280. texelVectZ * centerTapDir.z;
  43281. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43282. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43283. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43284. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43285. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43286. // so just adding one to specularpower do the trick.
  43287. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43288. //iterate over channels
  43289. for (k = 0; k < nSrcChannels; k++) {
  43290. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43291. srcCubeRowWalk++;
  43292. }
  43293. weightAccum += weight; //accumulate weight
  43294. }
  43295. else {
  43296. //step across source pixel
  43297. srcCubeRowWalk += nSrcChannels;
  43298. }
  43299. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43300. }
  43301. startIndexNormCubeMap += normCubePitch;
  43302. startIndexSrcCubeMap += srcCubePitch;
  43303. }
  43304. }
  43305. }
  43306. //divide through by weights if weight is non zero
  43307. if (weightAccum != 0.0) {
  43308. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43309. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43310. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43311. if (this.numChannels > 3) {
  43312. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43313. }
  43314. }
  43315. else {
  43316. // otherwise sample nearest
  43317. // get face idx and u, v texel coordinate in face
  43318. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43319. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43320. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43321. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43322. if (this.numChannels > 3) {
  43323. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43324. }
  43325. }
  43326. return PMREMGenerator._vectorTemp;
  43327. };
  43328. //--------------------------------------------------------------------------------------
  43329. // Fixup cube edges
  43330. //
  43331. // average texels on cube map faces across the edges
  43332. // WARP/BENT Method Only.
  43333. //--------------------------------------------------------------------------------------
  43334. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43335. var k;
  43336. var j;
  43337. var i;
  43338. var iFace;
  43339. var iCorner = 0;
  43340. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43341. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43342. // note that if functionality to filter across the three texels for each corner, then
  43343. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43344. var cornerPtr = [
  43345. [[], [], []],
  43346. [[], [], []],
  43347. [[], [], []],
  43348. [[], [], []],
  43349. [[], [], []],
  43350. [[], [], []],
  43351. [[], [], []],
  43352. [[], [], []]
  43353. ];
  43354. //if there is no fixup, or fixup width = 0, do nothing
  43355. if (cubeMapSize < 1) {
  43356. return;
  43357. }
  43358. //special case 1x1 cubemap, average face colors
  43359. if (cubeMapSize == 1) {
  43360. //iterate over channels
  43361. for (k = 0; k < this.numChannels; k++) {
  43362. var accum = 0.0;
  43363. //iterate over faces to accumulate face colors
  43364. for (iFace = 0; iFace < 6; iFace++) {
  43365. accum += cubeMap[iFace][k];
  43366. }
  43367. //compute average over 6 face colors
  43368. accum /= 6.0;
  43369. //iterate over faces to distribute face colors
  43370. for (iFace = 0; iFace < 6; iFace++) {
  43371. cubeMap[iFace][k] = accum;
  43372. }
  43373. }
  43374. return;
  43375. }
  43376. //iterate over faces to collect list of corner texel pointers
  43377. for (iFace = 0; iFace < 6; iFace++) {
  43378. //the 4 corner pointers for this face
  43379. faceCornerStartIndicies[0] = [iFace, 0];
  43380. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43381. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43382. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43383. //iterate over face corners to collect cube corner pointers
  43384. for (iCorner = 0; iCorner < 4; iCorner++) {
  43385. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43386. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43387. cornerNumPtrs[corner]++;
  43388. }
  43389. }
  43390. //iterate over corners to average across corner tap values
  43391. for (iCorner = 0; iCorner < 8; iCorner++) {
  43392. for (k = 0; k < this.numChannels; k++) {
  43393. var cornerTapAccum = 0.0;
  43394. //iterate over corner texels and average results
  43395. for (i = 0; i < 3; i++) {
  43396. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  43397. }
  43398. //divide by 3 to compute average of corner tap values
  43399. cornerTapAccum *= (1.0 / 3.0);
  43400. //iterate over corner texels and average results
  43401. for (i = 0; i < 3; i++) {
  43402. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  43403. }
  43404. }
  43405. }
  43406. //iterate over the twelve edges of the cube to average across edges
  43407. for (i = 0; i < 12; i++) {
  43408. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  43409. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  43410. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  43411. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  43412. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  43413. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  43414. var edgeWalk = 0;
  43415. var neighborEdgeWalk = 0;
  43416. //Determine walking pointers based on edge type
  43417. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  43418. switch (edge) {
  43419. case PMREMGenerator.CP_EDGE_LEFT:
  43420. // no change to faceEdgeStartPtr
  43421. edgeWalk = this.numChannels * cubeMapSize;
  43422. break;
  43423. case PMREMGenerator.CP_EDGE_RIGHT:
  43424. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43425. edgeWalk = this.numChannels * cubeMapSize;
  43426. break;
  43427. case PMREMGenerator.CP_EDGE_TOP:
  43428. // no change to faceEdgeStartPtr
  43429. edgeWalk = this.numChannels;
  43430. break;
  43431. case PMREMGenerator.CP_EDGE_BOTTOM:
  43432. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43433. edgeWalk = this.numChannels;
  43434. break;
  43435. }
  43436. //For certain types of edge abutments, the neighbor edge walk needs to
  43437. // be flipped: the cases are
  43438. // if a left edge mates with a left or bottom edge on the neighbor
  43439. // if a top edge mates with a top or right edge on the neighbor
  43440. // if a right edge mates with a right or top edge on the neighbor
  43441. // if a bottom edge mates with a bottom or left edge on the neighbor
  43442. //Seeing as the edges are enumerated as follows
  43443. // left =0
  43444. // right =1
  43445. // top =2
  43446. // bottom =3
  43447. //
  43448. //If the edge enums are the same, or the sum of the enums == 3,
  43449. // the neighbor edge walk needs to be flipped
  43450. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43451. switch (neighborEdge) {
  43452. case PMREMGenerator.CP_EDGE_LEFT:
  43453. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43454. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43455. break;
  43456. case PMREMGenerator.CP_EDGE_RIGHT:
  43457. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43458. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43459. break;
  43460. case PMREMGenerator.CP_EDGE_TOP:
  43461. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43462. neighborEdgeWalk = -this.numChannels;
  43463. break;
  43464. case PMREMGenerator.CP_EDGE_BOTTOM:
  43465. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43466. neighborEdgeWalk = -this.numChannels;
  43467. break;
  43468. }
  43469. }
  43470. else {
  43471. //swapped direction neighbor edge walk
  43472. switch (neighborEdge) {
  43473. case PMREMGenerator.CP_EDGE_LEFT:
  43474. //no change to neighborEdgeStartPtr for this case since it points
  43475. // to the upper left corner already
  43476. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43477. break;
  43478. case PMREMGenerator.CP_EDGE_RIGHT:
  43479. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43480. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43481. break;
  43482. case PMREMGenerator.CP_EDGE_TOP:
  43483. //no change to neighborEdgeStartPtr for this case since it points
  43484. // to the upper left corner already
  43485. neighborEdgeWalk = this.numChannels;
  43486. break;
  43487. case PMREMGenerator.CP_EDGE_BOTTOM:
  43488. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43489. neighborEdgeWalk = this.numChannels;
  43490. break;
  43491. }
  43492. }
  43493. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43494. //nearby neighborhood
  43495. //step ahead one texel on edge
  43496. edgeStartIndex += edgeWalk;
  43497. neighborEdgeStartIndex += neighborEdgeWalk;
  43498. // note that this loop does not process the corner texels, since they have already been
  43499. // averaged across faces across earlier
  43500. for (j = 1; j < (cubeMapSize - 1); j++) {
  43501. //for each set of taps along edge, average them
  43502. // and rewrite the results into the edges
  43503. for (k = 0; k < this.numChannels; k++) {
  43504. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43505. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43506. //compute average of tap intensity values
  43507. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43508. //propagate average of taps to edge taps
  43509. cubeMap[face][edgeStartIndex + k] = avgTap;
  43510. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43511. }
  43512. edgeStartIndex += edgeWalk;
  43513. neighborEdgeStartIndex += neighborEdgeWalk;
  43514. }
  43515. }
  43516. };
  43517. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43518. PMREMGenerator.CP_UDIR = 0;
  43519. PMREMGenerator.CP_VDIR = 1;
  43520. PMREMGenerator.CP_FACEAXIS = 2;
  43521. //used to index cube faces
  43522. PMREMGenerator.CP_FACE_X_POS = 0;
  43523. PMREMGenerator.CP_FACE_X_NEG = 1;
  43524. PMREMGenerator.CP_FACE_Y_POS = 2;
  43525. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43526. PMREMGenerator.CP_FACE_Z_POS = 4;
  43527. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43528. //used to index image edges
  43529. // NOTE.. the actual number corresponding to the edge is important
  43530. // do not change these, or the code will break
  43531. //
  43532. // CP_EDGE_LEFT is u = 0
  43533. // CP_EDGE_RIGHT is u = width-1
  43534. // CP_EDGE_TOP is v = 0
  43535. // CP_EDGE_BOTTOM is v = height-1
  43536. PMREMGenerator.CP_EDGE_LEFT = 0;
  43537. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43538. PMREMGenerator.CP_EDGE_TOP = 2;
  43539. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43540. //corners of CUBE map (P or N specifys if it corresponds to the
  43541. // positive or negative direction each of X, Y, and Z
  43542. PMREMGenerator.CP_CORNER_NNN = 0;
  43543. PMREMGenerator.CP_CORNER_NNP = 1;
  43544. PMREMGenerator.CP_CORNER_NPN = 2;
  43545. PMREMGenerator.CP_CORNER_NPP = 3;
  43546. PMREMGenerator.CP_CORNER_PNN = 4;
  43547. PMREMGenerator.CP_CORNER_PNP = 5;
  43548. PMREMGenerator.CP_CORNER_PPN = 6;
  43549. PMREMGenerator.CP_CORNER_PPP = 7;
  43550. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43551. //3x2 matrices that map cube map indexing vectors in 3d
  43552. // (after face selection and divide through by the
  43553. // _ABSOLUTE VALUE_ of the max coord)
  43554. // into NVC space
  43555. //Note this currently assumes the D3D cube face ordering and orientation
  43556. PMREMGenerator._sgFace2DMapping = [
  43557. //XPOS face
  43558. [[0, 0, -1],
  43559. [0, -1, 0],
  43560. [1, 0, 0]],
  43561. //XNEG face
  43562. [[0, 0, 1],
  43563. [0, -1, 0],
  43564. [-1, 0, 0]],
  43565. //YPOS face
  43566. [[1, 0, 0],
  43567. [0, 0, 1],
  43568. [0, 1, 0]],
  43569. //YNEG face
  43570. [[1, 0, 0],
  43571. [0, 0, -1],
  43572. [0, -1, 0]],
  43573. //ZPOS face
  43574. [[1, 0, 0],
  43575. [0, -1, 0],
  43576. [0, 0, 1]],
  43577. //ZNEG face
  43578. [[-1, 0, 0],
  43579. [0, -1, 0],
  43580. [0, 0, -1]],
  43581. ];
  43582. //------------------------------------------------------------------------------
  43583. // D3D cube map face specification
  43584. // mapping from 3D x,y,z cube map lookup coordinates
  43585. // to 2D within face u,v coordinates
  43586. //
  43587. // --------------------> U direction
  43588. // | (within-face texture space)
  43589. // | _____
  43590. // | | |
  43591. // | | +Y |
  43592. // | _____|_____|_____ _____
  43593. // | | | | | |
  43594. // | | -X | +Z | +X | -Z |
  43595. // | |_____|_____|_____|_____|
  43596. // | | |
  43597. // | | -Y |
  43598. // | |_____|
  43599. // |
  43600. // v V direction
  43601. // (within-face texture space)
  43602. //------------------------------------------------------------------------------
  43603. //Information about neighbors and how texture coorrdinates change across faces
  43604. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43605. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43606. //Note this currently assumes the D3D cube face ordering and orientation
  43607. PMREMGenerator._sgCubeNgh = [
  43608. //XPOS face
  43609. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43610. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43611. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43612. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43613. //XNEG face
  43614. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43615. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43616. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43617. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43618. //YPOS face
  43619. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43620. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43621. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43622. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43623. //YNEG face
  43624. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43625. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43626. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43627. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43628. //ZPOS face
  43629. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43630. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43631. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43632. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43633. //ZNEG face
  43634. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43635. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43636. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43637. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43638. ];
  43639. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43640. // this table is used to average over the edges.
  43641. PMREMGenerator._sgCubeEdgeList = [
  43642. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43643. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43644. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43645. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43646. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43647. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43648. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43649. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43650. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43651. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43652. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43653. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43654. ];
  43655. //Information about which of the 8 cube corners are correspond to the
  43656. // the 4 corners in each cube face
  43657. // the order is upper left, upper right, lower left, lower right
  43658. PMREMGenerator._sgCubeCornerList = [
  43659. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43660. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43661. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43662. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43663. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43664. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43665. ];
  43666. return PMREMGenerator;
  43667. }());
  43668. Internals.PMREMGenerator = PMREMGenerator;
  43669. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43670. })(BABYLON || (BABYLON = {}));
  43671. var BABYLON;
  43672. (function (BABYLON) {
  43673. /**
  43674. * This represents a texture coming from an HDR input.
  43675. *
  43676. * The only supported format is currently panorama picture stored in RGBE format.
  43677. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43678. */
  43679. var HDRCubeTexture = (function (_super) {
  43680. __extends(HDRCubeTexture, _super);
  43681. /**
  43682. * Instantiates an HDRTexture from the following parameters.
  43683. *
  43684. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43685. * @param scene The scene the texture will be used in
  43686. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  43687. * @param noMipmap Forces to not generate the mipmap if true
  43688. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43689. * @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)
  43690. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43691. */
  43692. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43693. if (noMipmap === void 0) { noMipmap = false; }
  43694. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43695. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43696. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43697. _super.call(this, scene);
  43698. this._useInGammaSpace = false;
  43699. this._generateHarmonics = true;
  43700. /**
  43701. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43702. */
  43703. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43704. /**
  43705. * The spherical polynomial data extracted from the texture.
  43706. */
  43707. this.sphericalPolynomial = null;
  43708. /**
  43709. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43710. * This is usefull at run time to apply the good shader.
  43711. */
  43712. this.isPMREM = false;
  43713. this.name = url;
  43714. this.url = url;
  43715. this._noMipmap = noMipmap;
  43716. this.hasAlpha = false;
  43717. this._size = size;
  43718. this._useInGammaSpace = useInGammaSpace;
  43719. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43720. this.isPMREM = this._usePMREMGenerator;
  43721. if (!url) {
  43722. return;
  43723. }
  43724. this._texture = this._getFromCache(url, noMipmap);
  43725. if (!this._texture) {
  43726. if (!scene.useDelayedTextureLoading) {
  43727. this.loadTexture();
  43728. }
  43729. else {
  43730. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43731. }
  43732. }
  43733. this.isCube = true;
  43734. this._textureMatrix = BABYLON.Matrix.Identity();
  43735. }
  43736. HDRCubeTexture.prototype.loadTexture = function () {
  43737. var _this = this;
  43738. var callback = function (buffer) {
  43739. // Extract the raw linear data.
  43740. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  43741. // Generate harmonics if needed.
  43742. if (_this._generateHarmonics) {
  43743. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  43744. }
  43745. var results = [];
  43746. var byteArray = null;
  43747. // Create uintarray fallback.
  43748. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43749. // 3 channels of 1 bytes per pixel in bytes.
  43750. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  43751. byteArray = new Uint8Array(byteBuffer);
  43752. }
  43753. // Push each faces.
  43754. for (var j = 0; j < 6; j++) {
  43755. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  43756. // If special cases.
  43757. if (_this._useInGammaSpace || byteArray) {
  43758. for (var i = 0; i < _this._size * _this._size; i++) {
  43759. // Put in gamma space if requested.
  43760. if (_this._useInGammaSpace) {
  43761. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  43762. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  43763. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  43764. }
  43765. // Convert to int texture for fallback.
  43766. if (byteArray) {
  43767. // R
  43768. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  43769. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  43770. // G
  43771. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  43772. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  43773. // B
  43774. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  43775. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  43776. }
  43777. }
  43778. }
  43779. results.push(dataFace);
  43780. }
  43781. return results;
  43782. };
  43783. var mipmapGenerator = null;
  43784. if (!this._noMipmap && this._usePMREMGenerator) {
  43785. mipmapGenerator = function (data) {
  43786. // Custom setup of the generator matching with the PBR shader values.
  43787. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  43788. return generator.filterCubeMap();
  43789. };
  43790. }
  43791. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  43792. };
  43793. HDRCubeTexture.prototype.clone = function () {
  43794. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  43795. // Base texture
  43796. newTexture.level = this.level;
  43797. newTexture.wrapU = this.wrapU;
  43798. newTexture.wrapV = this.wrapV;
  43799. newTexture.coordinatesIndex = this.coordinatesIndex;
  43800. newTexture.coordinatesMode = this.coordinatesMode;
  43801. return newTexture;
  43802. };
  43803. // Methods
  43804. HDRCubeTexture.prototype.delayLoad = function () {
  43805. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43806. return;
  43807. }
  43808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43809. this._texture = this._getFromCache(this.url, this._noMipmap);
  43810. if (!this._texture) {
  43811. this.loadTexture();
  43812. }
  43813. };
  43814. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  43815. return this._textureMatrix;
  43816. };
  43817. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43818. var texture = null;
  43819. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  43820. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  43821. texture.name = parsedTexture.name;
  43822. texture.hasAlpha = parsedTexture.hasAlpha;
  43823. texture.level = parsedTexture.level;
  43824. texture.coordinatesMode = parsedTexture.coordinatesMode;
  43825. }
  43826. return texture;
  43827. };
  43828. HDRCubeTexture.prototype.serialize = function () {
  43829. if (!this.name) {
  43830. return null;
  43831. }
  43832. var serializationObject = {};
  43833. serializationObject.name = this.name;
  43834. serializationObject.hasAlpha = this.hasAlpha;
  43835. serializationObject.isCube = true;
  43836. serializationObject.level = this.level;
  43837. serializationObject.size = this._size;
  43838. serializationObject.coordinatesMode = this.coordinatesMode;
  43839. serializationObject.useInGammaSpace = this._useInGammaSpace;
  43840. serializationObject.generateHarmonics = this._generateHarmonics;
  43841. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  43842. return serializationObject;
  43843. };
  43844. HDRCubeTexture._facesMapping = [
  43845. "right",
  43846. "up",
  43847. "front",
  43848. "left",
  43849. "down",
  43850. "back"
  43851. ];
  43852. return HDRCubeTexture;
  43853. }(BABYLON.BaseTexture));
  43854. BABYLON.HDRCubeTexture = HDRCubeTexture;
  43855. })(BABYLON || (BABYLON = {}));
  43856. var BABYLON;
  43857. (function (BABYLON) {
  43858. var Debug;
  43859. (function (Debug) {
  43860. /**
  43861. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43862. */
  43863. var SkeletonViewer = (function () {
  43864. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43865. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43866. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43867. this.skeleton = skeleton;
  43868. this.mesh = mesh;
  43869. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43870. this.renderingGroupId = renderingGroupId;
  43871. this.color = BABYLON.Color3.White();
  43872. this._debugLines = [];
  43873. this._isEnabled = false;
  43874. this._scene = scene;
  43875. this.update();
  43876. this._renderFunction = this.update.bind(this);
  43877. }
  43878. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43879. get: function () {
  43880. return this._isEnabled;
  43881. },
  43882. set: function (value) {
  43883. if (this._isEnabled === value) {
  43884. return;
  43885. }
  43886. this._isEnabled = value;
  43887. if (value) {
  43888. this._scene.registerBeforeRender(this._renderFunction);
  43889. }
  43890. else {
  43891. this._scene.unregisterBeforeRender(this._renderFunction);
  43892. }
  43893. },
  43894. enumerable: true,
  43895. configurable: true
  43896. });
  43897. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43898. if (x === void 0) { x = 0; }
  43899. if (y === void 0) { y = 0; }
  43900. if (z === void 0) { z = 0; }
  43901. var tmat = BABYLON.Tmp.Matrix[0];
  43902. var parentBone = bone.getParent();
  43903. tmat.copyFrom(bone.getLocalMatrix());
  43904. if (x !== 0 || y !== 0 || z !== 0) {
  43905. var tmat2 = BABYLON.Tmp.Matrix[1];
  43906. BABYLON.Matrix.IdentityToRef(tmat2);
  43907. tmat2.m[12] = x;
  43908. tmat2.m[13] = y;
  43909. tmat2.m[14] = z;
  43910. tmat2.multiplyToRef(tmat, tmat);
  43911. }
  43912. if (parentBone) {
  43913. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  43914. }
  43915. tmat.multiplyToRef(meshMat, tmat);
  43916. position.x = tmat.m[12];
  43917. position.y = tmat.m[13];
  43918. position.z = tmat.m[14];
  43919. };
  43920. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  43921. var len = bones.length;
  43922. for (var i = 0; i < len; i++) {
  43923. var bone = bones[i];
  43924. var points = this._debugLines[i];
  43925. if (!points) {
  43926. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43927. this._debugLines[i] = points;
  43928. }
  43929. this._getBonePosition(points[0], bone, meshMat);
  43930. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  43931. }
  43932. };
  43933. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  43934. var len = bones.length;
  43935. var boneNum = 0;
  43936. for (var i = len - 1; i >= 0; i--) {
  43937. var childBone = bones[i];
  43938. var parentBone = childBone.getParent();
  43939. if (!parentBone) {
  43940. continue;
  43941. }
  43942. var points = this._debugLines[boneNum];
  43943. if (!points) {
  43944. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43945. this._debugLines[boneNum] = points;
  43946. }
  43947. this._getBonePosition(points[0], childBone, meshMat);
  43948. this._getBonePosition(points[1], parentBone, meshMat);
  43949. boneNum++;
  43950. }
  43951. };
  43952. SkeletonViewer.prototype.update = function () {
  43953. if (this.autoUpdateBonesMatrices) {
  43954. this._updateBoneMatrix(this.skeleton.bones[0]);
  43955. }
  43956. if (this.skeleton.bones[0].length === undefined) {
  43957. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43958. }
  43959. else {
  43960. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43961. }
  43962. if (!this._debugMesh) {
  43963. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  43964. this._debugMesh.renderingGroupId = this.renderingGroupId;
  43965. }
  43966. else {
  43967. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  43968. }
  43969. this._debugMesh.color = this.color;
  43970. };
  43971. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  43972. if (bone.getParent()) {
  43973. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  43974. }
  43975. var children = bone.children;
  43976. var len = children.length;
  43977. for (var i = 0; i < len; i++) {
  43978. this._updateBoneMatrix(children[i]);
  43979. }
  43980. };
  43981. SkeletonViewer.prototype.dispose = function () {
  43982. if (this._debugMesh) {
  43983. this.isEnabled = false;
  43984. this._debugMesh.dispose();
  43985. this._debugMesh = null;
  43986. }
  43987. };
  43988. return SkeletonViewer;
  43989. }());
  43990. Debug.SkeletonViewer = SkeletonViewer;
  43991. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43992. })(BABYLON || (BABYLON = {}));
  43993. var BABYLON;
  43994. (function (BABYLON) {
  43995. var maxSimultaneousLights = 4;
  43996. var PBRMaterialDefines = (function (_super) {
  43997. __extends(PBRMaterialDefines, _super);
  43998. function PBRMaterialDefines() {
  43999. _super.call(this);
  44000. this.ALBEDO = false;
  44001. this.AMBIENT = false;
  44002. this.OPACITY = false;
  44003. this.OPACITYRGB = false;
  44004. this.REFLECTION = false;
  44005. this.EMISSIVE = false;
  44006. this.REFLECTIVITY = false;
  44007. this.BUMP = false;
  44008. this.PARALLAX = false;
  44009. this.PARALLAXOCCLUSION = false;
  44010. this.SPECULAROVERALPHA = false;
  44011. this.CLIPPLANE = false;
  44012. this.ALPHATEST = false;
  44013. this.ALPHAFROMALBEDO = false;
  44014. this.POINTSIZE = false;
  44015. this.FOG = false;
  44016. this.LIGHT0 = false;
  44017. this.LIGHT1 = false;
  44018. this.LIGHT2 = false;
  44019. this.LIGHT3 = false;
  44020. this.SPOTLIGHT0 = false;
  44021. this.SPOTLIGHT1 = false;
  44022. this.SPOTLIGHT2 = false;
  44023. this.SPOTLIGHT3 = false;
  44024. this.HEMILIGHT0 = false;
  44025. this.HEMILIGHT1 = false;
  44026. this.HEMILIGHT2 = false;
  44027. this.HEMILIGHT3 = false;
  44028. this.POINTLIGHT0 = false;
  44029. this.POINTLIGHT1 = false;
  44030. this.POINTLIGHT2 = false;
  44031. this.POINTLIGHT3 = false;
  44032. this.DIRLIGHT0 = false;
  44033. this.DIRLIGHT1 = false;
  44034. this.DIRLIGHT2 = false;
  44035. this.DIRLIGHT3 = false;
  44036. this.SPECULARTERM = false;
  44037. this.SHADOW0 = false;
  44038. this.SHADOW1 = false;
  44039. this.SHADOW2 = false;
  44040. this.SHADOW3 = false;
  44041. this.SHADOWS = false;
  44042. this.SHADOWVSM0 = false;
  44043. this.SHADOWVSM1 = false;
  44044. this.SHADOWVSM2 = false;
  44045. this.SHADOWVSM3 = false;
  44046. this.SHADOWPCF0 = false;
  44047. this.SHADOWPCF1 = false;
  44048. this.SHADOWPCF2 = false;
  44049. this.SHADOWPCF3 = false;
  44050. this.OPACITYFRESNEL = false;
  44051. this.EMISSIVEFRESNEL = false;
  44052. this.FRESNEL = false;
  44053. this.NORMAL = false;
  44054. this.UV1 = false;
  44055. this.UV2 = false;
  44056. this.VERTEXCOLOR = false;
  44057. this.VERTEXALPHA = false;
  44058. this.NUM_BONE_INFLUENCERS = 0;
  44059. this.BonesPerMesh = 0;
  44060. this.INSTANCES = false;
  44061. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44062. this.MICROSURFACEAUTOMATIC = false;
  44063. this.EMISSIVEASILLUMINATION = false;
  44064. this.LINKEMISSIVEWITHALBEDO = false;
  44065. this.LIGHTMAP = false;
  44066. this.USELIGHTMAPASSHADOWMAP = false;
  44067. this.REFLECTIONMAP_3D = false;
  44068. this.REFLECTIONMAP_SPHERICAL = false;
  44069. this.REFLECTIONMAP_PLANAR = false;
  44070. this.REFLECTIONMAP_CUBIC = false;
  44071. this.REFLECTIONMAP_PROJECTION = false;
  44072. this.REFLECTIONMAP_SKYBOX = false;
  44073. this.REFLECTIONMAP_EXPLICIT = false;
  44074. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44075. this.INVERTCUBICMAP = false;
  44076. this.LOGARITHMICDEPTH = false;
  44077. this.CAMERATONEMAP = false;
  44078. this.CAMERACONTRAST = false;
  44079. this.OVERLOADEDVALUES = false;
  44080. this.OVERLOADEDSHADOWVALUES = false;
  44081. this.USESPHERICALFROMREFLECTIONMAP = false;
  44082. this.REFRACTION = false;
  44083. this.REFRACTIONMAP_3D = false;
  44084. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44085. this.REFRACTIONMAPINLINEARSPACE = false;
  44086. this.LODBASEDMICROSFURACE = false;
  44087. this.USEPHYSICALLIGHTFALLOFF = false;
  44088. this.RADIANCEOVERALPHA = false;
  44089. this.USEPMREMREFLECTION = false;
  44090. this.USEPMREMREFRACTION = false;
  44091. this._keys = Object.keys(this);
  44092. }
  44093. return PBRMaterialDefines;
  44094. }(BABYLON.MaterialDefines));
  44095. /**
  44096. * The Physically based material of BJS.
  44097. *
  44098. * This offers the main features of a standard PBR material.
  44099. * For more information, please refer to the documentation :
  44100. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44101. */
  44102. var PBRMaterial = (function (_super) {
  44103. __extends(PBRMaterial, _super);
  44104. /**
  44105. * Instantiates a new PBRMaterial instance.
  44106. *
  44107. * @param name The material name
  44108. * @param scene The scene the material will be use in.
  44109. */
  44110. function PBRMaterial(name, scene) {
  44111. var _this = this;
  44112. _super.call(this, name, scene);
  44113. /**
  44114. * Intensity of the direct lights e.g. the four lights available in your scene.
  44115. * This impacts both the direct diffuse and specular highlights.
  44116. */
  44117. this.directIntensity = 1.0;
  44118. /**
  44119. * Intensity of the emissive part of the material.
  44120. * This helps controlling the emissive effect without modifying the emissive color.
  44121. */
  44122. this.emissiveIntensity = 1.0;
  44123. /**
  44124. * Intensity of the environment e.g. how much the environment will light the object
  44125. * either through harmonics for rough material or through the refelction for shiny ones.
  44126. */
  44127. this.environmentIntensity = 1.0;
  44128. /**
  44129. * This is a special control allowing the reduction of the specular highlights coming from the
  44130. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44131. */
  44132. this.specularIntensity = 1.0;
  44133. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44134. /**
  44135. * Debug Control allowing disabling the bump map on this material.
  44136. */
  44137. this.disableBumpMap = false;
  44138. /**
  44139. * Debug Control helping enforcing or dropping the darkness of shadows.
  44140. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44141. */
  44142. this.overloadedShadowIntensity = 1.0;
  44143. /**
  44144. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44145. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44146. */
  44147. this.overloadedShadeIntensity = 1.0;
  44148. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44149. /**
  44150. * The camera exposure used on this material.
  44151. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44152. * This corresponds to a photographic exposure.
  44153. */
  44154. this.cameraExposure = 1.0;
  44155. /**
  44156. * The camera contrast used on this material.
  44157. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44158. */
  44159. this.cameraContrast = 1.0;
  44160. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44161. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44162. /**
  44163. * Debug Control allowing to overload the ambient color.
  44164. * This as to be use with the overloadedAmbientIntensity parameter.
  44165. */
  44166. this.overloadedAmbient = BABYLON.Color3.White();
  44167. /**
  44168. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  44169. */
  44170. this.overloadedAmbientIntensity = 0.0;
  44171. /**
  44172. * Debug Control allowing to overload the albedo color.
  44173. * This as to be use with the overloadedAlbedoIntensity parameter.
  44174. */
  44175. this.overloadedAlbedo = BABYLON.Color3.White();
  44176. /**
  44177. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  44178. */
  44179. this.overloadedAlbedoIntensity = 0.0;
  44180. /**
  44181. * Debug Control allowing to overload the reflectivity color.
  44182. * This as to be use with the overloadedReflectivityIntensity parameter.
  44183. */
  44184. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  44185. /**
  44186. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  44187. */
  44188. this.overloadedReflectivityIntensity = 0.0;
  44189. /**
  44190. * Debug Control allowing to overload the emissive color.
  44191. * This as to be use with the overloadedEmissiveIntensity parameter.
  44192. */
  44193. this.overloadedEmissive = BABYLON.Color3.White();
  44194. /**
  44195. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  44196. */
  44197. this.overloadedEmissiveIntensity = 0.0;
  44198. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  44199. /**
  44200. * Debug Control allowing to overload the reflection color.
  44201. * This as to be use with the overloadedReflectionIntensity parameter.
  44202. */
  44203. this.overloadedReflection = BABYLON.Color3.White();
  44204. /**
  44205. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  44206. */
  44207. this.overloadedReflectionIntensity = 0.0;
  44208. /**
  44209. * Debug Control allowing to overload the microsurface.
  44210. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  44211. */
  44212. this.overloadedMicroSurface = 0.0;
  44213. /**
  44214. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  44215. */
  44216. this.overloadedMicroSurfaceIntensity = 0.0;
  44217. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  44218. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44219. /**
  44220. * AKA Diffuse Color in other nomenclature.
  44221. */
  44222. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44223. /**
  44224. * AKA Specular Color in other nomenclature.
  44225. */
  44226. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44227. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  44228. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44229. /**
  44230. * AKA Glossiness in other nomenclature.
  44231. */
  44232. this.microSurface = 0.9;
  44233. /**
  44234. * source material index of refraction (IOR)' / 'destination material IOR.
  44235. */
  44236. this.indexOfRefraction = 0.66;
  44237. /**
  44238. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44239. */
  44240. this.invertRefractionY = false;
  44241. /**
  44242. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44243. * Materials half opaque for instance using refraction could benefit from this control.
  44244. */
  44245. this.linkRefractionWithTransparency = false;
  44246. /**
  44247. * The emissive and albedo are linked to never be more than one (Energy conservation).
  44248. */
  44249. this.linkEmissiveWithAlbedo = false;
  44250. this.useLightmapAsShadowmap = false;
  44251. /**
  44252. * In this mode, the emissive informtaion will always be added to the lighting once.
  44253. * A light for instance can be thought as emissive.
  44254. */
  44255. this.useEmissiveAsIllumination = false;
  44256. /**
  44257. * Secifies that the alpha is coming form the albedo channel alpha channel.
  44258. */
  44259. this.useAlphaFromAlbedoTexture = false;
  44260. /**
  44261. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44262. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44263. */
  44264. this.useSpecularOverAlpha = true;
  44265. /**
  44266. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44267. */
  44268. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44269. /**
  44270. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44271. * The material will try to infer what glossiness each pixel should be.
  44272. */
  44273. this.useAutoMicroSurfaceFromReflectivityMap = false;
  44274. /**
  44275. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  44276. * the creation of the material.
  44277. */
  44278. this.useScalarInLinearSpace = false;
  44279. /**
  44280. * BJS is using an harcoded light falloff based on a manually sets up range.
  44281. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44282. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44283. */
  44284. this.usePhysicalLightFalloff = true;
  44285. /**
  44286. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44287. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44288. */
  44289. this.useRadianceOverAlpha = true;
  44290. /**
  44291. * Allows using the bump map in parallax mode.
  44292. */
  44293. this.useParallax = false;
  44294. /**
  44295. * Allows using the bump map in parallax occlusion mode.
  44296. */
  44297. this.useParallaxOcclusion = false;
  44298. /**
  44299. * Controls the scale bias of the parallax mode.
  44300. */
  44301. this.parallaxScaleBias = 0.05;
  44302. this.disableLighting = false;
  44303. this._renderTargets = new BABYLON.SmartArray(16);
  44304. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44305. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44306. this._tempColor = new BABYLON.Color3();
  44307. this._defines = new PBRMaterialDefines();
  44308. this._cachedDefines = new PBRMaterialDefines();
  44309. this._myScene = null;
  44310. this._myShadowGenerator = null;
  44311. this._cachedDefines.BonesPerMesh = -1;
  44312. this.getRenderTargetTextures = function () {
  44313. _this._renderTargets.reset();
  44314. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  44315. _this._renderTargets.push(_this.reflectionTexture);
  44316. }
  44317. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  44318. _this._renderTargets.push(_this.refractionTexture);
  44319. }
  44320. return _this._renderTargets;
  44321. };
  44322. }
  44323. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  44324. get: function () {
  44325. return this._useLogarithmicDepth;
  44326. },
  44327. set: function (value) {
  44328. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44329. },
  44330. enumerable: true,
  44331. configurable: true
  44332. });
  44333. PBRMaterial.prototype.needAlphaBlending = function () {
  44334. if (this.linkRefractionWithTransparency) {
  44335. return false;
  44336. }
  44337. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  44338. };
  44339. PBRMaterial.prototype.needAlphaTesting = function () {
  44340. if (this.linkRefractionWithTransparency) {
  44341. return false;
  44342. }
  44343. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  44344. };
  44345. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44346. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  44347. };
  44348. PBRMaterial.prototype.getAlphaTestTexture = function () {
  44349. return this.albedoTexture;
  44350. };
  44351. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44352. if (!mesh) {
  44353. return true;
  44354. }
  44355. if (this._defines.INSTANCES !== useInstances) {
  44356. return false;
  44357. }
  44358. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  44359. return true;
  44360. }
  44361. return false;
  44362. };
  44363. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  44364. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  44365. };
  44366. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  44367. if (!useScalarInLinear) {
  44368. color.toLinearSpaceToRef(ref);
  44369. }
  44370. else {
  44371. ref.r = color.r;
  44372. ref.g = color.g;
  44373. ref.b = color.b;
  44374. }
  44375. };
  44376. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  44377. var lightIndex = 0;
  44378. var depthValuesAlreadySet = false;
  44379. for (var index = 0; index < scene.lights.length; index++) {
  44380. var light = scene.lights[index];
  44381. if (!light.isEnabled()) {
  44382. continue;
  44383. }
  44384. if (!light.canAffectMesh(mesh)) {
  44385. continue;
  44386. }
  44387. this._lightRadiuses[lightIndex] = light.radius;
  44388. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  44389. // GAMMA CORRECTION.
  44390. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  44391. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  44392. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  44393. if (defines["SPECULARTERM"]) {
  44394. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  44395. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  44396. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  44397. }
  44398. // Shadows
  44399. if (scene.shadowsEnabled) {
  44400. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  44401. }
  44402. lightIndex++;
  44403. if (lightIndex === maxSimultaneousLights)
  44404. break;
  44405. }
  44406. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  44407. };
  44408. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  44409. if (this.checkReadyOnlyOnce) {
  44410. if (this._wasPreviouslyReady) {
  44411. return true;
  44412. }
  44413. }
  44414. var scene = this.getScene();
  44415. if (!this.checkReadyOnEveryCall) {
  44416. if (this._renderId === scene.getRenderId()) {
  44417. if (this._checkCache(scene, mesh, useInstances)) {
  44418. return true;
  44419. }
  44420. }
  44421. }
  44422. var engine = scene.getEngine();
  44423. var needNormals = false;
  44424. var needUVs = false;
  44425. this._defines.reset();
  44426. if (scene.texturesEnabled) {
  44427. // Textures
  44428. if (scene.texturesEnabled) {
  44429. if (scene.getEngine().getCaps().textureLOD) {
  44430. this._defines.LODBASEDMICROSFURACE = true;
  44431. }
  44432. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44433. if (!this.albedoTexture.isReady()) {
  44434. return false;
  44435. }
  44436. else {
  44437. needUVs = true;
  44438. this._defines.ALBEDO = true;
  44439. }
  44440. }
  44441. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44442. if (!this.ambientTexture.isReady()) {
  44443. return false;
  44444. }
  44445. else {
  44446. needUVs = true;
  44447. this._defines.AMBIENT = true;
  44448. }
  44449. }
  44450. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44451. if (!this.opacityTexture.isReady()) {
  44452. return false;
  44453. }
  44454. else {
  44455. needUVs = true;
  44456. this._defines.OPACITY = true;
  44457. if (this.opacityTexture.getAlphaFromRGB) {
  44458. this._defines.OPACITYRGB = true;
  44459. }
  44460. }
  44461. }
  44462. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44463. if (!this.reflectionTexture.isReady()) {
  44464. return false;
  44465. }
  44466. else {
  44467. needNormals = true;
  44468. this._defines.REFLECTION = true;
  44469. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44470. this._defines.INVERTCUBICMAP = true;
  44471. }
  44472. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  44473. switch (this.reflectionTexture.coordinatesMode) {
  44474. case BABYLON.Texture.CUBIC_MODE:
  44475. case BABYLON.Texture.INVCUBIC_MODE:
  44476. this._defines.REFLECTIONMAP_CUBIC = true;
  44477. break;
  44478. case BABYLON.Texture.EXPLICIT_MODE:
  44479. this._defines.REFLECTIONMAP_EXPLICIT = true;
  44480. break;
  44481. case BABYLON.Texture.PLANAR_MODE:
  44482. this._defines.REFLECTIONMAP_PLANAR = true;
  44483. break;
  44484. case BABYLON.Texture.PROJECTION_MODE:
  44485. this._defines.REFLECTIONMAP_PROJECTION = true;
  44486. break;
  44487. case BABYLON.Texture.SKYBOX_MODE:
  44488. this._defines.REFLECTIONMAP_SKYBOX = true;
  44489. break;
  44490. case BABYLON.Texture.SPHERICAL_MODE:
  44491. this._defines.REFLECTIONMAP_SPHERICAL = true;
  44492. break;
  44493. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44494. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44495. break;
  44496. }
  44497. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  44498. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  44499. needNormals = true;
  44500. if (this.reflectionTexture.isPMREM) {
  44501. this._defines.USEPMREMREFLECTION = true;
  44502. }
  44503. }
  44504. }
  44505. }
  44506. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44507. if (!this.lightmapTexture.isReady()) {
  44508. return false;
  44509. }
  44510. else {
  44511. needUVs = true;
  44512. this._defines.LIGHTMAP = true;
  44513. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  44514. }
  44515. }
  44516. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44517. if (!this.emissiveTexture.isReady()) {
  44518. return false;
  44519. }
  44520. else {
  44521. needUVs = true;
  44522. this._defines.EMISSIVE = true;
  44523. }
  44524. }
  44525. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44526. if (!this.reflectivityTexture.isReady()) {
  44527. return false;
  44528. }
  44529. else {
  44530. needUVs = true;
  44531. this._defines.REFLECTIVITY = true;
  44532. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  44533. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  44534. }
  44535. }
  44536. }
  44537. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44538. if (!this.bumpTexture.isReady()) {
  44539. return false;
  44540. }
  44541. else {
  44542. needUVs = true;
  44543. this._defines.BUMP = true;
  44544. if (this.useParallax) {
  44545. this._defines.PARALLAX = true;
  44546. if (this.useParallaxOcclusion) {
  44547. this._defines.PARALLAXOCCLUSION = true;
  44548. }
  44549. }
  44550. }
  44551. }
  44552. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44553. if (!this.refractionTexture.isReady()) {
  44554. return false;
  44555. }
  44556. else {
  44557. needUVs = true;
  44558. this._defines.REFRACTION = true;
  44559. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  44560. if (this.linkRefractionWithTransparency) {
  44561. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44562. }
  44563. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  44564. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  44565. if (this.refractionTexture.isPMREM) {
  44566. this._defines.USEPMREMREFRACTION = true;
  44567. }
  44568. }
  44569. }
  44570. }
  44571. }
  44572. // Effect
  44573. if (scene.clipPlane) {
  44574. this._defines.CLIPPLANE = true;
  44575. }
  44576. if (engine.getAlphaTesting()) {
  44577. this._defines.ALPHATEST = true;
  44578. }
  44579. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44580. this._defines.ALPHAFROMALBEDO = true;
  44581. }
  44582. if (this.useEmissiveAsIllumination) {
  44583. this._defines.EMISSIVEASILLUMINATION = true;
  44584. }
  44585. if (this.linkEmissiveWithAlbedo) {
  44586. this._defines.LINKEMISSIVEWITHALBEDO = true;
  44587. }
  44588. if (this.useLogarithmicDepth) {
  44589. this._defines.LOGARITHMICDEPTH = true;
  44590. }
  44591. if (this.cameraContrast != 1) {
  44592. this._defines.CAMERACONTRAST = true;
  44593. }
  44594. if (this.cameraExposure != 1) {
  44595. this._defines.CAMERATONEMAP = true;
  44596. }
  44597. if (this.overloadedShadeIntensity != 1 ||
  44598. this.overloadedShadowIntensity != 1) {
  44599. this._defines.OVERLOADEDSHADOWVALUES = true;
  44600. }
  44601. if (this.overloadedMicroSurfaceIntensity > 0 ||
  44602. this.overloadedEmissiveIntensity > 0 ||
  44603. this.overloadedReflectivityIntensity > 0 ||
  44604. this.overloadedAlbedoIntensity > 0 ||
  44605. this.overloadedAmbientIntensity > 0 ||
  44606. this.overloadedReflectionIntensity > 0) {
  44607. this._defines.OVERLOADEDVALUES = true;
  44608. }
  44609. // Point size
  44610. if (this.pointsCloud || scene.forcePointsCloud) {
  44611. this._defines.POINTSIZE = true;
  44612. }
  44613. // Fog
  44614. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44615. this._defines.FOG = true;
  44616. }
  44617. if (scene.lightsEnabled && !this.disableLighting) {
  44618. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  44619. }
  44620. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44621. // Fresnel
  44622. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  44623. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44624. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44625. this._defines.OPACITYFRESNEL = true;
  44626. }
  44627. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44628. this._defines.EMISSIVEFRESNEL = true;
  44629. }
  44630. needNormals = true;
  44631. this._defines.FRESNEL = true;
  44632. }
  44633. }
  44634. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  44635. this._defines.SPECULAROVERALPHA = true;
  44636. }
  44637. if (this.usePhysicalLightFalloff) {
  44638. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  44639. }
  44640. if (this.useRadianceOverAlpha) {
  44641. this._defines.RADIANCEOVERALPHA = true;
  44642. }
  44643. // Attribs
  44644. if (mesh) {
  44645. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44646. this._defines.NORMAL = true;
  44647. }
  44648. if (needUVs) {
  44649. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44650. this._defines.UV1 = true;
  44651. }
  44652. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44653. this._defines.UV2 = true;
  44654. }
  44655. }
  44656. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  44657. this._defines.VERTEXCOLOR = true;
  44658. if (mesh.hasVertexAlpha) {
  44659. this._defines.VERTEXALPHA = true;
  44660. }
  44661. }
  44662. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44663. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  44664. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  44665. }
  44666. // Instances
  44667. if (useInstances) {
  44668. this._defines.INSTANCES = true;
  44669. }
  44670. }
  44671. // Get correct effect
  44672. if (!this._defines.isEqual(this._cachedDefines)) {
  44673. this._defines.cloneTo(this._cachedDefines);
  44674. scene.resetCachedMaterial();
  44675. // Fallbacks
  44676. var fallbacks = new BABYLON.EffectFallbacks();
  44677. if (this._defines.REFLECTION) {
  44678. fallbacks.addFallback(0, "REFLECTION");
  44679. }
  44680. if (this._defines.REFRACTION) {
  44681. fallbacks.addFallback(0, "REFRACTION");
  44682. }
  44683. if (this._defines.REFLECTIVITY) {
  44684. fallbacks.addFallback(0, "REFLECTIVITY");
  44685. }
  44686. if (this._defines.BUMP) {
  44687. fallbacks.addFallback(0, "BUMP");
  44688. }
  44689. if (this._defines.PARALLAX) {
  44690. fallbacks.addFallback(1, "PARALLAX");
  44691. }
  44692. if (this._defines.PARALLAXOCCLUSION) {
  44693. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44694. }
  44695. if (this._defines.SPECULAROVERALPHA) {
  44696. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44697. }
  44698. if (this._defines.FOG) {
  44699. fallbacks.addFallback(1, "FOG");
  44700. }
  44701. if (this._defines.POINTSIZE) {
  44702. fallbacks.addFallback(0, "POINTSIZE");
  44703. }
  44704. if (this._defines.LOGARITHMICDEPTH) {
  44705. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44706. }
  44707. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  44708. if (this._defines.SPECULARTERM) {
  44709. fallbacks.addFallback(0, "SPECULARTERM");
  44710. }
  44711. if (this._defines.OPACITYFRESNEL) {
  44712. fallbacks.addFallback(1, "OPACITYFRESNEL");
  44713. }
  44714. if (this._defines.EMISSIVEFRESNEL) {
  44715. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  44716. }
  44717. if (this._defines.FRESNEL) {
  44718. fallbacks.addFallback(3, "FRESNEL");
  44719. }
  44720. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  44721. fallbacks.addCPUSkinningFallback(0, mesh);
  44722. }
  44723. //Attributes
  44724. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44725. if (this._defines.NORMAL) {
  44726. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44727. }
  44728. if (this._defines.UV1) {
  44729. attribs.push(BABYLON.VertexBuffer.UVKind);
  44730. }
  44731. if (this._defines.UV2) {
  44732. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44733. }
  44734. if (this._defines.VERTEXCOLOR) {
  44735. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44736. }
  44737. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  44738. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  44739. // Legacy browser patch
  44740. var shaderName = "pbr";
  44741. if (!scene.getEngine().getCaps().standardDerivatives) {
  44742. shaderName = "legacypbr";
  44743. }
  44744. var join = this._defines.toString();
  44745. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44746. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  44747. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  44748. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  44749. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  44750. "vFogInfos", "vFogColor", "pointSize",
  44751. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44752. "mBones",
  44753. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44754. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  44755. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  44756. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  44757. "logarithmicDepthConstant",
  44758. "vSphericalX", "vSphericalY", "vSphericalZ",
  44759. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44760. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44761. "vMicrosurfaceTextureLods", "vLightRadiuses"
  44762. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  44763. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  44764. ], join, fallbacks, this.onCompiled, this.onError);
  44765. }
  44766. if (!this._effect.isReady()) {
  44767. return false;
  44768. }
  44769. this._renderId = scene.getRenderId();
  44770. this._wasPreviouslyReady = true;
  44771. if (mesh) {
  44772. if (!mesh._materialDefines) {
  44773. mesh._materialDefines = new PBRMaterialDefines();
  44774. }
  44775. this._defines.cloneTo(mesh._materialDefines);
  44776. }
  44777. return true;
  44778. };
  44779. PBRMaterial.prototype.unbind = function () {
  44780. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  44781. this._effect.setTexture("reflection2DSampler", null);
  44782. }
  44783. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  44784. this._effect.setTexture("refraction2DSampler", null);
  44785. }
  44786. _super.prototype.unbind.call(this);
  44787. };
  44788. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44789. this._effect.setMatrix("world", world);
  44790. };
  44791. PBRMaterial.prototype.bind = function (world, mesh) {
  44792. this._myScene = this.getScene();
  44793. // Matrices
  44794. this.bindOnlyWorldMatrix(world);
  44795. // Bones
  44796. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44797. if (this._myScene.getCachedMaterial() !== this) {
  44798. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  44799. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44800. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44801. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44802. }
  44803. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44804. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44805. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44806. }
  44807. }
  44808. // Textures
  44809. if (this._myScene.texturesEnabled) {
  44810. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44811. this._effect.setTexture("albedoSampler", this.albedoTexture);
  44812. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  44813. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  44814. }
  44815. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44816. this._effect.setTexture("ambientSampler", this.ambientTexture);
  44817. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  44818. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  44819. }
  44820. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44821. this._effect.setTexture("opacitySampler", this.opacityTexture);
  44822. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  44823. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  44824. }
  44825. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44826. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  44827. if (this.reflectionTexture.isCube) {
  44828. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  44829. }
  44830. else {
  44831. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  44832. }
  44833. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  44834. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  44835. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  44836. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  44837. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  44838. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  44839. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  44840. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  44841. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  44842. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  44843. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  44844. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  44845. }
  44846. }
  44847. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44848. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  44849. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  44850. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  44851. }
  44852. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44853. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  44854. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  44855. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  44856. }
  44857. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44858. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  44859. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  44860. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  44861. }
  44862. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44863. this._effect.setTexture("bumpSampler", this.bumpTexture);
  44864. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  44865. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  44866. }
  44867. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44868. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  44869. var depth = 1.0;
  44870. if (this.refractionTexture.isCube) {
  44871. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  44872. }
  44873. else {
  44874. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  44875. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  44876. if (this.refractionTexture.depth) {
  44877. depth = this.refractionTexture.depth;
  44878. }
  44879. }
  44880. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44881. }
  44882. if ((this.reflectionTexture || this.refractionTexture)) {
  44883. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  44884. }
  44885. }
  44886. // Clip plane
  44887. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  44888. // Point size
  44889. if (this.pointsCloud) {
  44890. this._effect.setFloat("pointSize", this.pointSize);
  44891. }
  44892. // Colors
  44893. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44894. // GAMMA CORRECTION.
  44895. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  44896. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  44897. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44898. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  44899. // GAMMA CORRECTION.
  44900. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  44901. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  44902. // GAMMA CORRECTION.
  44903. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  44904. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  44905. }
  44906. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  44907. // GAMMA CORRECTION.
  44908. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  44909. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  44910. // Lights
  44911. if (this._myScene.lightsEnabled && !this.disableLighting) {
  44912. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  44913. }
  44914. // View
  44915. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  44916. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  44917. }
  44918. // Fog
  44919. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  44920. this._lightingInfos.x = this.directIntensity;
  44921. this._lightingInfos.y = this.emissiveIntensity;
  44922. this._lightingInfos.z = this.environmentIntensity;
  44923. this._lightingInfos.w = this.specularIntensity;
  44924. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  44925. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  44926. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  44927. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  44928. this._cameraInfos.x = this.cameraExposure;
  44929. this._cameraInfos.y = this.cameraContrast;
  44930. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  44931. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  44932. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  44933. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  44934. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  44935. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  44936. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  44937. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  44938. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  44939. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  44940. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  44941. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  44942. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  44943. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  44944. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  44945. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  44946. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  44947. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  44948. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  44949. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  44950. // Log. depth
  44951. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  44952. }
  44953. _super.prototype.bind.call(this, world, mesh);
  44954. this._myScene = null;
  44955. };
  44956. PBRMaterial.prototype.getAnimatables = function () {
  44957. var results = [];
  44958. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  44959. results.push(this.albedoTexture);
  44960. }
  44961. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  44962. results.push(this.ambientTexture);
  44963. }
  44964. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  44965. results.push(this.opacityTexture);
  44966. }
  44967. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  44968. results.push(this.reflectionTexture);
  44969. }
  44970. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  44971. results.push(this.emissiveTexture);
  44972. }
  44973. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  44974. results.push(this.reflectivityTexture);
  44975. }
  44976. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  44977. results.push(this.bumpTexture);
  44978. }
  44979. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  44980. results.push(this.lightmapTexture);
  44981. }
  44982. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  44983. results.push(this.refractionTexture);
  44984. }
  44985. return results;
  44986. };
  44987. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  44988. if (this.albedoTexture) {
  44989. this.albedoTexture.dispose();
  44990. }
  44991. if (this.ambientTexture) {
  44992. this.ambientTexture.dispose();
  44993. }
  44994. if (this.opacityTexture) {
  44995. this.opacityTexture.dispose();
  44996. }
  44997. if (this.reflectionTexture) {
  44998. this.reflectionTexture.dispose();
  44999. }
  45000. if (this.emissiveTexture) {
  45001. this.emissiveTexture.dispose();
  45002. }
  45003. if (this.reflectivityTexture) {
  45004. this.reflectivityTexture.dispose();
  45005. }
  45006. if (this.bumpTexture) {
  45007. this.bumpTexture.dispose();
  45008. }
  45009. if (this.lightmapTexture) {
  45010. this.lightmapTexture.dispose();
  45011. }
  45012. if (this.refractionTexture) {
  45013. this.refractionTexture.dispose();
  45014. }
  45015. _super.prototype.dispose.call(this, forceDisposeEffect);
  45016. };
  45017. PBRMaterial.prototype.clone = function (name) {
  45018. var _this = this;
  45019. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45020. };
  45021. PBRMaterial.prototype.serialize = function () {
  45022. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45023. serializationObject.customType = "BABYLON.PBRMaterial";
  45024. return serializationObject;
  45025. };
  45026. // Statics
  45027. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45028. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45029. };
  45030. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45031. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45032. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45033. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45034. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45035. __decorate([
  45036. BABYLON.serialize()
  45037. ], PBRMaterial.prototype, "directIntensity", void 0);
  45038. __decorate([
  45039. BABYLON.serialize()
  45040. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45041. __decorate([
  45042. BABYLON.serialize()
  45043. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45044. __decorate([
  45045. BABYLON.serialize()
  45046. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45047. __decorate([
  45048. BABYLON.serialize()
  45049. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45050. __decorate([
  45051. BABYLON.serialize()
  45052. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45053. __decorate([
  45054. BABYLON.serialize()
  45055. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45056. __decorate([
  45057. BABYLON.serialize()
  45058. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45059. __decorate([
  45060. BABYLON.serialize()
  45061. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45062. __decorate([
  45063. BABYLON.serializeAsColor3()
  45064. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45065. __decorate([
  45066. BABYLON.serialize()
  45067. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45068. __decorate([
  45069. BABYLON.serializeAsColor3()
  45070. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45071. __decorate([
  45072. BABYLON.serialize()
  45073. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45074. __decorate([
  45075. BABYLON.serializeAsColor3()
  45076. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45077. __decorate([
  45078. BABYLON.serialize()
  45079. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45080. __decorate([
  45081. BABYLON.serializeAsColor3()
  45082. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45083. __decorate([
  45084. BABYLON.serialize()
  45085. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45086. __decorate([
  45087. BABYLON.serializeAsColor3()
  45088. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45089. __decorate([
  45090. BABYLON.serialize()
  45091. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45092. __decorate([
  45093. BABYLON.serialize()
  45094. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45095. __decorate([
  45096. BABYLON.serialize()
  45097. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45098. __decorate([
  45099. BABYLON.serializeAsTexture()
  45100. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45101. __decorate([
  45102. BABYLON.serializeAsTexture()
  45103. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45104. __decorate([
  45105. BABYLON.serializeAsTexture()
  45106. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45107. __decorate([
  45108. BABYLON.serializeAsTexture()
  45109. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45110. __decorate([
  45111. BABYLON.serializeAsTexture()
  45112. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45113. __decorate([
  45114. BABYLON.serializeAsTexture()
  45115. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45116. __decorate([
  45117. BABYLON.serializeAsTexture()
  45118. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45119. __decorate([
  45120. BABYLON.serializeAsTexture()
  45121. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45122. __decorate([
  45123. BABYLON.serializeAsTexture()
  45124. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45125. __decorate([
  45126. BABYLON.serializeAsColor3("ambient")
  45127. ], PBRMaterial.prototype, "ambientColor", void 0);
  45128. __decorate([
  45129. BABYLON.serializeAsColor3("albedo")
  45130. ], PBRMaterial.prototype, "albedoColor", void 0);
  45131. __decorate([
  45132. BABYLON.serializeAsColor3("reflectivity")
  45133. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45134. __decorate([
  45135. BABYLON.serializeAsColor3("reflection")
  45136. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45137. __decorate([
  45138. BABYLON.serializeAsColor3("emissive")
  45139. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45140. __decorate([
  45141. BABYLON.serialize()
  45142. ], PBRMaterial.prototype, "microSurface", void 0);
  45143. __decorate([
  45144. BABYLON.serialize()
  45145. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45146. __decorate([
  45147. BABYLON.serialize()
  45148. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45149. __decorate([
  45150. BABYLON.serializeAsFresnelParameters()
  45151. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45152. __decorate([
  45153. BABYLON.serializeAsFresnelParameters()
  45154. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45155. __decorate([
  45156. BABYLON.serialize()
  45157. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45158. __decorate([
  45159. BABYLON.serialize()
  45160. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45161. __decorate([
  45162. BABYLON.serialize()
  45163. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45164. __decorate([
  45165. BABYLON.serialize()
  45166. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45167. __decorate([
  45168. BABYLON.serialize()
  45169. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45170. __decorate([
  45171. BABYLON.serialize()
  45172. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45173. __decorate([
  45174. BABYLON.serialize()
  45175. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45176. __decorate([
  45177. BABYLON.serialize()
  45178. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45179. __decorate([
  45180. BABYLON.serialize()
  45181. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  45182. __decorate([
  45183. BABYLON.serialize()
  45184. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45185. __decorate([
  45186. BABYLON.serialize()
  45187. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45188. __decorate([
  45189. BABYLON.serialize()
  45190. ], PBRMaterial.prototype, "useParallax", void 0);
  45191. __decorate([
  45192. BABYLON.serialize()
  45193. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45194. __decorate([
  45195. BABYLON.serialize()
  45196. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45197. __decorate([
  45198. BABYLON.serialize()
  45199. ], PBRMaterial.prototype, "disableLighting", void 0);
  45200. __decorate([
  45201. BABYLON.serialize()
  45202. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  45203. return PBRMaterial;
  45204. }(BABYLON.Material));
  45205. BABYLON.PBRMaterial = PBRMaterial;
  45206. })(BABYLON || (BABYLON = {}));
  45207. 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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[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 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]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[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]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[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;\nuniform vec4 vLightRadiuses;\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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\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\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]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\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\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;\nuniform vec4 vLightRadiuses;\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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\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\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]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\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 (microSurface>0.5)\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 (microSurface>0.5)\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#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\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;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"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}","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}","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}"};
  45208. 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;\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\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\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","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 range,float roughness,float NdotV,float lightRadius,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,range);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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 range,float roughness,float NdotV,float lightRadius,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,range);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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,float lightRadius,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,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,vLightRadiuses[{X}],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,vLightRadiuses[{X}],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"};
  45209. 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.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.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.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=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,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.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 h(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,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,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=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.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],F=_.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))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,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=p,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.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.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,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.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=h;var a=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,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.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],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+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.decompose=function(n,r,o){o.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,a=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=a*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 h.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.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);\ni.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){h.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){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,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 h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=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.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=a.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],u=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,u,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=u;var m=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=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(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=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(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=c;var p=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=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=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=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=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 x(e,h,a),m=u.angle.radians()/s;u.orientation===f.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,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),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=z;var w=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=w;var v=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=v;var d=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=d;var g=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=g;var T=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=T;var R=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=R;var _=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 h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  45210. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  45211. module.exports = BABYLON;
  45212. };